How to sell a token programmatically
Tags: bsc, etherjs, token, sell
Published: 2022-01-05 18:27:14


If you want to sell 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
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.**

I assume that you have experience with basic nodejs programming, and you have installed 'metamask' wallet, and know the seed phrase of your wallet. Further, assuming you already have purchased the token(to purchase token programmatically read this https://dev.to/rahuldev17/how-to-buy-a-token-programmatically-3plb ), here are the steps to sell 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 'sellToken.js' script
5. Put the token address you want to sell for in this file.
6. execute the script
7. I have not handled 'returned promise rejections' in this program. 

If it is your first time of selling of this token, do approve the token for swapping via 'metamask' if not done beforehand, otherwise you might not be able to sell the token.

'.env' file:

```
MNEMONIC=
MY_ACCOUNT_ADDRESS=
GET_BLOCK_API_KEY=
```
'sellToken.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 sell = async () => {
    
  
    let tokenIn = addresses.tokenAddress , tokenOut = addresses.WBNB;
  
    const amountIn = ethers.utils.parseUnits("1.0",9); //selling one token with 9 decimals; change decimals to 18 if desired
    const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
    //let us be ready to accept little less of BNB due to price fluctuations
    const amountOutMin = amounts[1].sub(amounts[1].div(10));
  
    console.log(`
      selling new token
      =================
      tokenIn: ${amountIn} ${tokenIn}
      tokenOut: ${amountOutMin} ${tokenOut} (WBNB)
    `);
  
    const tx = await router.swapExactTokensForETH(
      amountIn,
      amountOutMin,
      [tokenIn, tokenOut],
      addresses.recipient,
      Math.floor(Date.now() / 1000) + 60 * 15, // 15 minutes from the current Unix time
      {
          gasPrice: mygasPrice,
          gasLimit: 250000
      }
    );
    
    const receipt = await tx.wait(); 
    console.log('Transaction receipt');
    console.log(receipt);
  }

sell();


```

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