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);
});
}
@MetalGear-cmd
Copy link

Hey,
What error are you seeing?
can you please share the error code.
Thanks

@tuncatunc
Copy link
Author

tuncatunc commented Jul 28, 2022

/opt/homebrew/bin/node ./sell-b-pancakeswap.js
0: Selling 10000000 B for BNB to pancakeswap for address 0x9d2AC5E8A1460204D05F035ce92892fd86C489C2
Promise {[[PromiseState]]: 'pending', [[PromiseResult]]: undefined, Symbol(async_id_symbol): 26, Symbol(trigger_async_id_symbol): 18}
Process exited with code 1
Error in sell: Error: Transaction has been reverted by the EVM:
{
  "blockHash": "0x7a6e0f6f83f4416a99053e52f4f7a699a3a8d9e27c6c0c57eafd01ce94de7240",
  "blockNumber": 19934967,
  "contractAddress": null,
  "cumulativeGasUsed": 11258075,
  "from": "0x9d2ac5e8a1460204d05f035ce92892fd86c489c2",
  "gasUsed": 60227,
  "logs": [],
  "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "status": false,
  "to": "0x10ed43c718714eb63d5aa57b78b54704e256024e",
  "transactionHash": "0xb800d25a112da6594d2f391b23910ed478bd1acfa5fbad4c7ede9ab537125321",
  "transactionIndex": 140,
  "type": "0x0"
}
    at Object.TransactionError (/Users/tuncatunc/git/onlyone/helper-scripts/node_modules/web3-core-helpers/lib/errors.js:87:21)
    at Object.TransactionRevertedWithoutReasonError (/Users/tuncatunc/git/onlyone/helper-scripts/node_modules/web3-core-helpers/lib/errors.js:98:21)
    at /Users/tuncatunc/git/onlyone/helper-scripts/node_modules/web3-core-method/lib/index.js:396:57
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {receipt: {…}, stack: 'Error: Transaction has been reverted by the E…ions (node:internal/process/task_queues:95:5)', message: 'Transaction has been reverted by the EVM:
{
…  "transactionIndex": 140,
  "type": "0x0"
}'}
No debugger available, can not send 'variables'

@coderguy1998
Copy link

Hey I've seen this on UpWork, I can help you with that. You can reach me on my mail.

@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