approve function

Future<bool> approve(
  1. BigInt amount,
  2. String accountAddress,
  3. String tokenContractAddress,
  4. String tokenContractName,
  5. Credentials credentials, {
  6. BigInt? gasLimit,
  7. int? gasPrice,
})

Sends an approve transaction to an ERC 20 contract for a certain amount of tokens

@param {BigInt} amount - Amount of tokens to be approved by the ERC 20 contract @param {String} accountAddress - The Ethereum address of the transaction sender @param {String} contractAddress - The token smart contract address @param {String} providerUrl - Network url (i.e, http://localhost:8545). Optional @param {Object} signerData - Signer data used to build a Signer to send the transaction

@returns {Promise} transaction

Implementation

Future<bool> approve(
    BigInt amount,
    String accountAddress,
    String tokenContractAddress,
    String tokenContractName,
    Credentials credentials,
    {BigInt? gasLimit,
    int? gasPrice}) async {
  EtherAmount ethGasPrice;
  if (gasLimit == null) {
    gasLimit = BigInt.from(GAS_LIMIT_HIGH);
  }
  if (gasPrice == null) {
    ethGasPrice = await HermezSDK.currentWeb3Client!.getGasPrice();
  } else {
    ethGasPrice = EtherAmount.fromUnitAndValue(EtherUnit.wei, gasPrice);
  }

  final contract = await ContractParser.fromAssets(
      'ERC20ABI.json', tokenContractAddress, tokenContractName);

  EthereumAddress from = await credentials.extractAddress();

  try {
    final allowanceCall = await HermezSDK.currentWeb3Client!
        .call(contract: contract, function: _allowance(contract), params: [
      EthereumAddress.fromHex(accountAddress),
      EthereumAddress.fromHex(getCurrentEnvironment()!.contracts['Hermez']!)
    ]);
    final allowance = allowanceCall.first as BigInt;

    if (allowance < amount) {
      final transactionParameters = [
        EthereumAddress.fromHex(getCurrentEnvironment()!.contracts['Hermez']!),
        amount
      ];

      int nonce = await HermezSDK.currentWeb3Client!
          .getTransactionCount(from, atBlock: BlockNum.pending());

      Transaction transaction = Transaction.callContract(
        contract: contract,
        function: _approve(contract),
        parameters: transactionParameters,
        maxGas: gasLimit.toInt(),
        gasPrice: ethGasPrice,
        nonce: nonce,
      );

      String txHash = await HermezSDK.currentWeb3Client!.sendTransaction(
          credentials, transaction,
          chainId: getCurrentEnvironment()!.chainId);

      print(txHash);

      return true;
    } else {
      return true;
    }
  } catch (error, trace) {
    print(error);
    print(trace);
    return false;
  }
}