> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lfg.rich/llms.txt
> Use this file to discover all available pages before exploring further.

# Developer Examples

> Practical API examples for reading LFG.RICH tokens, trades, candles, portfolio data, protocol config, and user state.

This page is for the public REST API. For direct contract calls, use the Protocol Examples page.

<CardGroup cols={2}>
  <Card title="Protocol Contract Examples" icon="code" href="/en/developers/protocol-examples">
    V5 Ethers, Viem, Web3.js, and Python Web3.py examples for estimates, buys, sells, borrowing, borrowMore, and repayment.
  </Card>

  <Card title="Contract Reference" icon="braces" href="/en/developers/contracts">
    V5 addresses and readable ABI string arrays.
  </Card>

  <Card title="Public API Reference" icon="server" href="/en/developers/api">
    Endpoint overview for token lists, token details, config, trades, candles, portfolio, and user data.
  </Card>
</CardGroup>

## Base URL

```txt theme={null}
https://lfg.rich/api/bsc/tokens
```

All examples assume this response shape:

```js theme={null}
{
  "success": true,
  "data": "...",
  "total": 123,
  "page": 1,
  "limit": 20
}
```

When `success` is `false`, inspect `error`.

## Fetch latest tokens

```js theme={null}
const res = await fetch('https://lfg.rich/api/bsc/tokens?sort=latest&page=1&limit=20');
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch latest tokens');

console.log(json.data);
```

## Fetch top volume, active, or gainers

```js theme={null}
const sorts = ['volume', 'active', 'gainers', 'latest'];

for (const sort of sorts) {
  const res = await fetch(`https://lfg.rich/api/bsc/tokens?sort=${sort}&page=1&limit=20`);
  const json = await res.json();
  console.log(sort, json.data);
}
```

## Search tokens

```js theme={null}
const query = 'bull';

const res = await fetch(
  `https://lfg.rich/api/bsc/tokens?search=${encodeURIComponent(query)}&page=1&limit=20`
);
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Search failed');

console.log(json.data);
```

Search matches token name, symbol, or token address.

## Fetch only verified tokens

```js theme={null}
const res = await fetch('https://lfg.rich/api/bsc/tokens?verified=true&page=1&limit=20');
const json = await res.json();

console.log(json.data);
```

Each token includes `is_verified` when the backend joins the token with the verified-token table.

## Fetch a token detail

```js theme={null}
const tokenAddress = '0x29Ede1E1254419Fe5a3c803fC2b015042075A49A';

const res = await fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}`);
const json = await res.json();

if (!json.success || !json.data) throw new Error('Token not found');

console.log(json.data.pool_id);
console.log(json.data.current_price);
console.log(json.data.floor_price);
```

<Info>
  The `pool_id` field is important for V5. Use it for Hook reads and estimates. If it is missing in an external integration, resolve it with `hook.tokenToPoolId(tokenAddress)`.
</Info>

## Fetch a token and its trades

```js theme={null}
const tokenAddress = '0x29Ede1E1254419Fe5a3c803fC2b015042075A49A';

const [tokenRes, tradesRes] = await Promise.all([
  fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}`),
  fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}/trades?page=1&limit=50`)
]);

const token = await tokenRes.json();
const trades = await tradesRes.json();

if (!token.success) throw new Error('Token request failed');
if (!trades.success) throw new Error('Trades request failed');

console.log(token.data);
console.log(trades.data);
```

Trades can include:

```txt theme={null}
buy
sell
borrow
borrowmore
repay
```

## Fetch candles

```js theme={null}
const tokenAddress = '0x29Ede1E1254419Fe5a3c803fC2b015042075A49A';

const res = await fetch(
  `https://lfg.rich/api/bsc/tokens/${tokenAddress}/candles?interval=5m&limit=100`
);
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch candles');

console.log(json.data);
console.log(json.floorData);
```

Common intervals used by the site:

```txt theme={null}
1m
5m
1h
1d
```

## Refresh token data after a trade

The app triggers a backend sync after a wallet action, then fetches the token, trades, and candles again.

```js theme={null}
async function refreshTokenAfterTrade(tokenAddress, interval = '5m') {
  fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}/sync`, {
    method: 'POST'
  }).catch(() => {});

  const [tokenRes, tradesRes, candlesRes] = await Promise.all([
    fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}?_nocache=1`),
    fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}/trades?page=1&limit=50`),
    fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}/candles?interval=${interval}`)
  ]);

  return {
    token: await tokenRes.json(),
    trades: await tradesRes.json(),
    candles: await candlesRes.json()
  };
}
```

## Fetch protocol contract config

```js theme={null}
const res = await fetch('https://lfg.rich/api/bsc/tokens/config/contracts');
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch contracts config');

console.log(json.data.factoryAddress);
console.log(json.data.hookAddress);
console.log(json.data.swapRouterAddress);
console.log(json.data.referralAddress);
console.log(json.data.treasuryAddress);
console.log(json.data.poolManagerAddress);
console.log(json.data.abiVersion);
console.log(json.data.factoryABI);
```

This route returns human-readable ABI string arrays.

## Fetch JSON ABI config

```js theme={null}
const res = await fetch('https://lfg.rich/api/bsc/tokens/jsonconfig/contracts');
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch JSON ABI config');

