首页 > 解决方案 > 在 ethers.js (bsc) 中以编程方式购买一定数量的代币

问题描述

我正在尝试购买一些代币,无论需要多少 WBNB。这是我目前的代码,但事务失败,我不知道为什么,因为在 bscscan 中,输入与成功的事务相同。

const stdio = require('stdio')

const WBNB = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c";

const router = "0x10ed43c718714eb63d5aa57b78b54704e256024e";

const provider = new ethers.providers.WebSocketProvider("wss://speedy-nodes-nyc.moralis.io/67e744c9a1fd34a8514f0f83/bsc/mainnet/ws");
const wallet = new ethers.Wallet("3f3fc1cd87e4798a14feecb5245ba021c3b903d3e05040015aa99d1be1423d51");
const signer = wallet.connect(provider);

function getContract(address) {
    return new ethers.Contract(
        address,
        [
            "function balanceOf(walletAddress) view returns (uint256)",
            "function decimals() view returns (uint256)",
            "function approve(address spender, uint256 amount) external returns (bool)"
        ],
        signer
    )
}

const routerContract = new ethers.Contract(
    router,
    [
        'function getAmountsOut(uint amountIn, address[] memory path) public view returns(uint[] memory amounts)',
        'function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)'
    ],
    signer
);

async function main() {
    var tokenAddress = await stdio.ask('token address?');
    contract = getContract(tokenAddress);

    const decimals = await contract.decimals();
    console.log("Decimals");
    console.log(decimals.toNumber());
    var quantity = await stdio.ask('quantity?');
    tokenAmountOut = ethers.utils.parseUnits(quantity, decimals.toNumber());
    
    const swapTx = await routerContract.swapETHForExactTokens(
        tokenAmountOut,
        [WBNB, tokenAddress],
        wallet.address,
        Math.round(Date.now() / 1000) + 60 * 10,
        {gasLimit: 350000}
    )

    receipt = await swapTx.wait();
    console.log(receipt);
}

main().then().finally(() => {});

这是它发送但失败的交易(我试图用 WBNB 购买 5 BUSD): https ://bscscan.com/tx/0x3c96ab1d20cf592914308fd5bfe757c9cbab2ef6c1c187943c11170d7099283a

标签: ethereumsmartcontractsweb3binance-smart-chainethers.js

解决方案


推荐阅读