How to swap tokens on PancakeSwap using Nethereum.Web3

189 Views Asked by At

I want to write a swapping processor to be able to swap tokens on different Dexes. But stuck with first - PancakeSwap.

I tried to use swapExactTokensForTokens and swapExactETHForTokens.

But instead of actually swap tokens my code just deploy contract.

My transaction - https://etherscan.io/tx/0x68291f27c4dc9c45031040709141156f1adbb98ad94e90d01e84cd8cc72c2f2c

What I want to achieve (Here I used pancakeswap web site) - https://etherscan.io/tx/0x70eed3fc60939704e605f1b388a815bc125f5a8441acdbbdd93e11464c96428f

My code:

using System.Numerics;
using Nethereum.Hex.HexTypes;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.Web3;
using Nethereum.Web3.Accounts;

public class UniswapV2Router
{
  public async Task SwapExactETHForTokens()
  {
    string privateKey = "my_private_key";
    string ethereumRpcUrl = "https://rpc.ankr.com/eth/xxx";
      
    var account = new Account(privateKey);
    var web3 = new Web3(account,ethereumRpcUrl)
    {
      TransactionManager =
      {
        UseLegacyAsDefault = false, //Using legacy option instead of 1559
      },
    };

    // PancakeSwap router address and ABI
    string routerAddress = "0xEfF92A263d31888d860bD50809A8D171709b7b1c"; // Replace with the correct address
    string routerAbi = await File.ReadAllTextAsync("PancakeSwapAbi.txt");

    var contract = web3.Eth.GetContract(routerAbi,routerAddress);
    var swapFunction = contract.GetFunction("swapExactTokensForTokens");

    string ethAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"; // ETH address
    string usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; // USDC address

    var minUsdcAmountExpected = 1;
    var ethAmount = Web3.Convert.ToWei(0.001);

    var deadline = new BigInteger(DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds());

    var encodedData = swapFunction.GetData(ethAmount,minUsdcAmountExpected,new[] {ethAddress,usdcAddress},account.Address,deadline);

    var transactionInput = new TransactionInput
    {
      From = account.Address,
      Value = new HexBigInteger(ethAmount),
      Data = encodedData,
      Gas = new HexBigInteger(100000),
    };

    var transactionHash = await web3.Eth.TransactionManager.SendTransactionAsync(transactionInput);
  }
}
0

There are 0 best solutions below