sendBNB method

  1. @override
Future<String> sendBNB({
  1. required String toAddress,
  2. required String privateKey,
  3. required double amount,
})
override

BNB 전송

Implementation

@override
Future<String> sendBNB({
  required String toAddress,
  required String privateKey,
  required double amount, // BNB 단위
}) async {
  // 개인키로부터 자격증명 생성
  final credentials = EthPrivateKey.fromHex(privateKey);
  final from = await credentials.address;

  // 잔액 확인
  final balance = await _client.getBalance(from);

  // BNB 단위를 Wei로 변환
  final amountInWei = BigInt.from(amount * pow(10, 18));

  final gasFee = await estimateGasFee(
      from: from.hex,
      toAddress: toAddress,
      amount: amount,
      isBEP20: false
  );

  // 총 필요한 금액 (전송액 + 가스비)
  final totalNeeded = amountInWei + gasFee['totalGasFee']!;

  if (balance.getInWei < totalNeeded) {
    double ava = balance.getInWei / BigInt.from(10).pow(18);
    double total = totalNeeded / BigInt.from(10).pow(18);
    // throw Exception('Insufficient balance for transaction + gas');

    throw InsufficientBalanceException(required: total, available: ava);
  }


  // 트랜잭션 생성 및 전송
  final transaction = await _client.sendTransaction(
    credentials,
    Transaction(
      to: EthereumAddress.fromHex(toAddress),
      value: EtherAmount.fromBigInt(EtherUnit.wei, amountInWei),
      gasPrice: EtherAmount.fromBigInt(EtherUnit.wei, gasFee['gasPrice']!),
      maxGas: gasFee['estimatedGas']!.toInt(),
      // gas 설정
      // gasPrice: await _client.getGasPrice(),
      // maxGas: 21000, // 기본 전송의 경우 21000이 표준
    ),
    chainId: chainId, // BSC 메인넷/테스트넷의 Chain ID
  );

  return transaction; // 트랜잭션 해시 반환
}