Perps for Developers
Mainnet perps run on the Somnia Tokyo chain, which the app shows as the SomniaX region. Build against it with @somnia-chain/markets-sdk; this page uses version 0.34.0, the one the app runs. For how the markets themselves work, see Margin, Liquidations and Funding.
Network
| Chain ID | 50321 |
| RPC | https://api.tokyo.infra.mainnet.somnia.network |
| WebSocket | wss://api.tokyo.infra.mainnet.somnia.network/ws |
| Indexer (GraphQL) | https://tokyo-prd.smk.somnia.host/v1/graphql |
| Explorer | explorer.somnia.network/tokyo |
| Gas coin | SOMI |
Contracts
Every perps address, per market included, is on the Contract Addresses page.
Read per-market addresses off the market row rather than hardcoding them: poolAddress, marginBank and stopRegistry are all on it. client.getPerpSystemConfig(marginBank) returns the MarginBank's collateral, factory, liquidation engine and insurance fund in one read, which is the check worth running before trusting any list.
Connect, size and place an order
import { SOMNIA_TOKYO_ADDRESSES, SomniaMarkets } from "@somnia-chain/markets-sdk"
import { somniaTokyo } from "@somnia-chain/markets-sdk/chains"
import { createPublicClient, http, parseAbi, parseUnits } from "viem"
const markets = new SomniaMarkets({
chain: somniaTokyo,
indexerUrl: "https://tokyo-prd.smk.somnia.host/v1/graphql",
addresses: SOMNIA_TOKYO_ADDRESSES,
privateKey: process.env.PRIVATE_KEY as `0x${string}`,
})
const perps = await markets.client.listPerpMarkets()
const btc = perps.find((m) => m.baseSymbol === "BTC")!
const account = markets.walletAddress!
// Move USDso from the wallet into the MarginBank (approves the bank first if needed)
await markets.trader.depositMargin({
marginBank: btc.marginBank,
amount: parseUnits("500", btc.quoteDecimals),
})
const price = parseUnits("60000", btc.quoteDecimals)
const max = await markets.client.getMaxPerpOrderSize({
pool: btc.poolAddress,
marginBank: btc.marginBank,
account,
isBid: true,
price,
})
if (!max.priceable) throw new Error("No live mark price to size against")
// maxQuantity leaves out orders already resting on this side; the pool counts
// them toward the position limit, so read them and check the room as well
const chainClient = createPublicClient({ chain: somniaTokyo, transport: http() })
const resting = await chainClient.readContract({
address: btc.poolAddress,
abi: parseAbi([
"function getReducingCapacity(address account) view returns ((int128 positionSize, uint256 pendingBidQuantity, uint256 pendingAskQuantity, uint256 pendingOppositeQuantity, uint256 effectiveReducingCapacity))",
]),
functionName: "getReducingCapacity",
args: [account],
})
const room = max.maxPositionSize - resting.positionSize - resting.pendingBidQuantity // a buy
const quantity = parseUnits("0.001", btc.baseDecimals)
const isExit = resting.positionSize < 0n && quantity <= -resting.positionSize
if (!max.placeable || quantity > max.maxQuantity) {
throw new Error(`Order too large for this account: limited by ${max.limitedBy}`)
}
if (!isExit && quantity > room) throw new Error("Order would pass the position limit")
await markets.trader.placePerpOrder({ pool: btc.poolAddress, isBid: true, price, quantity })
Prices are raw quote units per whole base asset and quantities are raw base units, so convert with each market's own decimals: they differ per market. A price must sit on the market's tickSize and a quantity on its lotSize, at least minQuantity.
getMaxPerpOrderSize tells you the largest order the account can place (maxQuantity) and which limit binds it (limitedBy), so check it before sending rather than reading a revert afterwards. It answers priceable: false when the market's mark price is stale, and then quotes no size at all.
It sizes against the margin already in the MarginBank. To size against USDso still in the wallet instead, which the pool pulls when the order is sent by its owner, pass autoPull: true and approve the USDso to the MarginBank first.
It also reports the account's position limit in the market as maxPositionSize, but maxQuantity does not count orders the account already has resting on the same side. The pool does: it counts them as if they had filled, and reverts with MaxPositionSizeExceeded() when the result would pass the limit. With positionSize signed (negative for a short) and the resting quantities read from the pool's getReducingCapacity(account), the room the limit leaves for a new order is:
Buy: maxPositionSize − positionSize − pendingBidQuantity
Sell: maxPositionSize + positionSize − pendingAskQuantity
Size an order that increases the position to the smaller of that room and maxQuantity; a negative room means only a reducing order can go through. Orders resting on the other side do not add room. An order that only reduces the position, and is no larger than it, is never stopped by the limit, even when resting orders leave no room: size it against the position it reduces. The example above does both checks for a buy.
Trade an app wallet with a bot
To have code trade a wallet you use in the app, link your key to it with Link a Bot: the key can then place, cancel and reduce orders for that wallet, and nothing else.
Raw and operator calls
If you call the pools directly instead of through the SDK, for example a bot key placing orders for another wallet with placeOrderFor, these are the things that trip people up.
function placeOrderFor(address owner, bool isBid, uint64 userData, uint256 price, uint256 quantity,
uint64 expireTimestampNs, uint8 orderType, uint8 selfMatchingOption, address builder,
uint96 builderFeeBpsTimes1k) payable returns (bool success, uint128 orderId)
Scale quantity by the base asset's decimals
price always has 18 decimals, because every market's collateral, USDso, does. quantity uses the base asset's own decimals, which differ per market:
| Base decimals | Markets |
|---|---|
| 6 | ADA, HYPE, XRP |
| 8 | BTC, DOGE, ZEC |
| 9 | SOL, SUI |
| 18 | AVAX, BNB, ETH, LINK, LIT, WLD |
| 24 | NEAR |
Read them rather than copying this table: baseDecimals is on every market row. getOrderBookParameters() on the pool returns the raw tickSize, minQuantity and lotSize, in that order.
Grant an operator per pool, pool first
The wallet that owns the margin authorizes an operator on the OperatorPermissionsRegistry, one function selector at a time:
function setOperatorApprovalForPool(address pool, address operator, bytes4[] selectors, bool approved)
The pool comes first. With the pool and operator swapped the call still succeeds, but grants nothing. Check the result with isApprovedForPool(pool, owner, operator, selector), which should return true for every selector you granted.
Three grants cover every operator call. Each batch call checks the grant of its single-order counterpart:
| Grant this selector | Lets the operator call |
|---|---|
0x80054449 (placeOrderFor) | placeOrderFor, placeOrdersFor |
0xe37b444b (cancelOrderFor) | cancelOrderFor, cancelOrdersFor |
0x364c2587 (reduceOrderFor) | reduceOrderFor, reduceOrdersFor |
Amending (amendOrderFor, amendOrdersFor) needs both the place and the cancel grant. Granting the selector of a batch or amend function itself authorizes nothing.
Leave plenty of gas
Perp orders are heavier than token transfers. On mainnet, eth_estimateGas returned about 2.0M gas for a small resting BTC-PERP order and 2.6M for one that crossed the book. A transaction that runs out of gas or reverts lands with status 0 and no reason in the receipt. Replay it with eth_call at the parent block to see the revert.
An IOC that fills nothing reverts
An IOC order that finds nothing to fill reverts a single placeOrderFor with ImmediateOrCancelNoFill() (0xd48c4403). The level you saw can be gone by the time the transaction lands, so price an IOC through the book with some slippage room rather than exactly at the touch. The full list of order errors is on the Errors page.
Common pitfalls
- The SDK reads the chain over WebSocket. An environment that only proxies HTTP fails on the first chain read. Give it access to the WebSocket endpoint above.
- Decimals vary per market, from 6 to 24 on the base side. Never assume 18; see the table above.
- The factory lists one more market than the app.
listPerpMarkets()also returns XLM, which is close-only:isRestricted()on its pool istrue, and orders that would open or increase a position revert. Filter on it. - Each account has a position limit per market, about a fifth of the market's open interest cap, and resting orders on the same side count toward it as if filled.
getMaxPerpOrderSizereports the limit asmaxPositionSizebut does not subtract resting orders frommaxQuantity; see above. - TP and SL carry 0.15 SOMI each, sent with the create call on the market's stop registry, refunded on cancel and used on trigger. Read
somiPaymentPerOrder()on the registry rather than hardcoding it. - LIT-PERP has no stop registry.
getStopOrderRegistryon the factory returns the zero address for it, so TP and SL orders can't be placed there. - A resting order can't sit too far through the mark. A bid above the mark, or an ask below it, by more than the market's band reverts with
OrderPriceOutsideBand. The bands are on Orders.