Documentation

Trading for Agents

Buy and sell Agent tokens on-chain using the TypeScript SDK, CLI, or MCP Server. You hold the private key and sign all transactions locally — fully self-custodied.

Wallet Setup

Use a dedicated trading wallet
Never use your main wallet for automated trading. Export a fresh wallet from MetaMask, fund it with FET and BNB for gas, and keep the private key in a .env file that is excluded from version control.
01

Create a trading wallet

2 min

Open MetaMask, create a new account (not your main account), and copy the address.

02

Export the private key

1 min

In MetaMask: three dots next to account → Account details → Private key → Enter password → Hold to reveal → Copy.

03

Add to .env

30s

Create a .env file in your project root and add WALLET_PRIVATE_KEY. Never commit this file.

04

Fund your wallet

2 min

For mainnet: bridge FET and BNB to BSC. For testnet: message the $GIFT agent on Agentverse with 'claim 0xYourAddress' to receive 200 TFET + 0.005 tBNB.

Environment variables

bash
# .env fileWALLET_PRIVATE_KEY=0xabc123...your_private_key_hereCHAIN_ID=56   # 56=BSC Mainnet, 97=BSC Testnet
bash
# Step 1: Get testnet funds via the $GIFT agent on Agentverse (testnet only)# Message: "claim 0xYourWalletAddress"# Receive: 200 TFET + 0.005 tBNB for gas  (BSC Testnet: chainId=97)
# Step 2: Verify your private key works (dry-run, no wallet needed)npx @fetchai/agent-launch-cli buy 0xF7e2F77f014a5ad3C121b1942968be33BA89e03c \  --amount 10 \  --dry-run
# Step 3: Check your balances# (requires WALLET_PRIVATE_KEY to be set)npx @fetchai/agent-launch-cli status 0xF7e2F77f... --json

Trading Interface

Install ethers peer dependency
On-chain trading requires ethers@^6 as a peer dependency.
bash
npm install @fetchai/agent-launch-sdk ethers@^6

buyTokens()

Automatically checks FET balance, approves spend if needed (with BSC lag handling), calculates slippage protection, submits the transaction, and waits for confirmation.

typescript
import { buyTokens } from '@fetchai/agent-launch-sdk';
// Buy 10 FET worth of tokens on BSC Mainnet
const result = await buyTokens('0xF7e2F77f014a5ad3C121b1942968be33BA89e03c', '10', {
chainId: 56, // BSC Mainnet (56) or BSC Testnet (97)
slippagePercent: 5, // 5% slippage tolerance (default)
});
console.log(`Tx hash: ${result.txHash}`);
console.log(`Received: ${result.tokensReceived} tokens`);
console.log(`Spent: ${result.fetSpent} FET`);
console.log(`Fee: ${result.fee} FET (2% to protocol treasury)`);
console.log(`Impact: ${result.priceImpact}%`);
console.log(`Block: ${result.blockNumber}`);

sellTokens()

No approval step needed for sells. Checks token balance, submits the sell transaction, and waits for confirmation.

typescript
import { sellTokens } from '@fetchai/agent-launch-sdk';
// Sell 50,000 tokens
const result = await sellTokens('0xF7e2F77f014a5ad3C121b1942968be33BA89e03c', '50000', {
chainId: 56,
});
console.log(`Tx hash: ${result.txHash}`);
console.log(`Received: ${result.fetReceived} FET`);
console.log(`Sold: ${result.tokensSold} tokens`);
console.log(`Fee: ${result.fee} FET (2% to protocol treasury)`);
console.log(`Impact: ${result.priceImpact}%`);

getWalletBalances()

Query BNB (gas), FET, and a specific token balance. Useful for pre-trade checks.

typescript
import { getWalletBalances } from '@fetchai/agent-launch-sdk';
const balances = await getWalletBalances('0xF7e2F77f014a5ad3C121b1942968be33BA89e03c', {
chainId: 56,
});
console.log(`Wallet: ${balances.wallet}`);
console.log(`BNB: ${balances.bnb}`); // gas token
console.log(`FET: ${balances.fet}`); // trading token
console.log(`Token: ${balances.token}`); // the specific token queried

Buy flow (internal steps)

1.Connect to BSC via ethers.JsonRpcProvider
2.Read FET address from token contract FET_TOKEN()
3.Check FET balance — throw if insufficient
4.Check FET allowance — approve if insufficient (reset to 0 first if nonzero)
5.Poll allowance up to 5x (BSC nodes can lag)
6.Call calculateBuy() via API to get expected tokens
7.Compute minTokensOut = expected × (100 − slippage) / 100
8.Call buyTokens(wallet.address, minTokensOut, fetAmountWei) on token contract
9.Wait for confirmation → return BuyResult

Security Guidelines

Never do this

  • ×Commit WALLET_PRIVATE_KEY to git
  • ×Use your main/production wallet for automated trading
  • ×Share private keys in Slack, Discord, or any chat
  • ×Log private keys in console output

Best practices

  • Use a dedicated trading wallet separate from your main wallet
  • Store WALLET_PRIVATE_KEY in .env (in .gitignore)
  • Always preview with --dry-run before executing
  • Check balances with getWalletBalances() before trading

Error Handling

typescript
import { buyTokens } from '@fetchai/agent-launch-sdk';
try {
const result = await buyTokens('0xToken...', '10', { chainId: 56 });
console.log('Buy succeeded:', result.txHash);
} catch (err) {
if (err instanceof Error) {
if (err.message.includes('Insufficient FET balance')) {
console.error('Not enough FET — check your wallet balance first');
} else if (err.message.includes('insufficient funds')) {
console.error('Not enough BNB for gas — bridge BNB to BSC Mainnet');
} else if (err.message.includes('slippage')) {
console.error('Price moved too much — try higher slippagePercent');
} else {
console.error('Trade failed:', err.message);
}
}
}

Common errors

Insufficient FET balance

Cause: Wallet has less FET than the amount requested

Fix: Bridge FET to BSC Mainnet or reduce trade amount

insufficient funds for gas

Cause: Not enough BNB for transaction gas

Fix: Bridge BNB to BSC Mainnet (for mainnet) or use the $GIFT agent (for testnet)

slippage / execution reverted

Cause: Price moved more than the slippage tolerance during execution

Fix: Increase slippagePercent (e.g. 10%) or retry later

WALLET_PRIVATE_KEY not set

Cause: Missing environment variable

Fix: Add WALLET_PRIVATE_KEY to your .env file

Trading fee
All buys and sells incur a 2% protocol fee that goes entirely to the protocol treasury. There is no creator fee split. The fee is deducted from the trade amount — the values returned in fee and netFetSpent reflect this.

Build your first AI agent in 5 minutes

Create, deploy, and tokenize — all from your terminal.