console.log(json.data.hookABI);
```

Use this only when your tool requires canonical JSON ABI objects.

## Fetch native BNB price

```js theme={null}
const res = await fetch('https://lfg.rich/api/bsc/tokens/config/native-price');
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch native price');

console.log(json.data.nativeUsdPrice);
```

## Fetch creator tokens

```js theme={null}
const creator = '0xYourWalletAddress';

const res = await fetch(`https://lfg.rich/api/bsc/tokens/creator/${creator}`);
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch creator tokens');

console.log(json.data);
```

## Fetch portfolio holdings

```js theme={null}
const wallet = '0xYourWalletAddress';

const res = await fetch(`https://lfg.rich/api/bsc/tokens/portfolio/${wallet}`);
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch portfolio');

console.log(json.data);
```

The portfolio endpoint reads current token balances and combines them with trade history to calculate holding stats.

## Fetch portfolio borrow positions

```js theme={null}
const wallet = '0xYourWalletAddress';

const res = await fetch(`https://lfg.rich/api/bsc/tokens/portfolio/${wallet}/borrows`);
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch borrow portfolio');

console.log(json.data);
```

## Fetch user token and BNB balances

```js theme={null}
const tokenAddress = '0x29Ede1E1254419Fe5a3c803fC2b015042075A49A';
const wallet = '0xYourWalletAddress';

const res = await fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}/user-data/${wallet}`);
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch user data');

console.log(json.data.tokenBalance);
console.log(json.data.ethBalance);
```

## Fetch user borrow data for a token

```js theme={null}
const tokenAddress = '0x29Ede1E1254419Fe5a3c803fC2b015042075A49A';
const wallet = '0xYourWalletAddress';

const tokenRes = await fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}`);
const tokenJson = await tokenRes.json();
const poolId = tokenJson.data.pool_id || tokenJson.data.poolId;

const borrowRes = await fetch(
  `https://lfg.rich/api/bsc/tokens/${tokenAddress}/borrow-data/${wallet}?poolId=${poolId}`
);
const borrowJson = await borrowRes.json();

if (!borrowJson.success) throw new Error(borrowJson.error || 'Failed to fetch borrow data');

console.log(borrowJson.data.borrowedETH);
console.log(borrowJson.data.collateralBalance);
console.log(borrowJson.data.borrowMoreEstimate);
```

## Fetch token roles for a wallet

```js theme={null}
const tokenAddress = '0x29Ede1E1254419Fe5a3c803fC2b015042075A49A';
const wallet = '0xYourWalletAddress';

const res = await fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}/roles/${wallet}`);
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch roles');

console.log(json.data.isCreator);
console.log(json.data.isFactoryOwner);
console.log(json.data.factoryBalance);
```

## Fetch owner data

```js theme={null}
const wallet = '0xOwnerWalletAddress';

const res = await fetch(`https://lfg.rich/api/bsc/tokens/config/owner-data/${wallet}`);
const json = await res.json();

if (!json.success) throw new Error(json.error || 'Failed to fetch owner data');

console.log(json.data.isOwner);
console.log(json.data.factoryBalance);
console.log(json.data.treasuryBalance);
console.log(json.data.treasuryRecipient);
```

## API + contract example: quote from API token data

This is useful for bots and dashboards that use the API for discovery, then use contracts for exact quote data.

```js theme={null}
import { ethers } from 'ethers';

async function quoteTokenBuy(tokenAddress, bnbAmount, walletAddress) {
  const [cfgJson, tokenJson] = await Promise.all([
    fetch('https://lfg.rich/api/bsc/tokens/config/contracts').then(r => r.json()),
    fetch(`https://lfg.rich/api/bsc/tokens/${tokenAddress}`).then(r => r.json())
  ]);

  const cfg = cfgJson.data;
  const token = tokenJson.data;

  const provider = new ethers.providers.JsonRpcProvider(cfg.rpcUrl);
  const hook = new ethers.Contract(cfg.hookAddress, cfg.hookABI, provider);

  const poolId = token.pool_id || token.poolId || await hook.tokenToPoolId(tokenAddress);
  const ethWei = ethers.utils.parseEther(bnbAmount);

  const quote = await hook.estimateBuy(
    poolId,
    ethWei,
    walletAddress || ethers.constants.AddressZero
  );

  return {
    poolId,
    tokensOut: quote.tokensOut.toString(),
    totalFee: quote.platformFee.add(quote.inviterFee || 0).toString()
  };
}
```

## Defensive fetch helper

```js theme={null}
async function lfgFetch(url, options) {
  const res = await fetch(url, options);
  const json = await res.json().catch(() => null);

  if (!res.ok || !json || json.success === false) {
    throw new Error(json?.error || `Request failed: ${res.status}`);
  }

  return json;
}
```
