Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

3 stars

Watchers

1 watching

Forks

Repository files navigation

PerpCity Rust SDK

Rust SDK for the PerpCity perpetual futures protocol on Arbitrum. Built for high-frequency trading with lock-free nonce management, multi-endpoint transport with circuit breakers, and a 2-tier state cache.

Installation

[dependencies]
perpcity-sdk = "0.2"

Quickstart

Prerequisites: Rust 1.85+, an Arbitrum Sepolia RPC (the public endpoint works fine).

  1. Clone and create a .env file:
git clone https://github.com/StrobeLabs/perpcity-rust-sdk.git
cd perpcity-rust-sdk
PERPCITY_PRIVATE_KEY=your_hex_private_key
PERPCITY_PERP=0x...      # Perp market contract address
PERPCITY_USDC=0x...      # optional; defaults to Arbitrum Sepolia test USDC
RPC_URL=https://sepolia-rollup.arbitrum.io/rpc  # optional
  1. Fund your wallet on Arbitrum Sepolia — you need a small amount of ETH for gas and some USDC for margin. The testnet USDC has a public mint function:
# Mint 10,000 USDC to your address
cast send 0xBEF280BefeE2Cb28c20D1E4Cc1da999B4DA0f1fD \
  "mint(address,uint256)" YOUR_ADDRESS 10000000000 \
  --rpc-url https://sepolia-rollup.arbitrum.io/rpc \
  --private-key YOUR_PRIVATE_KEY
  1. Run the quickstart:
cargo run --release --example quickstart

Examples

All examples load configuration from .env automatically via dotenvy.

Example Run What it does
quickstart cargo run --example quickstart Open a 2x long, close it. ~20 lines of setup.
open_position cargo run --example open_position Full taker lifecycle: market data, open, monitor PnL/funding/liquidation, close.
market_maker cargo run --example market_maker LP position: calculate tick range around mark, estimate liquidity, open maker position. Note: makers are currently subject to a 7-day lockup, so this example shouldn't run.
hft_bot cargo run --example hft_bot Full trading loop: multi-endpoint transport, momentum strategy, position manager with SL/TP/trailing stop, latency stats.
taker_price_impact cargo run --example taker_price_impact Local, exact taker quoting over a block-pinned pool snapshot: price impact, target-price sizing, hypothetical liquidity.
maker_equity cargo run --example maker_equity Batched maker settle previews (get_maker_equities) plus a liquidation gated on the contract's own health check.

API Overview

Client Setup

use perpcity_sdk::prelude::*;

// 1. Transport — single endpoint or read/write split
let transport = HftTransport::new(
    TransportConfig::builder()
        .shared_endpoint("https://sepolia-rollup.arbitrum.io/rpc")
        .build()?,
)?;

// 2. One chain reader per process — every client and reader shares its caches
let chain = ChainReader::arbitrum_sepolia(transport);

// 3. A signing client for one market
let client = PerpClient::new(chain.market(perp), signer);

// 4. Warm caches (required before first transaction)
client.sync_nonce().await?;
client.chain().refresh_gas().await?;
client.ensure_approval(U256::MAX).await?;

Trading

// Open a long with 10 USDC margin and 1 perp of exposure.
let open = client.open_taker(&OpenTakerParams {
    margin: 10.0,
    perp_delta: 1.0,
    amt1_limit: 0,
}, Urgency::Normal).await?;

// Close it: the SDK reads the exact delta on-chain and reverses it
let result = client.close_taker(open.pos_id, Urgency::Normal).await?;

Every write method takes an Urgency level that scales the EIP-1559 priority fee:

Urgency Priority fee multiplier Use case
Low 0.8x Background tasks
Normal 1.0x Standard trading
High 1.5x Time-sensitive fills
Critical 2.0x Liquidation defense

Market Data

// Snapshot — config + live data, one block, in one multicall plus the index
let (config, snapshot) = client.market().get_snapshot().await?;

// Or individually
let price    = client.market().get_pool_price().await?;        // the pool's spot price, f64
let funding  = client.market().get_funding_rate().await?;      // daily rate
let oi       = client.market().get_open_interest().await?;      // long/short OI
let cap      = client.market().get_capacity().await?;           // capacity + OI at one block
let headroom = cap.headroom_atoms(Side::Short);        // short OI still openable, perp atoms
let mark     = client.market().get_mark().await?;               // what the contract marks from; .fair_price_x96()
let position = client.market().get_position(open.pos_id).await?; // raw on-chain Position

