Skip to content

Instantly share code, notes, and snippets.

@tuncatunc
Last active July 29, 2022 06:43
Show Gist options
  • Save tuncatunc/92a827da7e09f7cc9db131a326f96fc5 to your computer and use it in GitHub Desktop.
Save tuncatunc/92a827da7e09f7cc9db131a326f96fc5 to your computer and use it in GitHub Desktop.
Pancakeswap Swap Extact B tokens for ETH
// Sells B for BNB from pancakeswap for address ${targetAccounts[targetIndex].address}
var fs = require('fs')
var Tx = require('ethereumjs-tx').Transaction;
var Web3 = require('web3')
var Common = require('ethereumjs-common').default;
const ankrlRpcUrl = 'https://rpc.ankr.com/bsc/';
var web3 = new Web3(new Web3.providers.HttpProvider(ankrlRpcUrl))
var BSC_FORK = Common.forCustomChain(
'mainnet',
{
name: 'Binance Smart Chain Mainnet',
networkId: 56,
chainId: 56,
url: ankrlRpcUrl
},
'istanbul',
);
var targetAccounts = [
{
"i": 0,
"address": "0x9d2AC5E8A1460204D05F035ce92892fd86C489C2",
"privateKey": "reducted"
},
]
sellMulty();
async function sellMulty() {
for (var i = 0; i < 1; i++) {
var targetAccount = targetAccounts[i];
var bAmount = 10000000; // Amount you want to sell
const bAmountInWei = web3.utils.toWei(bAmount.toString(), 'ether')
console.log(`${i}: Selling ${bAmount} B for BNB to pancakeswap for address ${targetAccount.address}`);
var res = sellB(targetAccount, bAmountInWei)
.catch(e => {
console.error("Error in sell:", e);
process.exit(1);
});
console.log(res);
await sleep(5000 + Math.random().toFixed(4) * 10000);
}
}
async function sellB(targetAccount, amount) {
var amountToSell = web3.utils.toHex(amount);
var privateKey = Buffer.from(targetAccount.privateKey.slice(2), 'hex');
var abiArray = JSON.parse(JSON.parse(fs.readFileSync('beast-abi.json', 'utf-8')));
var tokenAddress = '0xD96710E8419242A14D59Fe0295B0144aF66fB983'; // B contract address
var WBNBAddress = '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c'; // WBNB token address
var pancakeSwapRouterAddress = '0x10ed43c718714eb63d5aa57b78b54704e256024e';
// Approve B spend
var bContract = new web3.eth.Contract(abiArray, tokenAddress, { from: targetAccount.address });
var approveBSpendData = bContract.methods.approve(pancakeSwapRouterAddress, web3.utils.toWei('1', 'ether'));
var count = await web3.eth.getTransactionCount(targetAccount.address, 'pending');
var rawTransactionApprove = {
"from": targetAccount.address,
"gasPrice": web3.utils.toHex(5000000000),
"gasLimit": web3.utils.toHex(210000),
"to": tokenAddress,
"value": "0x0",
"data": approveBSpendData.encodeABI(),
"nonce": web3.utils.toHex(count)
};
var transactionApprove = new Tx(rawTransactionApprove, { 'common': BSC_FORK });
transactionApprove.sign(privateKey)
var resultApprove = await web3.eth.sendSignedTransaction('0x' + transactionApprove.serialize().toString('hex'));
console.log("Approved" + resultApprove);
var amountOutMin = 0; // Allow any slippage
var routerAbi = JSON.parse(fs.readFileSync('pancake-router-abi.json', 'utf-8'));
var contract = new web3.eth.Contract(routerAbi, pancakeSwapRouterAddress, { from: targetAccount.address });
// var data = contract.methods.swapExactTokensForETHSupportingFeeOnTransferTokens(
// amountToSell,
// amountOutMin,
// [tokenAddress,
// '0xe9e7cea3dedca5984780bafc599bd69add087d56' /* BUSD address */, // Add this if you want to go through the onlyone-busd pair
// WBNBAddress],
// targetAccount.address,
// web3.utils.toHex(Math.round(Date.now()/1000)+60*20),
// );
var data = contract.methods.swapExactTokensForETH(
amountToSell,
amountOutMin,
[tokenAddress,
WBNBAddress],
targetAccount.address,
web3.utils.toHex(Math.round(Date.now() / 1000) + 60 * 20),
);
count = await web3.eth.getTransactionCount(targetAccount.address);
var rawTransaction = {
"from": targetAccount.address,
"gasPrice": web3.utils.toHex(5000000000),
"gasLimit": web3.utils.toHex(190830),
"to": pancakeSwapRouterAddress,
"value": web3.utils.toHex(0),
"data": data.encodeABI(),
"nonce": web3.utils.toHex(count)
};
var transaction = new Tx(rawTransaction, { 'common': BSC_FORK });
transaction.sign(privateKey);
var result = await web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'));
console.log(result)
return result;
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
@tuncatunc
Copy link
Author

tuncatunc commented Jul 29, 2022

I’ve fixed that however there is another problem I need to talk What’s your email?

@coderguy1998
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment