Плохая цена на блиныJavascript

Форум по Javascript
Ответить
Anonymous
 Плохая цена на блины

Сообщение Anonymous »

Скорость транзакции всегда меньше, чем ожидалось. То же самое происходит, когда я покупаю с WBNB - тариф все еще не так хороша, как следовало бы. < /P>
Что я делаю не так? Сначала я делаю транзакцию одобрения, за которым следует своп. Пожалуйста, помогите! < /P>
import { ethers } from "ethers";

const privateKey = "...";

const provider = new ethers.JsonRpcProvider("https://bsc-dataseed.binance.org/");
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();


Подробнее здесь: https://stackoverflow.com/questions/794 ... ancakeswap
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»