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

# Trade on the onchain book

> Take liquidity for cNGN and EURC futures directly on Base: set up your account, quote, take and withdraw

Numo's futures liquidity is on **onchain books**: one `OnchainBook` contract per series family on Base.
Market makers quote curves on the contract, and you trade against them in one transaction that fills
and settles atomically. There is no API call, no signed order to submit and no matcher in between.

> [!NOTE]
>
> The venue's off-chain matcher still accepts signed futures orders (`POST /orders`), but no market
> maker quotes there. An order you post there rests until someone else crosses it. To trade now, take
> from the onchain book.

## The books

| Series | Book | Market id | Router | Taker fee | Tick | Trading stops |
| - | - | - | - | - | - | - |
| `cNGN-30NOV26` | `0x5a35f149005Ce74b874F7Cf07CC2618BFA4F8Bd4` | `1` | `0x09431Cf4a3693452DD46886b51453eDC8995B067` | 15 bps | 1e-8 USDC | 2026-11-30 13:00 UTC |
| `EURC-30NOV26` | `0x83C5741a24d57189379E1215F7A22d9f048E89d5` | `1` | `0xd9540220b514ab2E1a98Ff3C4c4F1F5FD5cf76aB` | 5 bps | 1e-6 USDC | 2026-11-30 14:30 UTC |

Both books trade in lots of 0.001 contract (`lotSize` 1e15). Read the live parameters with
`markets(marketId)` on the book: the future, the MarginEngine, the sub id, the expiry, the last trade
time, the tick and lot size, the taker fee rate (18 decimals) and whether the market is enabled.

The contracts you also need, all on Base:

| Contract | Address |
| - | - |
| `SubAccounts` | `0x7019244E25FA416e6Ca2ed2F3cA25277aef72843` |
| USDC cash (`CashAsset`) | `0xA74E49b4Ed7cb176bc02ef4D8a1A3240C9aD4272` |
| MarginEngine | `0x0705219a1594d5Fc5dC2573da4082cAf3e1B0950` |
| USDC | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |

## How a take works

Each maker posts a curve around its mid: sizes at price levels above it (asks) and below it (bids).
A take walks the best levels across every maker on the market until your amount is filled, your
limit price is reached, or `maxLevels` levels are used. Each fill moves the position to your account
and the opposite position to the maker's, at the level's price. The fee is charged in USDC from your
account's cash.

A take is described by a `TakeOrder`:

| Field | Meaning |
| - | - |
| `marketId` | The book's market id, `1` on both books. |
| `takerAccountId` | Your account. The transaction must come from its owner, or an address the owner approved. |
| `isBuy` | `true` to buy (go long), `false` to sell (go short). |
| `amount` | Size in position units: 1e18 is one contract. Rounded down to whole lots of 1e15. |
| `limitPrice` | The worst price you accept, in USDC per unit of the base, 18 decimals. |
| `minFill` | The take reverts if it fills less than this, in position units. Set it to `amount` for all or nothing. |
| `maxFee` | The most the take may charge, in USDC, 18 decimals. It reverts with `OB_FeeTooHigh` above it. |
| `deadline` | Unix seconds. The take reverts after it. |
| `maxLevels` | The most price levels to walk. `255` is the maximum. |
| `selfTradeMode` | `0` (`Abort`): revert if you would trade against your own quote. `1` (`DecrementTake`): skip it. |
| `managerData` | Leave empty. |

`take(order, optionalReport)` returns the size filled and the average price. Pass `0x` as
`optionalReport`.

### The fee

The fee is the taker fee rate × notional. On one `cNGN-30NOV26` contract (1,000,000 cNGN) at
0.00069 USDC per cNGN, the notional is 690 USDC and the 15 bps fee is 1.035 USDC. Set `maxFee` from
your limit price, so the bound holds at any fill inside it:

```
maxFee = amount / 1e18 × contract size × limitPrice × takerFeeRate / 1e18
```

