【问题标题】:swapExactETHForTokens keeps failingswapExactETHForTokens 不断失败
【发布时间】:2021-11-25 13:55:46
【问题描述】:

我遇到了一个我无法解决的问题,我上周一直被这个问题困扰...... 我正在尝试在 ropsten 网络上使用 UNISWAP 路由器执行 swapExactETHForTokens。 我试图用 0.01 ETH 购买 USDC 硬币。 首先,我同意 uniswap 使用 ETH 数量。 其次,我执行了交换功能,但它一直在恢复我的交易。 https://ropsten.etherscan.io/tx/0x176bae743bcc193b776a45b0389bc4934c5d1db5df85d991a37f2faca72db0c2 失败并出现错误“UniswapV2Router:EXPIRED” 这是我的代码:(它在某些地方说 pancakeswap 但它的 uniswap 路由器)

const ethers = require('ethers')
const to = '0xD5768aa815D590494277f558Ee5cbeC5FAF1501C'; // my account
const value = ethers.utils.parseUnits('0.01', 'ether')
let provider = new ethers.providers.InfuraProvider('ropsten', 'key');
const signer = new ethers.Wallet('privte_key');
const account = signer.connect(provider);
const config = {
    wbnb: '0xc778417E063141139Fce010982780140Aa0cD5Ab', //weth
    safemoon: '0x07865c6E87B9F70255377e024ace6630C1Eaa37F', //usdc
    pancakeSwapRouter: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
    slippage: 12,
}

const pancakeswap = new ethers.Contract(
    config.pancakeSwapRouter,
    [
        '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)',
        'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)',
    ],
    account
)

const wbnb = new ethers.Contract(
    config.wbnb,
    ['function approve(address spender, uint amount) public returns(bool)'],
    account
)

const buyToken = async () => {
    try {
        const deadline = Math.floor(Date.now() / 1000) + 60 * 10
        const tokenIn = config.wbnb
        const tokenOut = config.safemoon
        const amountIn = value;
        const ETHAmount = ethers.utils.parseEther('0.1').toHexString();
        const gasPrice = ethers.utils.parseUnits('1.5', 'gwei');
        const gas = {
            gasPrice: gasPrice,
            gasLimit: 6000000
        }
        const tx = await pancakeswap.swapExactETHForTokens(
            0, // Degen ape don't give a fuxk about slippage
            [tokenIn, tokenOut],
            to,
            Math.floor(Date.now() / 1000) + 60 * 20, // 10 minutes from now
            {
                ...gas,
                value: ETHAmount
            }
        );
        console.log(`Swapping WETH for tokens...`);
        const receipt = await tx.wait();
        console.log(`Transaction hash: ${receipt.transactionHash}`);
    } catch (error) {
        console.log(error)
    }
}

const approve = async () => {
    const ETHAmount = ethers.utils.parseEther('0.1').toHexString();
    const gasPrice = ethers.utils.parseUnits('1.5', 'gwei');
    const gas = {
        gasPrice: gasPrice,
        gasLimit: 6000000
    }
    const tx = await wbnb.approve(pancakeswap.address, ETHAmount, gas)
    console.log('Approving...')
    const receipt = await tx.wait()
    console.log('Approve receipt')
    console.log(receipt)
}

const main = async () => {
    await approve()
    await buyToken()
}

main()

【问题讨论】:

    标签: cryptography blockchain solidity swap


    【解决方案1】:

    swapExactETHForTokens()定义

    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
    

    获取第 4 个参数 deadline 并将其传递给 ensure 修饰符

    modifier ensure(uint deadline) {
        require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
        _;
    }
    

    如果deadline(传递给函数的第四个参数)低于阻塞时间,则有效地使用EXPIRED消息恢复交易。

    linked transaction 中,您将1637842091 作为deadline 的值传递,即2021-11-25 12:08:11 UTC。然而,包含交易的区块大约是被开采的。 1.5 小时后 - 2021-11-25 13:48:34 UTCdeadline低于出块时间,导致交易回滚。


    解决方案:要么提供更高的gasPrice,以便交易在10分钟窗口内(在JS sn-p中指定)内被挖掘的概率更高,要么增加deadline的值这样它在区块被挖掘时仍然有效。

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 2022-11-07
      • 2018-09-15
      • 1970-01-01
      • 2015-10-21
      • 2014-07-13
      • 2014-08-07
      • 2018-05-06
      • 2018-12-03
      相关资源
      最近更新 更多