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

# TraderCodes

> Referral codes, rewards balance, and rewards transfer

```typescript theme={null}
import { MonacoSDK } from "@0xmonaco/core";

// Get the authenticated user's TraderCode (with custom-handle fields)
await sdk.tradercodes.getMyTraderCode();

// Claim or edit a custom (vanity) handle
await sdk.tradercodes.setTraderCode(code);

// Revert to the wallet-derived default
await sdk.tradercodes.clearTraderCode();

// Advisory check of a handle's availability (public, no auth required)
await sdk.tradercodes.checkTraderCodeAvailability(code);

// Validate a referral code (public, no auth required)
await sdk.tradercodes.getTraderCodeInfo(code);

// Read accrued rewards
await sdk.tradercodes.getRewardsBalance();

// Move rewards into a trading balance
await sdk.tradercodes.transferRewards({ token, amount });
```

For a full integration walkthrough see [TraderCodes](https://docs.0xmonaco.com/developers/tradercodes.md).

***

**getMyTraderCode** `() =\> Promise\<TraderCodeResponse\>`

Return the authenticated caller's TraderCode. The default code is derived from the wallet
address and is created on demand — this method never returns `NOT_FOUND` for a signed-in user.

Requires authentication.

**Returns:** `TraderCodeResponse`:

* `code`: string — the wallet-derived code (normalized lowercase hex address)
* `createdAt`: string — ISO 8601 timestamp of when the code row was first derived
* `customCode`: string — the claimed custom handle as entered, or an empty string when the wallet-derived default is kept
* `isCustom`: boolean — whether a custom handle is currently set
* `display`: string — the string to show users (`Monaco - <address>` for the default, or the custom handle)

**Example:**

```typescript theme={null}
const { code, display, isCustom } = await sdk.tradercodes.getMyTraderCode();
// Render `display` directly; embed `code` in a referral URL: ?ref=<code>
console.log(display, isCustom);
```

**setTraderCode** `(code: string) =\> Promise\<TraderCodeResponse\>`

Claim or edit the caller's custom (vanity) handle. The handle is stored exactly as entered
(casing preserved) but is unique case-insensitively; it must be letter-first, `[A-Za-z0-9_]`,
and 5–20 characters. The SDK validates the handle client-side before sending, but the server
remains the authoritative gate.

Requires authentication.

**Parameters:**

* `code`: string — the desired handle

**Returns:** `TraderCodeResponse` — the updated code, with `isCustom: true` and `customCode` set.

Throws `409` when the handle is already taken (case-insensitive) or is a recently-freed handle
still in cooldown, `422` on validation failure (the error carries a stable reason code), `429`
when handles are edited too frequently, and `403` when custom handles are disabled.

**Example:**

```typescript theme={null}
const { display, isCustom } = await sdk.tradercodes.setTraderCode("acePilot");
console.log(display, isCustom); // "acePilot", true
```

**clearTraderCode** `() =\> Promise\<TraderCodeResponse\>`

Drop the caller's custom handle and revert to the wallet-derived default. Idempotent — clearing
when no handle is set simply returns the default code.

Requires authentication.

**Returns:** `TraderCodeResponse` — the code with `isCustom: false` and an empty `customCode`.

Clearing counts against the same rolling-hour edit limit as `setTraderCode`, so it throws `429`
when edited too frequently and `403` when custom handles are disabled.

**Example:**

```typescript theme={null}
const { display, isCustom } = await sdk.tradercodes.clearTraderCode();
console.log(isCustom); // false
```

**checkTraderCodeAvailability** `(code: string) =\> Promise\<TraderCodeAvailabilityResponse\>`

Public advisory check of whether a custom handle can be claimed. Use it for live feedback in a
claim form; it is not the authoritative gate — `setTraderCode` still validates on the server.

No authentication required. Rate-limited per client (throws `429` once the caller exceeds the
allowance).

**Parameters:**

* `code`: string — the handle to check

**Returns:** `TraderCodeAvailabilityResponse`:

* `available`: boolean — whether the handle can be claimed
* `reason?`: string — present only when unavailable; one of `taken`, `too_short`, `too_long`, `reserved`, `invalid_char`, or `looks_like_address`

**Example:**

```typescript theme={null}
const { available, reason } = await sdk.tradercodes.checkTraderCodeAvailability("acePilot");
if (!available) {
  console.log(`Unavailable: ${reason}`);
}
```

**getTraderCodeInfo** `(code: string) =\> Promise\<TraderCodeInfoResponse\>`

Public lookup for a TraderCode. Accepts a bare wallet address or the `Monaco - <address>`
display form. Use this to validate a referral code before showing a confirmation to the user.

No authentication required.

**Parameters:**

* `code`: string — wallet address or `Monaco - <address>` display form

**Returns:** `TraderCodeInfoResponse`:

* `code`: string — normalized wallet address

Throws `404` when the code does not resolve to a known wallet.

**Example:**

```typescript theme={null}
try {
  const info = await sdk.tradercodes.getTraderCodeInfo("0xabc...");
  console.log(info.code); // normalized address
} catch (err) {
  // 404 — code is not recognized; show a friendly message
}
```

**getRewardsBalance** `() =\> Promise\<GetRewardsBalanceResponse\>`

Return the caller's current rewards-bucket balances across all reward tokens. Rewards accrue
here as referred users trade. Returns an empty `balances` array if no rewards have been earned.

Requires authentication.

**Returns:** `GetRewardsBalanceResponse`:

* `balances`: `RewardsBalanceEntry[]`:
  * `token`: string — reward token contract address (0x-prefixed)
  * `available`: string — raw atomic units (divide by token decimals for display)

**Example:**

```typescript theme={null}
const { balances } = await sdk.tradercodes.getRewardsBalance();

for (const entry of balances) {
  const display = Number(entry.available) / 1e6; // USDC has 6 decimals
  console.log(`${display} USDC available`);
}
```

**transferRewards** `(params: TransferRewardsParams) =\> Promise\<TransferRewardsResponse\>`

Move earned rewards from the rewards bucket into the authenticated application's trading
balance. The transfer is ledger-only — no on-chain transaction, no gas. Funds are available
for trading immediately after the transfer.

Each call spends the per-user [movement budget](https://docs.0xmonaco.com/developers/rate-limits.md) that withdrawals and
collateral transfers share, whatever the rewards balance: `429` with `retryAfter` when that
budget is enforced and spent.

Requires authentication.

**Parameters:** `TransferRewardsParams`:

* `token`: string — token contract address (0x-prefixed EVM address)
* `amount`: string — positive integer string in raw atomic units (e.g. `"1000000"` for 1 USDC)

**Returns:** `TransferRewardsResponse`:

* `rewardsBalance`: string — remaining balance in the rewards bucket after the transfer (raw atomic units)
* `tradingBalance`: string — new trading balance for this token after the transfer (raw atomic units)

Throws `409` when the requested `amount` exceeds the available rewards balance.

**Example:**

```typescript theme={null}
const { rewardsBalance, tradingBalance } = await sdk.tradercodes.transferRewards({
  token: "0xusdc...",
  amount: "1000000", // 1 USDC in raw units
});

console.log(`Remaining rewards: ${rewardsBalance}`);
console.log(`New trading balance: ${tradingBalance}`);
```

**getMyReferralPosition** `() =\> Promise\<GetMyReferralPositionResponse\>`

Read the authenticated caller's own referral position. Self-scoped — the server derives your
identity from the session, so it only ever returns your own chain. Requires authentication.

**Returns:** `GetMyReferralPositionResponse`:

* `referrer`: string — the wallet address of your direct (L1) referrer, or `""` when you were not referred. Use the empty check to drive an "already referred" state.
* `upline`: array of `{ wallet, display, level }` — your referral chain upward, nearest first: L1 (your referrer), L2, and so on. At most as many entries as TraderCodes rewards levels (never more than 10); empty when you were not referred. These are the wallets your own trades pay.
* `referrerDisplay`: string — the referrer's custom TraderCode handle if they have claimed one, otherwise their wallet address (render this).
* `totalEarned`: string — all-time rewards you have earned, in raw atomic units.
* `rewards`: array of up to your 100 most recent reward rows (`totalEarned` remains the complete aggregate), each `{ source, sourceDisplay, level, amount, token, rateApplied, createdAt }` — `source`/`sourceDisplay` identify the trader whose fills paid you, and `level` is how far down your chain that trader sits: 1 for a direct referee, 2 for their referee, and so on (at most 10).

Throws `401` when unauthenticated, `429` when the account's read budget is exhausted (retry after the interval in the error detail), and `500` on a server error.

**Example:**

```typescript theme={null}
const { referrer, referrerDisplay, totalEarned } = await sdk.tradercodes.getMyReferralPosition();
if (referrer) console.log(`Referred by ${referrerDisplay}`);
```

**getMyReferralDownline** `(params?: \{ pageSize?: number; pageToken?: string \}) =\> Promise\<GetMyReferralDownlineResponse\>`

Read who you earn from and how much. Self-scoped, read-only. Requires authentication.

`earningsBySource` is paged. Called without `params`, it returns only the **first page** (up to 100 rows), not every row — follow `nextPageToken` until it is `""` to read the rest.

**Parameters:**

* `pageSize?`: number — `earningsBySource` rows per page, 1–500 (default 100).
* `pageToken?`: string — opaque `nextPageToken` from the previous response; omit for the first page.

**Returns:** `GetMyReferralDownlineResponse`:

* `earningsBySource`: array of `{ source, sourceDisplay, level, totalEarned, token }` — one page of rows, one per `(source, level, token)` across every reward level, ordered by each source account's total, largest first, so the same trader can appear more than once (a different level or token); `source` is not unique. Rows of a wallet that traded through several applications are merged within a page at its first part's position, so a merged row can sit below a smaller one, and that wallet can appear again on a later page.
* `directReferees`: array of `{ wallet, display, referredAt, totalEarned }` — your direct (L1) referees, including those who have not traded yet (`totalEarned: "0"`). Shows up to the 500 most recent effective referees (after wallet dedupe), drawn from a bounded scan, so a very large history may yield an incomplete roster; the earnings views stay complete.
* `summary`: `{ totalEarned, byLevel, level1Earned, level2Earned, level3Earned }` — your earnings broken down by level, covering every level and source regardless of the page. `byLevel` is an array of `{ level, earned }` (raw atomic units), ascending, one entry per level with earnings, including levels deeper than TraderCodes rewards today. `level1Earned`, `level2Earned`, and `level3Earned` are **deprecated** (levels 1–3 only) — use `byLevel`.
* `nextPageToken`: string — pass it back as `pageToken` for the next page; `""` when there are no more rows.

Throws a `ValidationError` before sending when `pageSize` is outside 1 to 500; `400` when `pageToken` is malformed; `401` when unauthenticated; `429` when the account's read budget is exhausted (retry after the interval in the error detail); `500` on a server error.

**Example:**

```typescript theme={null}
const first = await sdk.tradercodes.getMyReferralDownline({ pageSize: 500 });
const rows = [...first.earningsBySource];
let pageToken = first.nextPageToken;
while (pageToken) {
  const page = await sdk.tradercodes.getMyReferralDownline({ pageSize: 500, pageToken });
  rows.push(...page.earningsBySource);
  pageToken = page.nextPageToken;
}
console.log(`Total earned: ${first.summary.totalEarned}, from ${rows.length} rows`);
for (const { level, earned } of first.summary.byLevel) console.log(`L${level}: ${earned}`);
```

**getMyReferralTree** `(params?: GetMyReferralTreeParams) =\> Promise\<GetMyReferralTreeResponse\>`

Read one level of your referral tree. Self-scoped, read-only. Requires authentication.

**Parameters:**

* `parent?`: string — wallet whose direct referees to list. Omit for your own L1 referees; pass one of your referees above the deepest rewarded level to expand that node.
* `pageSize?`: number — nodes per page, 1–200 (default 50).
* `pageToken?`: string — `nextPageToken` from the previous page; only valid with the same `parent`.

**Returns:** `GetMyReferralTreeResponse`:

* `parent`: string — the wallet whose referees are listed (your own wallet when `parent` was omitted).
* `parentLevel`: number — `0` for you, `1`–`9` for an expanded referee.
* `nodes`: array of `{ wallet, display, level, parent, referredAt, refereeCount, totalEarned }`, newest first — `level` is the depth below you (1–10, down to the deepest level TraderCodes rewards), `refereeCount` is how many wallets that node referred (expand it when above 0; always 0 at the deepest rewarded level), and `totalEarned` is what you earned from that wallet's own trades in raw atomic units. Each wallet appears once, under the referrer that earns from it.
* `nextPageToken`: string — pass it back for the next page; `""` on the last page.

Throws `400` for an invalid `parent`, `pageSize`, or `pageToken`, `401` when unauthenticated, `404` when `parent` is not you or one of your own referees above the deepest rewarded level, `429` when the account's read budget is exhausted, and `500` on a server error.

**Example:**

```typescript theme={null}
const root = await sdk.tradercodes.getMyReferralTree();
for (const node of root.nodes) {
  if (node.refereeCount > 0) {
    const children = await sdk.tradercodes.getMyReferralTree({ parent: node.wallet });
    console.log(`${node.display} referred ${children.nodes.length} wallets`);
  }
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.