The contract size is `contract_multiplier` on [`GET /markets`](https://docs.numofx.com/api-reference/endpoint/get):
1,000,000 cNGN on `cNGN-30NOV26`, 1,000 EURC on `EURC-30NOV26`. Makers pay no fee.

## Set up your account

You need a trading account that **your wallet owns**, under the MarginEngine. An account opened
through [`POST /deposits`](https://docs.numofx.com/api-reference/endpoint/deposits) is held by the venue's `Matching` contract
for the off-chain matcher, so it cannot take from the book. Open your own instead. Each step is one
transaction from your wallet, and the first three are needed only once.

**1. Open the account**

`SubAccounts.createAccount(owner, manager)` with your address and the MarginEngine. It returns the
account id.

**2. Deposit USDC**

Approve the USDC cash asset for the amount, then call `CashAsset.deposit(accountId, amount)`.
The amount is in USDC's 6 decimals: `1000000000` is 1,000 USDC.

**3. Let the book move your assets**

`SubAccounts.setAssetAllowances(accountId, book, allowances)`, with an allowance on the future and
one on the cash, each `(asset, positive, negative)`. The book can then move your position and fees
in the takes you send. Grant it per book.

> [!WARNING]
>
> The allowance lets that book contract move the future and cash in your account. Only a take sent by
> you, or by an address you approved, can use it. Grant it only to the book addresses on this page.

```ts theme={"theme":"github-light-high-contrast"}
import { createPublicClient, createWalletClient, http, maxUint256, parseAbi } from 'viem'
import { base } from 'viem/chains'
import { privateKeyToAccount } from 'viem/accounts'

const SUB_ACCOUNTS = '0x7019244E25FA416e6Ca2ed2F3cA25277aef72843'
const CASH = '0xA74E49b4Ed7cb176bc02ef4D8a1A3240C9aD4272'
const ENGINE = '0x0705219a1594d5Fc5dC2573da4082cAf3e1B0950'
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
const BOOK = '0x5a35f149005Ce74b874F7Cf07CC2618BFA4F8Bd4'   // cNGN-30NOV26
const FUTURE = '0xcACEe66ad41fD1472a47D7D5Fe372FFbFac9AA75' // asset_address of cNGN-30NOV26

const abi = parseAbi([
  'function createAccount(address owner, address manager) returns (uint256)',
  'function setAssetAllowances(uint256 accountId, address delegate, (address asset, uint256 positive, uint256 negative)[] allowances)',
  'function approve(address spender, uint256 amount) returns (bool)',
  'function deposit(uint256 recipientAccount, uint256 amount)',
])

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)
const client = createPublicClient({ chain: base, transport: http() })
const wallet = createWalletClient({ account, chain: base, transport: http() })
const send = async (req: Parameters<typeof wallet.writeContract>[0]) =>
  client.waitForTransactionReceipt({ hash: await wallet.writeContract(req) })

// 1. Open the account, reading the id the call returns
const { result: accountId, request } = await client.simulateContract({
  account, address: SUB_ACCOUNTS, abi, functionName: 'createAccount', args: [account.address, ENGINE],
})
await send(request)

// 2. Deposit 1,000 USDC
await send({ address: USDC, abi, functionName: 'approve', args: [CASH, 1000_000000n] })
await send({ address: CASH, abi, functionName: 'deposit', args: [accountId, 1000_000000n] })

// 3. Let the book move the future and cash in this account
await send({
  address: SUB_ACCOUNTS, abi, functionName: 'setAssetAllowances',
  args: [accountId, BOOK, [
    { asset: FUTURE, positive: maxUint256, negative: maxUint256 },
    { asset: CASH, positive: maxUint256, negative: maxUint256 },
  ]],
})
```

The account holds USDC as [collateral](https://docs.numofx.com/collateral.md). The MarginEngine requires initial margin after
each take: 25% of notional on `cNGN-30NOV26`, 6% on `EURC-30NOV26`. See [Margin](https://docs.numofx.com/futures.md#margin).

## Quote, then take

`quote(order)` is a free view that runs the same walk as `take` and returns the size it would fill,
the average price, the fee and how many makers it would settle with. Call it with your account id to
check your allowances too, or with `takerAccountId` `0` for a price only.

```ts theme={"theme":"github-light-high-contrast"}
const bookAbi = parseAbi([
  'struct TakeOrder { uint256 marketId; uint256 takerAccountId; bool isBuy; uint256 amount; uint256 limitPrice; uint256 minFill; uint256 maxFee; uint64 deadline; uint16 maxLevels; uint8 selfTradeMode; bytes managerData; }',
  'function quote(TakeOrder o) view returns (uint256 filled, uint256 avgPrice, uint256 fee, uint256 makerCount)',
  'function take(TakeOrder o, bytes optionalReport) returns (uint256 filled, uint256 avgPrice)',
])

// Buy one cNGN-30NOV26 contract, paying at most 0.00070 USDC per cNGN
const amount = 1000000000000000000n                 // one contract
const limitPrice = 700000000000000n                 // 0.00070 x 1e18
const contractSize = 1000000n                       // cNGN per contract
const feeRate = 1500000000000000n                   // 15 bps, takerFeeRate from markets(1)
const maxFee = (amount * contractSize * limitPrice * feeRate) / 10n ** 36n // 1.05 USDC
const order = {
  marketId: 1n, takerAccountId: accountId, isBuy: true, amount, limitPrice,
  minFill: amount,                                  // all or nothing
  maxFee, deadline: BigInt(Math.floor(Date.now() / 1000) + 60),
  maxLevels: 255, selfTradeMode: 0, managerData: '0x',
} as const

const [filled, avgPrice, fee] = await client.readContract({
  address: BOOK, abi: bookAbi, functionName: 'quote', args: [order],
})
if (filled === amount) {
  await send({ address: BOOK, abi: bookAbi, functionName: 'take', args: [order, '0x'] })
}
```

To sell, set `isBuy: false` and `limitPrice` to the lowest price you accept. To close a position,
take the opposite side for its size.

### Why a take reverts

| Error | Cause |
| - | - |
| `OB_NotAuthorized` | The sender is not the account's owner or an approved address. |
| `OB_TakerAllowanceTooLow` | The account has not granted this book an allowance on the future or the cash. |
| `OB_FeeTooHigh` | The fee is above `maxFee`. |
| `OB_BelowMinFill` | Less than `minFill` was available inside `limitPrice` and `maxLevels`. |
| `OB_Expired` | The block is past `deadline`. |
| `OB_TradingClosed` | The series is past its last trade time. |
| `OB_MarketDisabled` | The market is not open. |

A take that would leave your account below initial margin is refused by the MarginEngine.

## Use the router instead

The router does a deposit, a take and a withdrawal in one call on your own account. It holds nothing
between calls. Set it up once:

* `SubAccounts.setApprovalForAll(router, true)`, so the router can take and withdraw for you.
* The book's allowance on your account, as above.
* USDC approved to the router, for deposits.

Then call `route(r)`:

| Field | Meaning |
| - | - |
| `accountId` | Your account. |
| `deposit` | USDC to deposit first, 6 decimals. `0` for none. |
| `take` | A `TakeOrder` as above, with `takerAccountId` set to `accountId`. `amount` `0` skips the take. |
| `reports` | `0x`. |
| `reduceOnly` | `true` to only reduce your position: the take must oppose it and is cut to its size. |
| `withdraw` | USDC to withdraw after the take, 6 decimals. `0` for none. |
| `recipient` | Where the withdrawal goes. The zero address sends it to you. |

## Positions, withdrawals and settlement

* **Your position** is your account's balance of the future at the series' sub id:
  `SubAccounts.getBalance(accountId, future, subId)`, in position units (1e18 a contract, negative
  when short). `getAccountBalances(accountId)` lists everything the account holds.
* **Variation margin** settles to your account's USDC cash as the mark moves, as for any futures
  position. See [Variation margin](https://docs.numofx.com/futures.md#variation-margin).
* **Withdraw** with `CashAsset.withdraw(accountId, amount, recipient)` from the owner, in USDC's 6
  decimals. The MarginEngine refuses a withdrawal that would leave the account below initial margin.
* **At expiry** the series settles in cash. See [Settlement](https://docs.numofx.com/futures.md#settlement).
* **On the tape**, fills on the book appear on [`GET /trades`](https://docs.numofx.com/api-reference/endpoint/trades) for the
  series with `source: "book"`.


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