perpcity-sdk 0.2.1

Rust SDK for the PerpCity perpetual futures protocol on Base L2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! On-chain contract bindings generated via Alloy's `sol!` macro.
//!
//! Structs, events, errors, and function selectors are derived directly from
//! `perpcity-contracts/src/interfaces/IPerpManager.sol` and related interfaces.
//! The `sol!` macro produces ABI-compatible Rust types automatically — no
//! manual encoding or decoding is needed.

use alloy::sol;

sol! {
    // ═══════════════════════════════════════════════════════════════════
    //  Uniswap V4 types used by PerpCity
    // ═══════════════════════════════════════════════════════════════════

    /// Identifies a Uniswap V4 pool (and PerpCity perp) by its constituent
    /// parameters.
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }

    /// Swap configuration for quoting through the Uniswap V4 pool.
    struct SwapConfig {
        PoolKey poolKey;
        bool isExactIn;
        bool zeroForOne;
        uint256 amountSpecified;
        uint160 sqrtPriceLimitX96;
        uint128 unspecifiedAmountLimit;
    }

    // ═══════════════════════════════════════════════════════════════════
    //  Module interfaces
    // ═══════════════════════════════════════════════════════════════════

    /// Fee module — returns trading fees for a perp.
    #[sol(rpc)]
    interface IFees {
        function fees(PerpManager.PerpConfig calldata perp)
            external
            returns (uint24 cFee, uint24 insFee, uint24 lpFee);

        function utilizationFee(PoolKey calldata key)
            external
            returns (uint24 fee);

        function liquidationFee(PerpManager.PerpConfig calldata perp)
            external
            returns (uint24 fee);
    }

    /// Margin ratio module — returns min/max/liquidation margin ratios.
    #[sol(rpc)]
    interface IMarginRatios {
        struct MarginRatios {
            uint24 min;
            uint24 max;
            uint24 liq;
        }

        function marginRatios(PerpManager.PerpConfig calldata perp, bool isMaker)
            external
            returns (MarginRatios memory);
    }

    // ═══════════════════════════════════════════════════════════════════
    //  PerpManager — the core protocol contract
    // ═══════════════════════════════════════════════════════════════════

    /// The PerpManager contract interface. Contains all structs, events,
    /// errors, and function signatures from IPerpManager.sol and
    /// PerpManager.sol.
    #[sol(rpc)]
    interface PerpManager {
        // ── Structs ──────────────────────────────────────────────

        struct PerpConfig {
            PoolKey key;
            address creator;
            address vault;
            address beacon;
            address fees;
            address marginRatios;
            address lockupPeriod;
            address sqrtPriceImpactLimit;
        }

        struct Position {
            bytes32 perpId;
            uint256 margin;
            int256 entryPerpDelta;
            int256 entryUsdDelta;
            int256 entryCumlFundingX96;
            uint256 entryCumlBadDebtX96;
            uint256 entryCumlUtilizationX96;
            IMarginRatios.MarginRatios marginRatios;
            MakerDetails makerDetails;
        }

        struct MakerDetails {
            uint32 unlockTimestamp;
            int24 tickLower;
            int24 tickUpper;
            uint128 liquidity;
            int256 entryCumlFundingBelowX96;
            int256 entryCumlFundingWithinX96;
            int256 entryCumlFundingDivSqrtPWithinX96;
        }

        struct CreatePerpParams {
            address beacon;
            address fees;
            address marginRatios;
            address lockupPeriod;
            address sqrtPriceImpactLimit;
            uint160 startingSqrtPriceX96;
        }

        struct OpenMakerPositionParams {
            address holder;
            uint128 margin;
            uint120 liquidity;
            int24 tickLower;
            int24 tickUpper;
            uint128 maxAmt0In;
            uint128 maxAmt1In;
        }

        struct OpenTakerPositionParams {
            address holder;
            bool isLong;
            uint128 margin;
            uint24 marginRatio;
            uint128 unspecifiedAmountLimit;
        }

        struct AdjustNotionalParams {
            uint256 posId;
            int256 usdDelta;
            uint128 perpLimit;
        }

        struct AdjustMarginParams {
            uint256 posId;
            int256 marginDelta;
        }

        struct ClosePositionParams {
            uint256 posId;
            uint128 minAmt0Out;
            uint128 minAmt1Out;
            uint128 maxAmt1In;
        }

        // ── Events ───────────────────────────────────────────────

        event PerpCreated(
            bytes32 perpId,
            address beacon,
            uint256 sqrtPriceX96,
            uint256 indexPriceX96
        );

        event PositionOpened(
            bytes32 perpId,
            uint256 sqrtPriceX96,
            uint256 longOI,
            uint256 shortOI,
            uint256 posId,
            bool isMaker,
            int256 perpDelta,
            int256 usdDelta,
            int24 tickLower,
            int24 tickUpper
        );

        event NotionalAdjusted(
            bytes32 perpId,
            uint256 sqrtPriceX96,
            uint256 longOI,
            uint256 shortOI,
            uint256 posId,
            int256 newPerpDelta,
            // Settlement details
            int256 swapPerpDelta,
            int256 swapUsdDelta,
            int256 funding,
            uint256 utilizationFee,
            uint256 adl,
            uint256 tradingFees
        );

        event MarginAdjusted(
            bytes32 perpId,
            uint256 posId,
            uint256 newMargin
        );

        event PositionClosed(
            bytes32 perpId,
            uint256 sqrtPriceX96,
            uint256 longOI,
            uint256 shortOI,
            uint256 posId,
            bool wasMaker,
            bool wasLiquidated,
            bool wasPartialClose,
            int256 exitPerpDelta,
            int256 exitUsdDelta,
            int24 tickLower,
            int24 tickUpper,
            // Settlement details
            int256 netUsdDelta,
            int256 funding,
            uint256 utilizationFee,
            uint256 adl,
            uint256 liquidationFee,
            int256 netMargin
        );

        event FeesModuleRegistered(address feesModule);
        event MarginRatiosModuleRegistered(address marginRatiosModule);
        event LockupPeriodModuleRegistered(address lockupPeriodModule);
        event SqrtPriceImpactLimitModuleRegistered(address sqrtPriceImpactLimitModule);

        // ── Errors ───────────────────────────────────────────────

        error ZeroLiquidity();
        error ZeroNotional();
        error TicksOutOfBounds();
        error InvalidMargin();
        error InvalidMarginDelta();
        error InvalidCaller();
        error PositionLocked();
        error ZeroDelta();
        error InvalidMarginRatio();
        error FeesNotRegistered();
        error MarginRatiosNotRegistered();
        error LockupPeriodNotRegistered();
        error SqrtPriceImpactLimitNotRegistered();
        error FeeTooLarge();
        error MakerNotAllowed();
        error BeaconNotRegistered();
        error PerpDoesNotExist();
        error StartingSqrtPriceTooLow();
        error StartingSqrtPriceTooHigh();
        error CouldNotFullyFill();
        error MarkTooFarFromIndex();

        // ── Perp functions ───────────────────────────────────────

        /// Creates a new perpetual market.
        function createPerp(CreatePerpParams calldata params)
            external
            returns (bytes32 perpId);

        /// Opens a maker (LP) position in a perp.
        function openMakerPos(bytes32 perpId, OpenMakerPositionParams calldata params)
            external
            returns (uint256 posId);

        /// Opens a taker (long/short) position in a perp.
        function openTakerPos(bytes32 perpId, OpenTakerPositionParams calldata params)
            external
            returns (uint256 posId);

        /// Adjusts the notional size of a taker position.
        function adjustNotional(AdjustNotionalParams calldata params) external;

        /// Adds or removes margin from an open position.
        function adjustMargin(AdjustMarginParams calldata params) external;

        /// Closes an open position (taker or maker).
        function closePosition(ClosePositionParams calldata params) external;

        /// Increases the oracle cardinality cap for a perp.
        function increaseCardinalityCap(bytes32 perpId, uint16 newCardinalityCap) external;

        // ── Module registration (owner only) ─────────────────────

        function registerFeesModule(address feesModule) external;
        function registerMarginRatiosModule(address marginRatiosModule) external;
        function registerLockupPeriodModule(address lockupPeriodModule) external;
        function registerSqrtPriceImpactLimitModule(address sqrtPriceImpactLimitModule) external;

        // ── Module registration queries ──────────────────────────

        function isFeesRegistered(address feesModule)
            external view returns (bool);
        function isMarginRatiosRegistered(address marginRatiosModule)
            external view returns (bool);
        function isLockupPeriodRegistered(address lockupPeriodModule)
            external view returns (bool);
        function isSqrtPriceImpactLimitRegistered(address sqrtPriceImpactLimitModule)
            external view returns (bool);

        // ── Protocol fee functions (owner only) ──────────────────

        function setProtocolFee(uint24 newProtocolFee) external;
        function collectProtocolFees(address recipient) external;

        // ── View functions ───────────────────────────────────────

        /// Returns the perp configuration for a given pool ID.
        function cfgs(bytes32 perpId) external view returns (PerpConfig memory);

        /// Returns a position by its NFT token ID.
        function positions(uint256 posId) external view returns (Position memory);

        /// Returns the next position ID to be minted.
        function nextPosId() external view returns (uint256);

        /// Returns the current protocol fee.
        function protocolFee() external view returns (uint24);

        /// Returns the oracle cardinality cap for a perp.
        function cardinalityCap(bytes32 perpId) external view returns (uint16);

        /// Returns the time-weighted average sqrtPrice, scaled by 2^96.
        function timeWeightedAvgSqrtPriceX96(bytes32 perpId, uint32 lookbackWindow)
            external view returns (uint256 twAvg);

        /// Returns funding rate per second, scaled by 2^96.
        function fundingPerSecondX96(bytes32 perpId) external view returns (int256);

        /// Returns utilization fee per second, scaled by 2^96.
        function utilFeePerSecX96(bytes32 perpId) external view returns (uint256);

        /// Returns the insurance fund balance for a perp.
        function insurance(bytes32 perpId) external view returns (uint128);

        /// Returns taker long and short open interest.
        function takerOpenInterest(bytes32 perpId)
            external view returns (uint128 longOI, uint128 shortOI);

        // ── Quote (simulation) functions ─────────────────────────

        /// Simulates opening a maker position.
        function quoteOpenMakerPosition(bytes32 perpId, OpenMakerPositionParams calldata params)
            external
            returns (bytes memory unexpectedReason, int256 perpDelta, int256 usdDelta);

        /// Simulates opening a taker position.
        function quoteOpenTakerPosition(bytes32 perpId, OpenTakerPositionParams calldata params)
            external
            returns (bytes memory unexpectedReason, int256 perpDelta, int256 usdDelta);

        /// Simulates closing a position — returns PnL, funding, and liquidation status.
        function quoteClosePosition(uint256 posId)
            external
            returns (
                bytes memory unexpectedReason,
                int256 pnl,
                int256 funding,
                int256 netMargin,
                bool wasLiquidated,
                uint256 notional
            );

        /// Simulates a swap in a perp's Uniswap V4 pool.
        function quoteSwap(
            bytes32 perpId,
            bool zeroForOne,
            bool isExactIn,
            uint256 amount,
            uint160 sqrtPriceLimitX96
        )
            external
            returns (bytes memory unexpectedReason, int256 perpDelta, int256 usdDelta);

        /// Simulates two sequential swaps.
        function quoteTwoSwaps(bytes32 perpId, SwapConfig memory first, SwapConfig memory second)
            external
            returns (
                bytes memory unexpectedReason,
                int256 perpDelta1,
                int256 usdDelta1,
                int256 perpDelta2,
                int256 usdDelta2
            );

        // ── ERC721 metadata ──────────────────────────────────────

        function name() external pure returns (string memory);
        function symbol() external pure returns (string memory);
        function tokenURI(uint256 tokenId) external pure returns (string memory);
        function ownerOf(uint256 tokenId) external view returns (address);
    }

    // ═══════════════════════════════════════════════════════════════════
    //  Beacon — oracle index contract
    // ═══════════════════════════════════════════════════════════════════

    /// Beacon interface — emits `IndexUpdated` when the oracle index changes.
    /// Each perp has its own beacon (from `PerpConfig.beacon`).
    #[sol(rpc)]
    interface IBeacon {
        event IndexUpdated(uint256 index);

        function index() external view returns (uint256);
    }

    // ═══════════════════════════════════════════════════════════════════
    //  ERC20 (USDC) — minimal interface for approve + balanceOf
    // ═══════════════════════════════════════════════════════════════════

    /// Minimal ERC20 interface for USDC interactions.
    #[sol(rpc)]
    interface IERC20 {
        function approve(address spender, uint256 amount)
            external
            returns (bool);

        function allowance(address owner, address spender)
            external view returns (uint256);

        function balanceOf(address account)
            external view returns (uint256);

        function transfer(address to, uint256 amount)
            external
            returns (bool);

        function transferFrom(address from, address to, uint256 amount)
            external
            returns (bool);

        event Transfer(address indexed from, address indexed to, uint256 value);
        event Approval(address indexed owner, address indexed spender, uint256 value);
    }

    // ═══════════════════════════════════════════════════════════════════
    //  Multicall3 — batch multiple contract reads into a single eth_call
    // ═══════════════════════════════════════════════════════════════════

    /// Multicall3 interface for batching contract reads.
    ///
    /// Deployed at `0xcA11bde05977b3631167028862bE2a173976CA11` on all
    /// major EVM chains (including Base mainnet and Base Sepolia).
    /// A single `aggregate3` call executes N sub-calls and returns all
    /// results — the RPC provider charges 1 CU regardless of N.
    #[sol(rpc)]
    interface IMulticall3 {
        struct Call3 {
            address target;
            bool allowFailure;
            bytes callData;
        }

        struct Result {
            bool success;
            bytes returnData;
        }

        function aggregate3(Call3[] calldata calls)
            external payable returns (Result[] memory returnData);

        function getEthBalance(address addr)
            external view returns (uint256 balance);
    }
}