swapExactETHForTokens method

Future<String> swapExactETHForTokens(
  1. String credentials,
  2. num tokenAmount,
  3. String tokenOut,
  4. String recipient,
  5. int timestamp,
)

Implementation

Future<String> swapExactETHForTokens(String credentials, num tokenAmount,
    String tokenOut, String recipient, int timestamp) async {
  try {
    final String rpc =
        'https://api.bitstack.com/v1/wNFxbiJyQsSeLrX8RRCHi7NpRxrlErZk/DjShIqLishPCTB9HiMkPHXjUM9CNM9Na/ETH/mainnet';
    final String eth = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
    final amountOutMin = convertToBigInt(tokenAmount);
    final List path = [
      EthereumAddress.fromHex(eth),
      EthereumAddress.fromHex(tokenOut)
    ];
    final EthereumAddress to = EthereumAddress.fromHex(recipient);
    final BigInt deadline = BigInt.from(timestamp);
    final Web3Client provider = Web3Client(rpc, Client());
    final EthereumAddress routerAddress =
        EthereumAddress.fromHex('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D');
    final ContractAbi routerAbi = ContractAbi.fromJson(abi, 'Router');
    final DeployedContract routerContract =
        DeployedContract(routerAbi, routerAddress);
    final function = routerContract.function('swapExactETHForTokens');
    final BigInt payableAmount =
        await getAmountsOut(token: tokenOut, val: tokenAmount);
    print('Running: swapExactETHForTokens');
    final result = await provider.sendTransaction(
      EthPrivateKey.fromHex(credentials),
      Transaction.callContract(
        contract: routerContract,
        function: function,
        parameters: [
          amountOutMin,
          path,
          to,
          deadline,
        ],
        value: EtherAmount.inWei(payableAmount),
      ),
      chainId: 1,
    );
    print('Success: swapExactETHForTokens');
    return result;
  } catch (err) {
    print(err);
    throw Exception(err);
  }
}