ethereum - 在 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
解决方案
推荐阅读
- asp.net-core - 如何解决“无法创建'ApplicationDbContext'类型的对象。”?
- reactjs - 在地图功能中使用地图时如何将删除ID传递给API
- ubuntu - SSH 从主机上的一个虚拟机连接到另一台主机上的另一台机器
- python - 如何在 apache nifi 的 ExecuteScript 处理器中编写 pythoncode?
- linux - shell脚本“测试”命令
- ios - 在未连接到 Internet 时将 base64 转换为图像
- r - 在r中处理时间序列中的缺失值
- visual-studio-extensions - 处理 Visual Studio 扩展中的停止调试按钮和全部分离按钮
- java - 格式化浮点值时,语言会发生变化
- c# - 错误 CS0117(“调试”不包含“日志”的定义)