// Storage at one block: the handle is the block, so nothing read through
// it can come from another. `state()` pins the lagged snapshot block;
// `state_at(n)` a block you name (archive endpoint for old ones).
let state    = client.market().state().await?;
let books    = state.solvency().await?;                        // badDebt, totalMargin (USDC)
let held     = state.collateral().await?;                      // the perp's USDC
let band     = state.maker_band(open.pos_id).await?;           // Some(MakerBand) for a live maker
let at_block = state.block();                                  // number, hash, timestamp

// Batch balances — N addresses in 1 multicall (1 CU instead of 2N)
let Balances { usdc, eth_wei } = client.chain().get_balances(address).await?; // usdc: UsdcAtoms
let all = client.chain().get_balances_batch(&addresses).await?;

Maker Equity and Liquidations

get_maker_equities computes, off-chain and pinned to one block, exactly what the contract would settle for each open maker position if it were touched now — margin, accrued funding, utilization earnings, uncollected V4 LP fees, and inventory PnL (validated against a real on-chain liquidation settle). Every input id gets exactly one outcome, in input order: Computed(breakdown), NotAMaker, or Failed(error).

Four conventions to know:

  • Exact atoms, f64 at the edge. Every figure is a units type: the signed components (margin(), funding_owed(), lp_fees(), unrealized_pnl(), settled_margin(), equity(), accrued_income()) are UsdcDelta, and position_value() is UsdcAtoms. .atoms() is the exact integer the contract settles in; .usdc() is the f64 for a display. Do accounting in atoms; print in USDC.
  • Funding sign. funding_owed() is what the position owes since its last settle: positive means the position pays, and it is subtracted when settling margin. The earnings components, utilization and LP fees, are positive when the position receives.
  • Health is per position. The deployed contracts liquidate a maker when equity over position value plus one atom, in millionths and floored, falls under the ratio stored on that position (PerpLogic.isHealthy): not a market-wide ratio, not relative to margin, and with no fee taken first. is_liquidatable() is that test in the contract's integers, over position_value() and liquidation_margin_ratio(); margin_ratio() is the same ratio as an f64 for a display. liquidation_prices() finds the marks the test turns at as the price moves, and its distance() is the nearer one as a fraction of the mark. Confirm with simulate_liquidate_maker before sending, from the address that will send: a liquidation can still revert after the test passes.
  • Pinning is automatic. Every read in a batch, including the mark that prices valPnl (the contract's own fair price for the block, of the pool price, beacon index and block-advanced EMAs), comes from one reorg-safe block a few blocks behind the head. There is no mark to supply and no way to mix state from different blocks; get_maker_equities_at_mark(pos_ids, mark) takes a Price for what-if pricing over the same pinned state.
for outcome in client.market().get_maker_equities(&pos_ids).await? {
    if let MakerEquityKind::Computed(b) = outcome.kind {
        println!(
            "pos {}: equity {:.6} (accrued {:+.6}), distance {:?}",
            outcome.pos_id,
            b.equity().usdc(),
            b.accrued_income().usdc(),
            b.liquidation_prices()?.distance(),
        );
    }
}

// Liquidations gate on the contract's own health check; typed reverts
// distinguish "not yet" (NotLiquidatable) from "never" (NonMakerPosition).
if client.simulate_liquidate_maker(pos_id, me).await.is_ok() {
    client.liquidate_maker(pos_id, me, Urgency::Critical).await?;
}

See examples/maker_equity.rs for the full flow.

HFT Infrastructure

The SDK is designed for sub-millisecond transaction preparation on the hot path.

Multi-endpoint transport with read/write split — route reads to free public RPCs, writes to paid endpoints:

let transport = HftTransport::new(
    TransportConfig::builder()
        .shared_endpoint("https://arb-mainnet.g.alchemy.com/v2/KEY")  // writes + read fallback
        .read_endpoint("https://arbitrum-one-rpc.publicnode.com")      // dedicated reads
        .strategy(Strategy::LatencyBased)
        .request_timeout(Duration::from_millis(2000))
        .build()?,
)?;

Each pool gets independent circuit breakers — if the read endpoint goes down, reads automatically fall back to the shared endpoint.

Lock-free nonce management — AtomicU64::fetch_add for O(1) nonce acquisition. No mutex on the hot path.

Fee cache — EIP-1559 base fee + priority fee cached from block headers. Refreshed per block.

Gas limit cache — eth_estimateGas results cached by function selector (1 hour TTL, 20% buffer). First call estimates, subsequent calls use the cache.

2-tier state cache:

  • Slow tier (60s TTL): fees, margin bounds — rarely change
  • Fast tier (2s TTL): mark price, funding rate, USDC balance — refreshed per block

Position manager — track open positions with automated triggers:

pos_manager.track(ManagedPosition {
    perp_id: perp_bytes,
    position_id: pos_id,
    is_long: true,
    entry_price: mark,
    margin: 10.0,
    stop_loss: Some(mark * 0.98),
    take_profit: Some(mark * 1.05),
    trailing_stop_pct: Some(0.03),
    trailing_stop_anchor: None,
});

Latency tracker — rolling-window stats (P50/P95/P99) for monitoring RPC and tx latency.

Math Utilities

use perpcity_sdk::{price_to_tick, tick_to_price, align_tick_down};
use perpcity_sdk::math::position::{entry_price, liquidation_price};
use perpcity_sdk::math::liquidity::estimate_liquidity;

let tick = price_to_tick(50.0)?;
let price = tick_to_price(tick)?;

// A maker's geometry: a range is valid by construction, a band is a range
// holding liquidity — every function below takes them and trusts them
use perpcity_sdk::{MakerBand, Side, TickRange, band_capacity, liquidity_for_capacity};
let range = TickRange::new(tick_lower, tick_upper)?;
let liq = estimate_liquidity(&range, margin_scaled)?;

// Taker capacity a band adds at the pool price, and its inverse
let cap = band_capacity(sqrt_price_x96, &MakerBand::new(range, liquidity))?;
let liq = liquidity_for_capacity(sqrt_price_x96, &range, Side::Short, 1_000_000)?;

All math functions are pure, O(1), and ported faithfully from PerpCity's Solidity contracts and Uniswap V4's TickMath.

Environment Variables

Variable Required Description
PERPCITY_PRIVATE_KEY Yes Hex-encoded private key (with or without 0x prefix)
PERPCITY_PERP Yes Address of the Perp market contract
PERPCITY_USDC No USDC token address (defaults to Arbitrum Sepolia test USDC)
RPC_URL No RPC endpoint (default: https://sepolia-rollup.arbitrum.io/rpc)
RPC_URL_1, RPC_URL_2 No Multi-endpoint config for hft_bot example

Configuration

Chains and markets

A ChainReader holds what every market on a chain shares — the transport, the collateral token, the pool manager, and the caches — and hands out a MarketReader per Perp contract. ChainReader::arbitrum and ChainReader::arbitrum_sepolia fill in the canonical addresses and chain id:

let perp: Address = std::env::var("PERPCITY_PERP")?.parse()?;

let chain = ChainReader::arbitrum_sepolia(transport); // test USDC 0xBEF280Be…, not Circle's
let client = PerpClient::new(chain.market(perp), signer);

For Arbitrum One, ChainReader::arbitrum(transport) uses canonical Circle USDC (0xaf88d065e77c8cC2239327C5EDb3A432268e5831) and chain id 42161. For any other collateral token or chain, build the reader with ChainReader::new(transport, ChainDeployments { usdc, pool_manager }, chain_id). Reads need no signer: chain.market(perp) on its own answers every market read, and one chain reader serves any number of markets and clients.

Release Profile

The crate ships with aggressive release optimizations for trading workloads:

[profile.release]
lto = "fat"           # Cross-crate inlining
codegen-units = 1     # Maximum optimization
panic = "abort"       # No unwind overhead
strip = "symbols"     # Smaller binary

Benchmarks

cargo bench
Benchmark What it measures
math_bench Tick math, price conversions, entry/liquidation price
hft_bench Nonce acquire (~1-5ns), gas peek, cache hit/miss, position triggers
transport_bench Endpoint selection, circuit breaker state checks, struct sizes

License

MIT

About

No description, website, or topics provided.

Resources

Contributing

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages