getTransactionInfo method

Future<EVMTransactionInfo> getTransactionInfo({
  1. required String from,
  2. String? to,
  3. String? data,
  4. double? amountInEth,
})

Implementation

Future<EVMTransactionInfo> getTransactionInfo({
  required String from,
  String? to,
  String? data,
  double? amountInEth,
}) async {
  try {
    final nonceRequest = await networkClient.postHTTP('', {
      'jsonrpc': '2.0',
      'id': 'dontcare',
      'method': 'eth_getTransactionCount',
      'params': [from, 'latest']
    });
    if (!nonceRequest.isSuccess) throw Exception('Nonce request error');

    final nonce = convertHexToDecimal(
      nonceRequest.data['result'].toString().substring(2),
    );

    final gasRequest = await networkClient.postHTTP('', {
      "jsonrpc": "2.0",
      "id": "dontcare",
      "method": "eth_gasPrice",
      "params": [],
    });

    if (!gasRequest.isSuccess) throw Exception('Gas request error');

    final gasPrice = convertHexToDecimal(
      gasRequest.data['result'].toString().substring(2),
    );

    int? maxPriorityFeePerGas;

    await networkClient.postHTTP('', {
      "jsonrpc": "2.0",
      "id": "dontcare",
      "method": "eth_maxPriorityFeePerGas",
      "params": [],
    }).then(
      (maxPriorityFeePerGasRequest) {
        if (maxPriorityFeePerGasRequest.isSuccess) {
          maxPriorityFeePerGas = convertHexToDecimal(
            maxPriorityFeePerGasRequest.data['result']
                .toString()
                .substring(2),
          );
        }
      },
    ).onError((error, stackTrace) {
      log("Legacy transaction will be used");
    });

    late int gasLimit;

    if (data != null) {
      final gasLimitRequest = await networkClient.postHTTP('', {
        "jsonrpc": "2.0",
        "method": "eth_estimateGas",
        "params": [
          {
            "from": from,
            "to": to,
            "data": data,
            if (amountInEth != null)
              "value": "0x" +
                  EthereumFormater.convertEthToWei(amountInEth)
                      .toRadixString(16),
          }
        ],
        "id": "dontcare"
      });

      if (!gasLimitRequest.isSuccess) {
        throw Exception('Gas limit request error');
      }

      if (gasLimitRequest.data['error'] != null) {
        throw Exception(gasLimitRequest.data['error']['message']);
      }

      gasLimit = convertHexToDecimal(
        gasLimitRequest.data['result'].toString().substring(2),
      );
    } else {
      gasLimit = 21000;
    }

    return EVMTransactionInfo(
      nonce: nonce,
      gasPrice: gasPrice,
      maxPriorityFeePerGas: maxPriorityFeePerGas,
      gasLimit: gasLimit,
    );
  } catch (err) {
    rethrow;
  }
}