Olayiwola Ayoola
Olayiwola Ayoola

Reputation: 11

How to build a crypto trading bot

I'm new to web3 programming and all. So, I've been trying to. build a trading bot. I am testing using goerli testnet.

Here is my code.


const ethers = require('ethers');

const addresses = {
  WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
  router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
  recipient: '0x...',
  // Add the contract address of the token you want to trade
  tokenToBuy: '0x...', // Replace with the actual contract address
};

const privateKey = '0x0...';
const provider = new ethers.providers.WebSocketProvider('wss://goerli.infura.io/ws/v3/...');

const wallet = new ethers.Wallet(privateKey, provider);
const account = wallet.connect(provider);

const router = new ethers.Contract(
  addresses.router,
  [
    'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
    'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
  ],
  account
);

// Specify the token you want to buy
const tokenIn = addresses.WETH; // You are buying with WETH
const tokenOut = addresses.tokenToBuy;

async function buyToken() {

  const gasPrice = await provider.getGasPrice();

  const amountIn = ethers.utils.parseUnits('0.02', 'ether');
  const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
  const amountOutMin = amounts[1].sub(amounts[1].div(10));

  console.log(`
    Buying existing token
    =====================
    tokenIn: ${amountIn.toString()} ${tokenIn} (WETH)
    tokenOut: ${amountOutMin.toString()} ${tokenOut}
  `);


  const tx = await router.swapExactTokensForTokens(
    amountIn,
    amountOutMin,
    [tokenIn, tokenOut],
    addresses.recipient,
    Date.now() + 1000 * 60 * 10,
    {
      gasPrice: gasPrice,
      gasLimit: 30000, 
    },
  );

  const receipt = await tx.wait();
  console.log('Transaction receipt');
  console.log(receipt);
}

// Call the function to execute the trade
buyToken();

I get this error when I run it

Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"code":-32000,"response":"{"jsonrpc":"2.0","id":3,"error":{"code":-32000,"message":"execution reverted"}}"}, method="call", transaction={"from":"0x...","to":"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D","data":"0xd06ca61f00000000000000000000000000000000000000000000000000470de4df82000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000002000000000000000000000000...000000000000000000000000a......"}, code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.0.24) at Logger.makeError (.../uniswap-bot/node_modules/@ethersproject/logger/lib/index.js:180:21) at Logger.throwError (...uniswap-bot/node_modules/@ethersproject/logger/lib/index.js:189:20) at checkError (...uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:107:16) at WebSocketProvider. (...uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:523:47) at step (.../uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:48:23) at Object.throw (...uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:29:53) at rejected (.../uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:21:65) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { reason: 'cannot estimate gas; transaction may fail or may require manual gas limit', code: 'UNPREDICTABLE_GAS_LIMIT', error: Error: execution reverted at WebSocketProvider._this._websocket.onmessage (.../uniswap-bot/node_modules/@ethersproject/providers/lib/websocket-provider.js:123:33) at WebSocket.onMessage (.../uniswap-bot/node_modules/ws/lib/event-target.js:120:16) at WebSocket.emit (node:events:514:28) at Receiver.receiverOnMessage (.../uniswap-bot/node_modules/ws/lib/websocket.js:801:20) at Receiver.emit (node:events:514:28) at Receiver.dataMessage (.../uniswap-bot/node_modules/ws/lib/receiver.js:436:14) at Receiver.getData (.../uniswap-bot/node_modules/ws/lib/receiver.js:366:17) at Receiver.startLoop (.../uniswap-bot/node_modules/ws/lib/receiver.js:142:22) at Receiver._write (.../uniswap-bot/node_modules/ws/lib/receiver.js:77:10) at writeOrBuffer (node:internal/streams/writable:392:12) { code: -32000, response: '{"jsonrpc":"2.0","id":3,"error":{"code":-32000,"message":"execution reverted"}}' }, method: 'call', transaction: { from: '0x6B9AC3A905897F153484A801005017f8206F7567', to: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', data: '0xd06ca61f00000000000000000000000000000000000000000000000000470de4df82000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000002000000000000000000000000...2000000000000000000000000a...' } }

Can anyone tell what's wrong?

I've tried different gasLimits

Upvotes: 0

Views: 366

Answers (1)

I saw your code.

You are using swapExactTokensForTokens function and input token is WETH. If you choose WETH for buying specific tokens, you can use another function swapExactETHForTokens.

Mostly, gas estimation error is related to bad function calls.

If you need extra help, I can guide this.

This is code piece of my trading bot

const sendBuyTxn = async (
  wallet,
  token,
  nonce,
  minimumBuyOutAmount,
  bnbValue
) => {
  let ABI = [
    "function swapExactETHForTokensSupportingFeeOnTransferTokens(uint amountOutMin,address[] calldata path,address to,uint deadline)",
  ];

  let iface = new ethers.utils.Interface(ABI);
  const deadLine = Math.floor(Date.now() / 1000) + 60 * 20; // within 20 minutes
  let buyPayload = iface.encodeFunctionData(
    "swapExactETHForTokensSupportingFeeOnTransferTokens",
    [minimumBuyOutAmount, [TOKEN.WBNB, token], wallet.address, deadLine]
  );

  let buyTxnData = {
    from: wallet.address,
    to: CONTRACT.UNISWAPV2ROUTER,
    data: buyPayload,
    chainId: CHAINID,
    gasLimit: BUYGASLIMIT,
    gasPrice: ethers.utils.parseUnits(GASPRICE, "gwei"),
    nonce: nonce,
    value: bnbValue,
  };

  let txnReceipt;
  try {
    console.log("INFO : SEND BUY TXN DATA :", buyTxnData);
    const signedTxn = await wallet.signTransaction(buyTxnData);
    const txn = await wssProvider.sendTransaction(signedTxn);

    txnReceipt = await txn.wait();
  } 

Upvotes: 0

Related Questions