'ethers.js swapExactETHForTokens and swapExactTokensForTokens on pancake swap
I'm, having trouble with the following code and I can't buy on pancake swap. I get the following errors depending on which function i call swapExactETHForTokens or swapExactTokensForTokens:
https://bscscan.com/tx/0x18285588819662c93543dba5650d4471e62a504900b9a089f09dea4970698352
https://bscscan.com/tx/0x38ae19f6b677f072a82ac7c5528d445d3fc45288b1004f205d479edffee97b2f
Here is the code i'm using:
const ethers = require('ethers')
require('dotenv').config({ path: __dirname + '/./../../.env' })
const config = {
wbnb: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',
safemoon: '0x8076c74c5e3f5852037f31ff0093eeb8c8add8d3',
pancakeSwapRouter: '0x10ed43c718714eb63d5aa57b78b54704e256024e',
slippage: 12,
}
const provider = new ethers.providers.WebSocketProvider(
'wss://bsc-ws-node.nariox.org:443'
)
const wallet = new ethers.Wallet.fromMnemonic(process.env.MNEMONIC)
const account = wallet.connect(provider)
const pancakeswap = new ethers.Contract(
config.pancakeSwapRouter,
[
'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)',
'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)',
],
account
)
const wbnb = new ethers.Contract(
config.wbnb,
['function approve(address spender, uint amount) public returns(bool)'],
account
)
const buyToken = async () => {
try {
const deadline = Math.floor(Date.now() / 1000) + 60 * 20
const tokenIn = config.wbnb
const tokenOut = config.safemoon
const amountIn = ethers.utils.parseUnits('0.001', 'ether')
const amounts = await pancakeswap.getAmountsOut(amountIn, [
tokenIn,
tokenOut,
])
const amountOutMin = amounts[1].sub(amounts[1].div(`${config.slippage}`))
console.log(`
Buying new token
tokenIn: ${amountIn} ${tokenIn} (WBNB)
tokenOut: ${amountOutMin} ${tokenOut}
`)
// const tx = await pancakeswap.swapExactTokensForTokens(
// amountIn,
// amountOutMin,
// [tokenIn, tokenOut],
// account.address,
// deadline,
// {
// gasPrice: provider.getGasPrice(),
// gasLimit: 100000,
// }
// )
const tx = await pancakeswap.swapExactETHForTokens(
amountOutMin,
[tokenIn, tokenOut],
account.address,
deadline,
{
gasPrice: provider.getGasPrice(),
gasLimit: 100000,
}
)
const receipt = await tx.wait()
console.log('buyToken receipt')
console.log(receipt)
} catch (error) {
console.log(error)
}
}
const approve = async () => {
const valueToapprove = ethers.utils.parseUnits('0.01', 'ether')
const tx = await wbnb.approve(pancakeswap.address, valueToapprove, {
gasPrice: provider.getGasPrice(),
gasLimit: 100000,
})
console.log('Approving...')
const receipt = await tx.wait()
console.log('Approve receipt')
console.log(receipt)
}
const main = async () => {
await approve()
await buyToken()
process.exit()
}
main()
The approve works, but I can't figure out what's going wrong with the swapExactTokensForTokens or swapExactETHForTokens. Is calling approve required? Doesn't seem to help either way. Thanks for your input.
Solution 1:[1]
Just use swapExactETHForTokens and try to add some value in the options.
const token = "Your token";
const amountIn = ethers.utils.parseUnits("0.0001", 'ether');
await approve(amountIn);
const amounts = await router.getAmountsOut(amountIn, [
addresses.WBNB,
token
])
const amountOutMin = amounts[1].sub(amounts[1].div(12))
const tx = await router.swapExactETHForTokens(
0,
[addresses.WBNB, token],
addresses.recipient,
Date.now() + 1000 * 60 * 10,
{
gasPrice: provider.getGasPrice(),
gasLimit: 310000,
value: amountIn
}
);
If it works, don't forget to mark as accepted answer. Thanks (-:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | thegreytangent |
