DEV Community

rahuldev-17
rahuldev-17

Posted on

How to buy a token programmatically

If you want to buy a token on Binance Smart Chain (BSC) via a script, we present a complete program. You can use the script easily for other EVM compatible blockchains just by modifying the addresses for:

  1. native coin
  2. router and factory
  3. desired token address

MOST IMPORTANT: USE AN ACCOUNT WITH JUST NOMINAL VALUE OF BNB SUCH AS 0.01 BNB WHICH YOU CAN AFFORD TO LOSE. I cannot overemphasis it.

Assuming you have experience with basic nodejs programming, and you have installed 'metamask' wallet, and know the seed phrase, here are the steps to buy a token programmatically:

  1. Create a project folder
  2. create a .env file in your project folder
  3. Write your private information in the .env file; do not enclose info in ""; save the file
  4. create another file in the same project folder, and copy paste the 'buyToken.js' script
  5. Put the token address you want to purchase for in this file.
  6. execute the script

I have not handled 'returned promise rejections' in this program. If it is your first purchase of the token, do import the token in 'metamask' if not done beforehand, otherwise you might not see the token in your account.

'.env' file:

MNEMONIC=
MY_ACCOUNT_ADDRESS=
GET_BLOCK_API_KEY=
Enter fullscreen mode Exit fullscreen mode

'buyToken.js' script:

const ethers = require('ethers');
require('dotenv').config()

const addresses = {
    WBNB: "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c",// native coin
    router:"0x10ED43C718714eb63d5aA57B78B54704E256024E", // PCS router
    recipient: process.env.MY_ACCOUNT_ADDRESS, //metamask acccount address
    tokenAddress:"" // token address you are interested in 
}


const mnemonic = process.env.MNEMONIC // seed phrase for Metamask 
const mygasPrice = ethers.utils.parseUnits('10', 'gwei');// setting gas price


const provider = new ethers.providers.WebSocketProvider("wss://bsc.getblock.io/testnet/?api_key=" + process.env.GET_BLOCK_API_KEY);
const wallet = ethers.Wallet.fromMnemonic(mnemonic);
const account = wallet.connect(provider);

var amount; 

const router = new ethers.Contract(
  addresses.router,
  [
  'function swapExactTokensForETH(uint256 amountIn, uint256 amountOutMin, address[] path, address to, uint256 deadline)',
      'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)     external     payable     returns (uint[] memory amounts)',
    'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)'

  ],
  account
);


  const buy = async () => {

  let tokenIn = addresses.WBNB , tokenOut = addresses.tokenAddress;

  const amountIn = ethers.utils.parseUnits('0.0001', 'ether'); // Most Important.. swapping only 0.0001 BNB, change this value if desired
  const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
  // accepting a little lower amount 
  const amountOutMin = amounts[1].sub(amounts[1].div(10));

  // to be used later while selling : amount = amountOutMin;

  console.log(`
    Buying new token
    =================
    tokenIn: ${amountIn} ${tokenIn} (WBNB)
    tokenOut: ${amountOutMin} ${tokenOut}
  `);

   const tx = await router.swapExactETHForTokens( 
    amountOutMin,
    [tokenIn, tokenOut],
    addresses.recipient,
    Math.floor(Date.now() / 1000) + 60 * 15, // 15 minutes from the current Unix time
    {
        gasPrice: mygasPrice,
        gasLimit: 270000, 
        value: amountIn // important for exact ethereum amount
    },

  );
  const receipt = await tx.wait(); 
  console.log('Transaction receipt');
  console.log(receipt); 
}
buy();

Enter fullscreen mode Exit fullscreen mode

Hope you find this useful. If so, give love and share.

Top comments (0)