Skip to content

Sell a token

Tested on BSC testnet before every release

This is an example. Every value in it (names, amounts, addresses) is there to show you how; change any of them to suit you. It’s sell.mjs, exactly as our tests run it on testnet. Point it at testnet with MM_API, or leave it for mainnet.

sell.mjs
// Sell a token for its pair currency. The first sale of a token needs two
// one-time approvals, which the API hands you as `requires`; after that, every
// sale is one transaction.
// PRIVATE_KEY=0x… TOKEN=0x… AMOUNT=1000 node sell.mjs
import { JsonRpcProvider, Wallet } from 'ethers';
const API = process.env.MM_API ?? 'https://marketmayhem.co/api/v1';
const token = process.env.TOKEN;
const amount = process.env.AMOUNT ?? '1000'; // whole tokens
const settings = await (await fetch(`${API}/settings`)).json();
const rpc = settings.chainId === 56 ? 'https://bsc-dataseed.bnbchain.org' : 'https://bsc-testnet-rpc.publicnode.com';
const wallet = new Wallet(process.env.PRIVATE_KEY, new JsonRpcProvider(rpc, settings.chainId));
async function build(body) {
const res = await fetch(`${API}/build/sell`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
const json = await res.json();
if (!res.ok) throw new Error(`${json.error.code}: ${json.error.message} ${json.error.fix ?? ''}`);
return json;
}
async function send(tx) {
const sent = await wallet.sendTransaction({ to: tx.to, data: tx.data, value: BigInt(tx.value), gasLimit: tx.gas ? BigInt(tx.gas) : undefined });
const receipt = await sent.wait();
if (receipt.status !== 1) throw new Error(`reverted: ${sent.hash}`);
return sent.hash;
}
const request = { wallet: wallet.address, token, amount, slippageBps: 100 };
let built = await build(request);
while (built.requires.length) {
for (const step of built.requires) {
console.log(`one-time step: ${step.explain}`);
await send(step.tx);
}
built = await build(request);
}
console.log(built.explain);
const hash = await send(built.tx);
console.log(`sold: ${hash}`);
console.log('RESULT', JSON.stringify({ hash }));