Perp CityDocs
SDK

API Reference

Reference for the PerpCity TypeScript SDK (@strobelabs/perpcity-sdk 0.17.1).

Reference for @strobelabs/perpcity-sdk 0.17.1. PerpAddress is a market's Perp contract address (0x${string}). Unit conventions are in Core Concepts.

PerpCityContext

new PerpCityContext({ walletClient, rpcUrl, deployments })
MemberReturnsDescription
validateChainId()Promise<void>Throws if rpcUrl and walletClient.chain differ
deployments()PerpCityDeploymentsThe configured addresses
getPerpConfig(perp)Promise<PerpConfig>Pool key, modules, protocol fee, EMA window (cached 5 min)
getPerpData(perp)Promise<PerpData>Mark, pool state, beacon, bounds, fees
getPositionRawData(perp, positionId)Promise<PositionRawData>Margin, entry deltas, margin ratios, maker range
getOpenPositionData(perp, positionId, isLong, isMaker)Promise<OpenPositionData>Existence check plus identifiers
getUserData(user, positions)Promise<UserData>USDC balance; echoes the positions passed in
publicClient, walletClientviem clientsDirect access for custom calls

Trading

FunctionReturnsDescription
openTakerPosition(ctx, perp, { margin, perpDelta, amt1Limit })Promise<OpenPosition>Open a long or short; approves USDC if needed
openMakerPosition(ctx, perp, { margin, priceLower, priceUpper, liquidity, maxAmt0In, maxAmt1In })Promise<OpenPosition>Open a liquidity range; aligns ticks and approves the margin (approve margin + maxAmt1In yourself, see Approvals)
adjustTaker(ctx, perp, { posId, marginDelta, perpDelta, amt1Limit })Promise<{ txHash }>Change taker size and margin
adjustMaker(ctx, perp, { posId, marginDelta, liquidityDelta, amt0Limit, amt1Limit })Promise<{ txHash }>Add or remove maker liquidity and margin
adjustMargin(ctx, perp, positionId, marginDelta)Promise<{ txHash }>Add (positive) or withdraw (negative) margin
closePosition(ctx, perp, positionId, { amt0Limit?, amt1Limit })Promise<{ txHash }>Close a taker or maker position
createPerp(ctx, params)Promise<PerpAddress>Create a market through the PerpFactory (needs deployments.perpFactory and the five modules). Listed markets are created by Strobe

OpenPosition has perpId, positionId, isLong, isMaker, txHash and closePosition(params).

Sizing, quotes and slippage

FunctionReturnsDescription
derivePerpDelta({ margin, leverage, price, isLong })bigintSigned perpDelta for a margin and leverage at a price
estimateTakerPosition(ctx, perp, { isLong, margin, leverage })Promise<EstimateTakerPositionResult>Quote an open: fill price, USD leg, fees, depth flags
estimateTakerAdjust(ctx, perp, { perpDelta })Promise<EstimateTakerAdjustResult>Quote an adjust or close
calculateTakerSlippageLimit(quote, isLong, slippagePercent)bigintamt1Limit from a quote
calculateAlignedTicks(priceLower, priceUpper, tickSpacing){ alignedTickLower, alignedTickUpper }Round a price range to valid ticks
estimateLiquidity(ctx, perp, tickLower, tickUpper, usdScaled)Promise<bigint>Max liquidity a margin can back over a range
calculateLiquidityForTargetRatio(...)bigintLiquidity for a target margin ratio (no simulation)
fetchPoolTickMap, simulateTakerSwapExact, maxFillablePerpDelta, walkPoolDepthExact multi-tick swap simulation and depth

Market reads

FunctionReturnsDescription
getFundingRate(ctx, perp)Promise<{ ratePerDay, ratePerMinute, fundingPerDayRaw }>Funding rate in percent; positive = longs pay
getIndexValue(ctx, perp)Promise<bigint>Beacon index, Q96
getIndexTWAP(ctx, perp, secondsAgo)Promise<bigint>Beacon time-weighted average, Q96
getPerpMark, getPerpBeacon, getPerpBounds, getPerpFees, getPerpTickSpacingField accessors on PerpData

Position math

All take PositionRawData from getPositionRawData.

FunctionReturns
calculateEntryPrice(raw)Entry price
calculatePositionSize(raw)Signed size in perp tokens
calculatePositionValue(raw, markPrice)Value at a price, in USD
calculateLeverage(positionValue, effectiveMargin)Leverage
calculateLiquidationPrice(raw, isLong, effectiveMargin?)Liquidation price, or null for an empty position
calculatePnlPercentage(pnl, funding, margin)Return on margin, percent

Calldata builders

For ERC-4337 batching or your own transaction sending. They build calls instead of sending them; a call is CallData = { to, data, value }.

BuilderReturns
buildApproveUsdcCall, buildOpenTakerPositionCall, buildAdjustTakerCall, buildAdjustMakerCallCallData
buildOpenMakerPositionCall, buildClosePositionCallPromise<CallData>
buildOpenTakerPositionCalls, buildOpenMakerPositionCalls, buildAdjustTakerCalls, buildAdjustMakerCallsPromise<CallData[]>: the USDC approval (when the allowance is short) followed by the action

Utilities

FunctionDescription
getRpcUrl({ url? })RPC URL from RPC_URL or an override
approveUsdc(ctx, amount, spender), getUsdcAllowance(ctx, owner, spender)USDC approval
scale6Decimals, scaleFrom6DecimalsUSDC amount conversion
scaleToX96, scaleFromX96, priceToSqrtPriceX96, sqrtPriceX96ToPriceQ96 conversion
priceToTick, tickToPriceTick conversion
marginRatioToLeverageMargin ratio to leverage
parseContractErrorNormalise an error into a PerpCityError

Constants: MIN_OPENING_MARGIN_USD (5), Q96, MIN_TICK, MAX_TICK.

ABIs: PERP_ABI, PERP_FACTORY_ABI, BEACON_ABI and the module ABIs, for direct viem calls. In 0.17.1 these describe the earlier contract version; see Core Concepts.

Errors

PerpCityError and its subclasses ContractError, TransactionRejectedError, InsufficientFundsError, RPCError, ValidationError.

On this page