如何构建加密货币交易机器人

问题描述 投票:0回答:1

我是 web3 编程的新手。所以,我一直在努力。构建一个交易机器人。我正在使用 goerli 测试网进行测试。

这是我的代码。


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();

运行时出现此错误

错误:无法估算gas;交易可能会失败或可能需要手动气体限制(error={"code":-32000,"response":"{"jsonrpc":"2.0","id":3,"error":{"code":- 32000,“消息”:“执行已恢复”}}“},方法=“调用”,交易= {“从”:“0x...”,“到”:“0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D”,“数据”:“0xd06ca61f0000000000000000 0000000000000000000000000000000000470de4df8200000000000000000000000000000000000000000000000000000000000000000004000000000000 000000000000000000000000000000000000000000000000000002000000000000000000000000。 ..000000000000000000000000a......"},代码=UNPREDICTABLE_GAS_LIMIT,版本=providers/5.0.24) 在 Logger.makeError (.../uniswap-bot/node_modules/@ethersproject/logger/lib/index.js:180:21) 在 Logger.throwError (...uniswap-bot/node_modules/@ethersproject/logger/lib/index.js:189:20) 在 checkError (...uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:107:16) 在 WebSocketProvider 处。 (...uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:523:47) 在步骤(.../uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:48:23) 在 Object.throw (...uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:29:53) 被拒绝(.../uniswap-bot/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:21:65) 在 process.processTicksAndRejections (节点:内部/进程/task_queues:95:5){ 原因:'无法估计气体;交易可能会失败或者可能需要手动限制gas', 代码:'UNPREDICTABLE_GAS_LIMIT', 错误:错误:执行已恢复 在 WebSocketProvider._this._websocket.onmessage (.../uniswap-bot/node_modules/@ethersproject/providers/lib/websocket-provider.js:123:33) 在 WebSocket.onMessage (.../uniswap-bot/node_modules/ws/lib/event-target.js:120:16) 在 WebSocket.emit (节点:事件:514:28) 在 Receiver.receiverOnMessage (.../uniswap-bot/node_modules/ws/lib/websocket.js:801:20) 在 Receiver.emit (节点:事件:514:28) 在 Receiver.dataMessage (.../uniswap-bot/node_modules/ws/lib/receiver.js:436:14) 在 Receiver.getData (.../uniswap-bot/node_modules/ws/lib/receiver.js:366:17) 在 Receiver.startLoop (.../uniswap-bot/node_modules/ws/lib/receiver.js:142:22) 在 Receiver._write (.../uniswap-bot/node_modules/ws/lib/receiver.js:77:10) 在writeOrBuffer(节点:内部/流/可写:392:12){ 代码:-32000, 响应:'{“jsonrpc”:“2.0”,“id”:3,“错误”:{“代码”:-32000,“消息”:“执行已恢复”}}' }, 方法:'调用', 交易: { 来自:'0x6B9AC3A905897F153484A801005017f8206F7567', 至:'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 数据:'0xd06ca61f00000000000000000000000000000000000000000000000000470de4df8200000000000000000000000000000000000000000000000000 0000000000000000040000000000000000000000000000000000000000000000000000000000000002000000000000000000000000...20000000000000 000000000000a...' } }

谁能告诉我出了什么问题吗?

我尝试过不同的gasLimits

javascript ethereum web3js ethers.js uniswap
1个回答
0
投票

我看到了你的代码。

您正在使用

swapExactTokensForTokens
功能,输入代币为WETH。 如果您选择WETH购买特定代币,您可以使用另一个功能
swapExactETHForTokens

大多数情况下,gas 估计错误与错误的函数调用有关。

如果您需要额外帮助,我可以指导。

这是我的交易机器人的代码片段

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();
  } 
© www.soinside.com 2019 - 2024. All rights reserved.