最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Bad rate on pancakeswap - Stack Overflow

programmeradmin2浏览0评论

The rate of the transaction is always smaller than expected.

For example, I should be able to buy 7-8 tokens, but I only get 5-6. The same happens when I buy with WBNB — the rate is still not as good as it should be.

What am I doing wrong? I am doing the approval transaction first, followed by the swap.

Do you have any examples or suggestions on how I can do this correctly?

Please help!

import { ethers } from "ethers";

const privateKey = "...";

const provider = new ethers.JsonRpcProvider("/");
const wallet = new ethers.Wallet(privateKey, provider);

const sellContract = "0x55d398326f99059ff775485246999027b3197955";
const buyContract = "0x9840652DC04fb9db2C43853633f0F62BE6f00f98";
const routerAddress = "0x10ED43C718714eb63d5aA57B78B54704E256024E";

const usdtABI = [
    "function balanceOf(address owner) view returns (uint256)",
    "function approve(address spender, uint256 amount) public returns (bool)"
];

const routerABI = [
    "function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)",
    "function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts)"
];

const sellContractInstance = new ethers.Contract(sellContract, usdtABI, wallet);
const routerContract = new ethers.Contract(routerAddress, routerABI, wallet);

const usdtAmount = ethers.parseUnits("1.00", 18);
const toAddress = wallet.address;

async function buyTokens() {
    const normalizedSellContract = ethers.getAddress(sellContract);
    const normalizedBuyAddress = ethers.getAddress(buyContract);
    const path = [normalizedSellContract, normalizedBuyAddress];
    const deadline = Math.floor(Date.now() / 1000) + 600;

    try {
        const usdtBalance = await sellContractInstance.balanceOf(wallet.address);
        console.log('USDT Balance:', ethers.formatUnits(usdtBalance, 18));

        const amountsOut = await routerContract.getAmountsOut(usdtAmount, path);
        const expectedTokens = BigInt(amountsOut[1]);
        console.log(`Ожидаемое количество токенов: ${ethers.formatUnits(expectedTokens, 18)}`);

        const slippageTolerance = 10;
        const amountOutMin = (expectedTokens * BigInt(100 - slippageTolerance)) / BigInt(100);
        console.log(`Минимальное количество токенов с учетом ${slippageTolerance}% slippage: ${ethers.formatUnits(amountOutMin, 18)}`);

        const approvalTx = await sellContractInstance.approve(routerAddress, usdtAmount, {
            gasLimit: 500000,
            gasPrice: ethers.parseUnits("1", "gwei")
        });
        console.log("Approval successful");

        const tx = await routerContract.swapExactTokensForTokens(
            usdtAmount,
            amountOutMin.toString(),
            path,
            toAddress,
            deadline,
            {
                gasLimit: 500000,
                gasPrice: ethers.parseUnits("1", "gwei")
            }
        );
        console.log("Transaction sent, awaiting confirmation...");
        console.log("Transaction confirmed!");
    } catch (error) {
        console.error("Error in buying tokens:", error);
    }
}

buyTokens();
发布评论

评论列表(0)

  1. 暂无评论