Untitled
unknown
plain_text
2 years ago
2.9 kB
6
Indexable
const fs = require('fs'); const ethers = require('ethers'); const { Fetcher, Route, TokenAmount, Trade, TradeType } = require('@trustevm/sdk'); const { Percent } = require('@trustevm/sdk'); const { readPrivateKey } = require('./readPrivateKey'); async function swapTokensforweth(bot, msg, token1, token2, amount, slippage = "50") { const QUICKNODE_HTTP_ENDPOINT = "https://api-testnet.trust.one/" let provider = new ethers.providers.getDefaultProvider(QUICKNODE_HTTP_ENDPOINT) // Router and ABI const UNISWAP_ROUTER_ADDRESS = "0x442F52B4364E4b037EaF9cfF46a6F747314C9c01" const UNISWAP_ROUTER_ABI = fs.readFileSync("swaprouter.abi").toString() const UNISWAP_ROUTER_CONTRACT = new ethers.Contract(UNISWAP_ROUTER_ADDRESS, UNISWAP_ROUTER_ABI, provider) try { const pair = await Fetcher.fetchPairData(token1, token2, provider); const route = await new Route([pair], token1); let amountIn = ethers.utils.parseEther(amount.toString()); amountIn = amountIn.toString() const slippageTolerance = new Percent(slippage, "10000000"); const trade = new Trade( route, new TokenAmount(token1, amountIn), TradeType.EXACT_INPUT ); const chatId = msg.chat.id; const fromId = msg.from.id; const privateKey = readPrivateKey(`./wallets/${fromId}.json`, bot, chatId); const wallet = new ethers.Wallet(privateKey, provider) const amountOutMin = trade.minimumAmountOut(slippageTolerance).raw; const amountOutMinHex = ethers.BigNumber.from(amountOutMin.toString()).toHexString(); const path = [token1.address, token2.address]; const to = wallet.address; const deadline = Math.floor(Date.now() / 1000) + 60 * 20; const value = trade.inputAmount.raw; const valueHex = await ethers.BigNumber.from(value.toString()).toHexString(); console.log("*******************************************************") console.log("amountin:", amountIn, "amountout:", amountOutMinHex,"path:", path, "to", to, "deadline" , deadline ) console.log("*******************************************************") const rawTxn = await UNISWAP_ROUTER_CONTRACT.populateTransaction.swapExactTokensForETH(amountIn, amountOutMinHex, path, to, deadline, ) console.log("RAW RAW RAW RAW:", rawTxn) let sendTxn = (await wallet).sendTransaction(rawTxn) let reciept = (await sendTxn).wait() if (reciept) { console.log(" - Transaction is mined - " + '\n' + "Transaction Hash:", (await sendTxn).hash + '\n' + "Block Number: " + (await reciept).blockNumber + '\n' + "Navigate to https://rinkeby.etherscan.io/txn/" + (await sendTxn).hash, "to see your transaction") return (await sendTxn).hash } else { console.log("Error submitting transaction") } } catch(e) { console.log(e) } } module.exports = { swapTokensforweth }
Editor is loading...