Скорость транзакции всегда меньше, чем ожидалось. То же самое происходит, когда я покупаю с 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
Плохая цена на блины ⇐ Javascript
Форум по Javascript
1740109720
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();
Подробнее здесь: [url]https://stackoverflow.com/questions/79456323/bad-rate-on-pancakeswap[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия