【发布时间】: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