Perp CityDocs

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

FieldTypeUnit
margin when openingf64Human USDC (100.0 = $100)
perp_deltai256Raw perp tokens (1e6 = 1 token); positive = long, negative = short
amt1_limitu256Raw USDC: the most paid when buying perp tokens, the least received when selling
margin_delta, margin_ini128 / u128Raw USDC (1e6 = $1)
max_amt0_in, max_amt1_in, amt0_limitu256Raw token amounts

Context (sdk.context.PerpCityContext)

Constructors are on the Installation page. Methods (all take self: *Self):

MethodReturns
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, resendBumpedManaged 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.

FunctionReturnsDescription
openTaker(ctx, perp, .{ .margin, .perp_delta, .amt1_limit })OpenPositionOpen a long or short
openMaker(ctx, perp, .{ .margin, .price_lower, .price_upper, .liquidity, .max_amt0_in, .max_amt1_in })OpenPositionOpen a liquidity range
adjustTaker(ctx, perp, .{ .position_id, .margin_delta, .perp_delta, .amt1_limit })tx hashChange 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 hashAdd or remove liquidity
liquidateTaker, liquidateMaker(ctx, perp, .{ .position_id, .fee_recipient })tx hashTwo-argument form; see the callout above
backstopTaker, backstopMaker(ctx, perp, .{ .position_id, .margin_in, .position_recipient })tx hashTake over an underwater position by posting margin
donate(ctx, perp, amount), touch(ctx, perp)tx hashInsurance 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)

ModuleFunctions
sdk.sizingderivePerpDelta(margin, leverage, price, is_long), calculateAlignedTicks(price_lower, price_upper, tick_spacing)
sdk.positionentryPrice, positionSize, positionValue(raw, mark), currentLeverage(raw, mark), liquidationPrice(raw, is_long, settled_margin, liq_fee_ratio), marginHuman, perpDelta, usdDelta, pnlPercentage
sdk.liquidityestimateLiquidity(tick_lower, tick_upper, usd_scaled), calculateLiquidityForTargetRatio(...), getSqrtRatioAtTick
sdk.conversionspriceToTick, tickToPrice, priceToSqrtPriceX96, sqrtPriceX96ToPrice, scale6Decimals, scaleFrom6Decimals, scaleToX96, scaleFromX96, marginRatioToLeverage
sdk.fundingFunding-rate conversions
sdk.perpAccessors on PerpData

HFT infrastructure

These have no network dependency and can be used on their own.

ModuleTypePurpose
sdk.nonceHftNonceManagerLock-free nonce acquisition with submission tracking and resync
sdk.gasGasCacheCached fees by Urgency, refreshed from block base fees
sdk.tx_pipelineTxPipelineNonce + gas preparation, stuck-transaction detection and fee bumps
sdk.multi_rpcMultiRpcProviderEndpoint selection with error backoff and latency tracking
sdk.state_cacheStateCacheTTL cache for mark prices, funding, fees and bounds
sdk.latencyLatencyTrackerRolling p50/p95/p99
sdk.position_managerPositionManagerStop-loss, take-profit and trailing-stop triggers (track, checkTriggers)
sdk.watcherPerpEventWatcherWebSocket subscription to a market's events, with RPC backfill
sdk.event_decodedecodeEvent, decodeLogsDecode 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.

On this page