API Reference
Reference for the PerpCity Zig SDK v0.7.0 - context, trading, math, and HFT infrastructure.
Reference for perpcity-zig-sdk v0.7.0 (Zig 0.17). Import it as const sdk = @import("perpcity_sdk");. Addresses are [20]u8, transaction hashes [32]u8 (sdk.types.Bytes32).
Liquidations on current markets
v0.7.0 encodes the two-argument liquidateTaker / liquidateMaker(posId, feeRecipient) and decodes the earlier close-event shapes. That matches markets created before October 2026; on current (contracts v0.2.2) markets, liquidation calls revert and their TakerClosed events are not decoded. Opening, adjusting and closing positions work on both.
Units
| Field | Type | Unit |
|---|---|---|
margin when opening | f64 | Human USDC (100.0 = $100) |
perp_delta | i256 | Raw perp tokens (1e6 = 1 token); positive = long, negative = short |
amt1_limit | u256 | Raw USDC: the most paid when buying perp tokens, the least received when selling |
margin_delta, margin_in | i128 / u128 | Raw USDC (1e6 = $1) |
max_amt0_in, max_amt1_in, amt0_limit | u256 | Raw token amounts |
Context (sdk.context.PerpCityContext)
Constructors are on the Installation page. Methods (all take self: *Self):
| Method | Returns |
|---|---|
setupForTrading(perp) / ensureApproval(perp) | Approve USDC for a market (max allowance) |
getPerpData(perp) | PerpData: mark, beacon, taker and maker bounds, fees |
getPerpConfig(perp) | PerpConfig: module addresses |
getPositionRawData(perp, pos_id) | PositionRawData: packed delta, margin, margin ratios, funding checkpoint |
getMakerDetails, getTakerDetails, getPositionOwner(perp, pos_id) | Per-position details |
getUserData(address, positions) | UserData: USDC balance |
getOpenInterest, getCapacity, getFundingRate, getSolvencyState, getFeeFund(perp) | Market state |
getIndexValue(beacon), getIndexTWAP(beacon, seconds_ago) | Beacon index, Q96 |
pollEvents(perp, from_block, to_block) | Decoded market events in a block range |
discoverOwnedPositions(perp, owner, from_block, to_block) | Position IDs an address holds |
multicall3(calls), simulateCall(to, calldata, from, overrides) | Batched reads and call simulation |
enableManagedWrites, sendManaged, stuckWrites, resendBumped | Managed write path with nonce tracking and gas bumping |
getMarkPriceCached(perp) | Mark price through the context's cache |
Trading (sdk.perp_contract)
Each write has a matching simulate* function that runs the call as an eth_call first and returns the decoded revert.
| Function | Returns | Description |
|---|---|---|
openTaker(ctx, perp, .{ .margin, .perp_delta, .amt1_limit }) | OpenPosition | Open a long or short |
openMaker(ctx, perp, .{ .margin, .price_lower, .price_upper, .liquidity, .max_amt0_in, .max_amt1_in }) | OpenPosition | Open a liquidity range |
adjustTaker(ctx, perp, .{ .position_id, .margin_delta, .perp_delta, .amt1_limit }) | tx hash | Change size and margin; close with perp_delta = minus the position size |
adjustMaker(ctx, perp, .{ .position_id, .margin_delta, .liquidity_delta, .amt0_limit, .amt1_limit }) | tx hash | Add or remove liquidity |
liquidateTaker, liquidateMaker(ctx, perp, .{ .position_id, .fee_recipient }) | tx hash | Two-argument form; see the callout above |
backstopTaker, backstopMaker(ctx, perp, .{ .position_id, .margin_in, .position_recipient }) | tx hash | Take over an underwater position by posting margin |
donate(ctx, perp, amount), touch(ctx, perp) | tx hash | Insurance top-up; accrue state |
OpenPosition has perp, position_id, is_maker and tx_hash fields, and adjustTaker, adjustMaker, liquidate, backstop, liveDetails and perpHex methods.
Opening a long with a 1% slippage cap:
const mark = (try ctx.getPerpData(perp)).mark;
const margin: f64 = 100.0;
const leverage: f64 = 3.0;
const perp_delta = try sdk.sizing.derivePerpDelta(margin, leverage, mark, true);
const max_usd = margin * leverage * 1.01; // long: the most USDC the swap may take
const amt1_limit: u256 = @intFromFloat(max_usd * 1e6);
const position = try sdk.perp_contract.openTaker(&ctx, perp, .{
.margin = margin,
.perp_delta = perp_delta,
.amt1_limit = amt1_limit,
});For a short, amt1_limit is the least USDC the swap must return (for example notional * 0.99). A limit of 0 disables the check for a short but makes every long revert.
Market factory (sdk.perp_factory)
createPerp(ctx, .{ .owner, .name, .symbol, .token_uri, .modules, .ema_window, .salt }) returns the new market's address; isPerp(ctx, perp) checks whether an address was created by the factory. Listed markets are created by Strobe.
Sizing and math (pure, no network)
| Module | Functions |
|---|---|
sdk.sizing | derivePerpDelta(margin, leverage, price, is_long), calculateAlignedTicks(price_lower, price_upper, tick_spacing) |
sdk.position | entryPrice, positionSize, positionValue(raw, mark), currentLeverage(raw, mark), liquidationPrice(raw, is_long, settled_margin, liq_fee_ratio), marginHuman, perpDelta, usdDelta, pnlPercentage |
sdk.liquidity | estimateLiquidity(tick_lower, tick_upper, usd_scaled), calculateLiquidityForTargetRatio(...), getSqrtRatioAtTick |
sdk.conversions | priceToTick, tickToPrice, priceToSqrtPriceX96, sqrtPriceX96ToPrice, scale6Decimals, scaleFrom6Decimals, scaleToX96, scaleFromX96, marginRatioToLeverage |
sdk.funding | Funding-rate conversions |
sdk.perp | Accessors on PerpData |
HFT infrastructure
These have no network dependency and can be used on their own.
| Module | Type | Purpose |
|---|---|---|
sdk.nonce | HftNonceManager | Lock-free nonce acquisition with submission tracking and resync |
sdk.gas | GasCache | Cached fees by Urgency, refreshed from block base fees |
sdk.tx_pipeline | TxPipeline | Nonce + gas preparation, stuck-transaction detection and fee bumps |
sdk.multi_rpc | MultiRpcProvider | Endpoint selection with error backoff and latency tracking |
sdk.state_cache | StateCache | TTL cache for mark prices, funding, fees and bounds |
sdk.latency | LatencyTracker | Rolling p50/p95/p99 |
sdk.position_manager | PositionManager | Stop-loss, take-profit and trailing-stop triggers (track, checkTriggers) |
sdk.watcher | PerpEventWatcher | WebSocket subscription to a market's events, with RPC backfill |
sdk.event_decode | decodeEvent, decodeLogs | Decode market logs into DecodedEvent |
Errors
SDK calls return sdk.errors.SdkError values; getErrorDebugInfo(err) returns its category, source (RPC, contract, validation and so on) and whether it is safe to retry. sdk.revert decodes contract revert data from simulations.
ABIs
sdk.abi holds the contract ABIs (perp_abi, perp_factory_abi, the module ABIs, beacon_abi, erc20_abi) with selectors computed at compile time, for building calls the wrappers do not cover.