sendBEP20Token method
BEP-20 토큰 전송
Implementation
@override
Future<String> sendBEP20Token({
required String toAddress,
required String privateKey,
required double amount,
}) async {
try {
var contract = DeployedContract(
ContractAbi.fromJson(abiJson, 'blToken'),
EthereumAddress.fromHex(blTokenContract)
);
// 금액을 토큰 단위로 변환
final amountInTokenUnit = BigInt.from(amount * pow(10, 18));
// 자격증명 생성
final credentials = EthPrivateKey.fromHex(privateKey);
final from = credentials.address;
// 토큰 잔액 확인
final balanceFunction = contract.function('balanceOf');
final balanceResult = await _client.call(
contract: contract,
function: balanceFunction,
params: [from]
);
final tokenBalance = balanceResult.first as BigInt;
if (tokenBalance < amountInTokenUnit) {
throw Exception('Insufficient token balance');
}
// 가스비 계산
final gasFee = await estimateGasFee(
from: from.hex,
toAddress: toAddress,
amount: amount,
isBEP20: true
);
// BNB 잔액 확인 (가스비를 위한)
final bnbBalance = await _client.getBalance(from);
if (bnbBalance.getInWei < gasFee['totalGasFee']!) {
throw Exception('Insufficient BNB balance for gas');
}
// transfer 함수 호출
final transferFunction = contract.function('transfer');
final transaction = await _client.sendTransaction(
credentials,
Transaction.callContract(
contract: contract,
function: transferFunction,
parameters: [
EthereumAddress.fromHex(toAddress),
amountInTokenUnit
],
gasPrice: EtherAmount.fromBigInt(EtherUnit.wei, gasFee['gasPrice']!),
maxGas: gasFee['estimatedGas']!.toInt(),
// gasPrice: await _client.getGasPrice(),
// maxGas: 100000, // BEP-20 전송은 일반적으로 더 많은 가스가 필요
),
chainId: chainId,
);
return transaction;
} catch (e) {
throw Exception('Failed to send token: ${e.toString()}');
}
}