@strobelabs/perpcity-sdk 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -23,7 +23,6 @@ __export(index_exports, {
23
23
  BEACON_ABI: () => BEACON_ABI,
24
24
  BIGINT_1E6: () => BIGINT_1E6,
25
25
  ContractError: () => ContractError,
26
- GraphQLError: () => GraphQLError,
27
26
  InsufficientFundsError: () => InsufficientFundsError,
28
27
  NUMBER_1E6: () => NUMBER_1E6,
29
28
  OpenPosition: () => OpenPosition,
@@ -38,22 +37,11 @@ __export(index_exports, {
38
37
  closePosition: () => closePosition,
39
38
  createPerp: () => createPerp,
40
39
  estimateLiquidity: () => estimateLiquidity,
41
- getAllMakerPositions: () => getAllMakerPositions,
42
- getAllTakerPositions: () => getAllTakerPositions,
43
40
  getPerpBeacon: () => getPerpBeacon,
44
41
  getPerpBounds: () => getPerpBounds,
45
42
  getPerpFees: () => getPerpFees,
46
- getPerpFundingRate: () => getPerpFundingRate,
47
- getPerpFundingRateTimeSeries: () => getPerpFundingRateTimeSeries,
48
- getPerpIndex: () => getPerpIndex,
49
- getPerpIndexTimeSeries: () => getPerpIndexTimeSeries,
50
- getPerpLastIndexUpdate: () => getPerpLastIndexUpdate,
51
43
  getPerpMark: () => getPerpMark,
52
- getPerpMarkTimeSeries: () => getPerpMarkTimeSeries,
53
- getPerpOpenInterest: () => getPerpOpenInterest,
54
- getPerpOpenInterestTimeSeries: () => getPerpOpenInterestTimeSeries,
55
44
  getPerpTickSpacing: () => getPerpTickSpacing,
56
- getPerps: () => getPerps,
57
45
  getPositionEffectiveMargin: () => getPositionEffectiveMargin,
58
46
  getPositionFundingPayment: () => getPositionFundingPayment,
59
47
  getPositionId: () => getPositionId,
@@ -64,12 +52,8 @@ __export(index_exports, {
64
52
  getPositionLiveDetailsFromContract: () => getPositionLiveDetailsFromContract,
65
53
  getPositionPerpId: () => getPositionPerpId,
66
54
  getPositionPnl: () => getPositionPnl,
67
- getTotalOpenMakerPnl: () => getTotalOpenMakerPnl,
68
- getTotalOpenTakerPnl: () => getTotalOpenTakerPnl,
69
- getUserClosedPositions: () => getUserClosedPositions,
55
+ getRpcUrl: () => getRpcUrl,
70
56
  getUserOpenPositions: () => getUserOpenPositions,
71
- getUserRealizedPnl: () => getUserRealizedPnl,
72
- getUserUnrealizedPnl: () => getUserUnrealizedPnl,
73
57
  getUserUsdcBalance: () => getUserUsdcBalance,
74
58
  getUserWalletAddress: () => getUserWalletAddress,
75
59
  marginRatioToLeverage: () => marginRatioToLeverage,
@@ -88,9 +72,7 @@ __export(index_exports, {
88
72
  module.exports = __toCommonJS(index_exports);
89
73
 
90
74
  // src/context.ts
91
- var import_graphql_request = require("graphql-request");
92
75
  var import_viem3 = require("viem");
93
- var import_graphql = require("graphql");
94
76
 
95
77
  // src/utils/constants.ts
96
78
  var NUMBER_1E6 = 1e6;
@@ -155,24 +137,218 @@ async function approveUsdc(context, amount, confirmations = DEFAULT_CONFIRMATION
155
137
  });
156
138
  }
157
139
 
140
+ // src/utils/liquidity.ts
141
+ async function estimateLiquidity(context, tickLower, tickUpper, usdScaled) {
142
+ const Q962 = 1n << 96n;
143
+ const sqrtPriceLowerX96 = getSqrtRatioAtTick(tickLower);
144
+ const sqrtPriceUpperX96 = getSqrtRatioAtTick(tickUpper);
145
+ const sqrtPriceDiff = sqrtPriceUpperX96 - sqrtPriceLowerX96;
146
+ const liquidity = usdScaled * Q962 / sqrtPriceDiff;
147
+ return liquidity;
148
+ }
149
+ function getSqrtRatioAtTick(tick) {
150
+ const absTick = Math.abs(tick);
151
+ let ratio = 0xfffcb933bd6fad37aa2d162d1a594001n;
152
+ if (absTick & 1) ratio = ratio * 0xfff97272373d413259a46990580e213an >> 128n;
153
+ if (absTick & 2) ratio = ratio * 0xfff2e50f5f656932ef12357cf3c7fdccn >> 128n;
154
+ if (absTick & 4) ratio = ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0n >> 128n;
155
+ if (absTick & 8) ratio = ratio * 0xffcb9843d60f6159c9db58835c926644n >> 128n;
156
+ if (absTick & 16) ratio = ratio * 0xff973b41fa98c081472e6896dfb254c0n >> 128n;
157
+ if (absTick & 32) ratio = ratio * 0xff2ea16466c96a3843ec78b326b52861n >> 128n;
158
+ if (absTick & 64) ratio = ratio * 0xfe5dee046a99a2a811c461f1969c3053n >> 128n;
159
+ if (absTick & 128) ratio = ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4n >> 128n;
160
+ if (absTick & 256) ratio = ratio * 0xf987a7253ac413176f2b074cf7815e54n >> 128n;
161
+ if (absTick & 512) ratio = ratio * 0xf3392b0822b70005940c7a398e4b70f3n >> 128n;
162
+ if (absTick & 1024) ratio = ratio * 0xe7159475a2c29b7443b29c7fa6e889d9n >> 128n;
163
+ if (absTick & 2048) ratio = ratio * 0xd097f3bdfd2022b8845ad8f792aa5825n >> 128n;
164
+ if (absTick & 4096) ratio = ratio * 0xa9f746462d870fdf8a65dc1f90e061e5n >> 128n;
165
+ if (absTick & 8192) ratio = ratio * 0x70d869a156d2a1b890bb3df62baf32f7n >> 128n;
166
+ if (absTick & 16384) ratio = ratio * 0x31be135f97d08fd981231505542fcfa6n >> 128n;
167
+ if (absTick & 32768) ratio = ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9n >> 128n;
168
+ if (absTick & 65536) ratio = ratio * 0x5d6af8dedb81196699c329225ee604n >> 128n;
169
+ if (absTick & 131072) ratio = ratio * 0x2216e584f5fa1ea926041bedfe98n >> 128n;
170
+ if (absTick & 262144) ratio = ratio * 0x48a170391f7dc42444e8fa2n >> 128n;
171
+ if (tick > 0) ratio = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn / ratio;
172
+ return ratio % (1n << 32n) > 0n ? (ratio >> 32n) + 1n : ratio >> 32n;
173
+ }
174
+
175
+ // src/utils/errors.ts
176
+ var import_viem2 = require("viem");
177
+ var PerpCityError = class extends Error {
178
+ constructor(message, cause) {
179
+ super(message);
180
+ this.cause = cause;
181
+ this.name = "PerpCityError";
182
+ }
183
+ };
184
+ var ContractError = class extends PerpCityError {
185
+ constructor(message, errorName, args, cause) {
186
+ super(message, cause);
187
+ this.errorName = errorName;
188
+ this.args = args;
189
+ this.name = "ContractError";
190
+ }
191
+ };
192
+ var TransactionRejectedError = class extends PerpCityError {
193
+ constructor(message = "Transaction rejected by user", cause) {
194
+ super(message, cause);
195
+ this.name = "TransactionRejectedError";
196
+ }
197
+ };
198
+ var InsufficientFundsError = class extends PerpCityError {
199
+ constructor(message = "Insufficient funds for transaction", cause) {
200
+ super(message, cause);
201
+ this.name = "InsufficientFundsError";
202
+ }
203
+ };
204
+ var RPCError = class extends PerpCityError {
205
+ constructor(message, cause) {
206
+ super(message, cause);
207
+ this.name = "RPCError";
208
+ }
209
+ };
210
+ var ValidationError = class extends PerpCityError {
211
+ constructor(message, cause) {
212
+ super(message, cause);
213
+ this.name = "ValidationError";
214
+ }
215
+ };
216
+ function parseContractError(error) {
217
+ if (error instanceof PerpCityError) {
218
+ return error;
219
+ }
220
+ if (error instanceof import_viem2.BaseError) {
221
+ const revertError = error.walk((err) => err instanceof import_viem2.ContractFunctionRevertedError);
222
+ if (revertError instanceof import_viem2.ContractFunctionRevertedError) {
223
+ const errorName = revertError.data?.errorName ?? "Unknown";
224
+ const args = revertError.data?.args ?? [];
225
+ const message = formatContractError(errorName, args);
226
+ return new ContractError(message, errorName, args, error);
227
+ }
228
+ if (error.message?.includes("User rejected") || error.code === 4001) {
229
+ return new TransactionRejectedError(error.message, error);
230
+ }
231
+ if (error.message?.includes("insufficient funds")) {
232
+ return new InsufficientFundsError(error.message, error);
233
+ }
234
+ return new PerpCityError(error.shortMessage || error.message, error);
235
+ }
236
+ if (error instanceof Error) {
237
+ return new PerpCityError(error.message, error);
238
+ }
239
+ return new PerpCityError(String(error));
240
+ }
241
+ function formatContractError(errorName, args) {
242
+ switch (errorName) {
243
+ case "InvalidBeaconAddress":
244
+ return `Invalid beacon address: ${args[0]}`;
245
+ case "InvalidTradingFeeSplits":
246
+ return `Invalid trading fee splits. Insurance split: ${args[0]}, Creator split: ${args[1]}`;
247
+ case "InvalidMaxOpeningLev":
248
+ return `Invalid maximum opening leverage: ${args[0]}`;
249
+ case "InvalidLiquidationLev":
250
+ return `Invalid liquidation leverage: ${args[0]}. Must be less than max opening leverage: ${args[1]}`;
251
+ case "InvalidLiquidationFee":
252
+ return `Invalid liquidation fee: ${args[0]}`;
253
+ case "InvalidLiquidatorFeeSplit":
254
+ return `Invalid liquidator fee split: ${args[0]}`;
255
+ case "InvalidClose":
256
+ return `Cannot close position. Caller: ${args[0]}, Holder: ${args[1]}, Is Liquidated: ${args[2]}`;
257
+ case "InvalidCaller":
258
+ return `Invalid caller. Expected: ${args[1]}, Got: ${args[0]}`;
259
+ case "InvalidLiquidity":
260
+ return `Invalid liquidity amount: ${args[0]}`;
261
+ case "InvalidMargin":
262
+ return `Invalid margin amount: ${args[0]}`;
263
+ case "InvalidLevX96":
264
+ return `Invalid leverage: ${args[0]}. Maximum allowed: ${args[1]}`;
265
+ case "MakerPositionLocked":
266
+ return `Maker position is locked until ${new Date(Number(args[1]) * 1e3).toISOString()}. Current time: ${new Date(Number(args[0]) * 1e3).toISOString()}`;
267
+ case "MaximumAmountExceeded":
268
+ return `Maximum amount exceeded. Maximum: ${args[0]}, Requested: ${args[1]}`;
269
+ case "MinimumAmountInsufficient":
270
+ return `Minimum amount not met. Required: ${args[0]}, Received: ${args[1]}`;
271
+ case "PriceImpactTooHigh":
272
+ return `Price impact too high. Current price: ${args[0]}, Min acceptable: ${args[1]}, Max acceptable: ${args[2]}`;
273
+ case "SwapReverted":
274
+ return "Swap failed. This may be due to insufficient liquidity or slippage tolerance.";
275
+ case "ZeroSizePosition":
276
+ return `Cannot create zero-size position. Perp delta: ${args[0]}, USD delta: ${args[1]}`;
277
+ case "InvalidFundingInterval":
278
+ return `Invalid funding interval: ${args[0]}`;
279
+ case "InvalidPriceImpactBand":
280
+ return `Invalid price impact band: ${args[0]}`;
281
+ case "InvalidMarketDeathThreshold":
282
+ return `Invalid market death threshold: ${args[0]}`;
283
+ case "InvalidTickRange":
284
+ return `Invalid tick range. Lower: ${args[0]}, Upper: ${args[1]}`;
285
+ case "MarketNotKillable":
286
+ return `Market health (${args[0]}) is above death threshold (${args[1]}). Market cannot be killed yet.`;
287
+ case "InvalidStartingSqrtPriceX96":
288
+ return `Invalid starting sqrt price: ${args[0]}`;
289
+ default:
290
+ return `Contract error: ${errorName}${args.length > 0 ? ` (${args.join(", ")})` : ""}`;
291
+ }
292
+ }
293
+ async function withErrorHandling(fn, context) {
294
+ try {
295
+ return await fn();
296
+ } catch (error) {
297
+ const parsedError = parseContractError(error);
298
+ parsedError.message = `${context}: ${parsedError.message}`;
299
+ throw parsedError;
300
+ }
301
+ }
302
+
303
+ // src/utils/rpc.ts
304
+ function getRpcUrl(config = {}) {
305
+ const rpcUrl = config.url ?? process.env.RPC_URL;
306
+ if (!rpcUrl) {
307
+ throw new Error(
308
+ "RPC_URL is required. Please set the RPC_URL environment variable with your full RPC endpoint URL.\nExample URLs (use your own provider and API key):\n https://base-sepolia.g.alchemy.com/v2/YOUR_API_KEY\n https://base-sepolia.infura.io/v3/YOUR_API_KEY\n https://sepolia.base.org"
309
+ );
310
+ }
311
+ return rpcUrl;
312
+ }
313
+
158
314
  // src/abis/perp-manager.ts
159
315
  var PERP_MANAGER_ABI = [
160
316
  {
161
317
  "inputs": [
162
- {
163
- "internalType": "contract IPoolManager",
164
- "name": "poolManager",
165
- "type": "address"
166
- },
167
318
  {
168
319
  "internalType": "address",
169
- "name": "usdc",
320
+ "name": "owner",
170
321
  "type": "address"
171
322
  }
172
323
  ],
173
324
  "stateMutability": "nonpayable",
174
325
  "type": "constructor"
175
326
  },
327
+ {
328
+ "inputs": [],
329
+ "name": "AccountBalanceOverflow",
330
+ "type": "error"
331
+ },
332
+ {
333
+ "inputs": [],
334
+ "name": "AlreadyInitialized",
335
+ "type": "error"
336
+ },
337
+ {
338
+ "inputs": [],
339
+ "name": "BalanceQueryForZeroAddress",
340
+ "type": "error"
341
+ },
342
+ {
343
+ "inputs": [],
344
+ "name": "FeeTooLarge",
345
+ "type": "error"
346
+ },
347
+ {
348
+ "inputs": [],
349
+ "name": "FeesNotRegistered",
350
+ "type": "error"
351
+ },
176
352
  {
177
353
  "inputs": [
178
354
  {
@@ -185,42 +361,10 @@ var PERP_MANAGER_ABI = [
185
361
  "type": "error"
186
362
  },
187
363
  {
188
- "inputs": [
189
- {
190
- "internalType": "address",
191
- "name": "caller",
192
- "type": "address"
193
- },
194
- {
195
- "internalType": "address",
196
- "name": "expectedCaller",
197
- "type": "address"
198
- }
199
- ],
364
+ "inputs": [],
200
365
  "name": "InvalidCaller",
201
366
  "type": "error"
202
367
  },
203
- {
204
- "inputs": [
205
- {
206
- "internalType": "address",
207
- "name": "caller",
208
- "type": "address"
209
- },
210
- {
211
- "internalType": "address",
212
- "name": "holder",
213
- "type": "address"
214
- },
215
- {
216
- "internalType": "bool",
217
- "name": "isLiquidated",
218
- "type": "bool"
219
- }
220
- ],
221
- "name": "InvalidClose",
222
- "type": "error"
223
- },
224
368
  {
225
369
  "inputs": [
226
370
  {
@@ -233,13 +377,7 @@ var PERP_MANAGER_ABI = [
233
377
  "type": "error"
234
378
  },
235
379
  {
236
- "inputs": [
237
- {
238
- "internalType": "uint256",
239
- "name": "margin",
240
- "type": "uint256"
241
- }
242
- ],
380
+ "inputs": [],
243
381
  "name": "InvalidMargin",
244
382
  "type": "error"
245
383
  },
@@ -247,16 +385,26 @@ var PERP_MANAGER_ABI = [
247
385
  "inputs": [
248
386
  {
249
387
  "internalType": "uint256",
250
- "name": "currentTimestamp",
251
- "type": "uint256"
252
- },
253
- {
254
- "internalType": "uint256",
255
- "name": "lockupPeriodEnd",
388
+ "name": "marginRatio",
256
389
  "type": "uint256"
257
390
  }
258
391
  ],
259
- "name": "MakerPositionLocked",
392
+ "name": "InvalidMarginRatio",
393
+ "type": "error"
394
+ },
395
+ {
396
+ "inputs": [],
397
+ "name": "LockupPeriodNotRegistered",
398
+ "type": "error"
399
+ },
400
+ {
401
+ "inputs": [],
402
+ "name": "MakerNotAllowed",
403
+ "type": "error"
404
+ },
405
+ {
406
+ "inputs": [],
407
+ "name": "MarginRatiosNotRegistered",
260
408
  "type": "error"
261
409
  },
262
410
  {
@@ -291,47 +439,161 @@ var PERP_MANAGER_ABI = [
291
439
  "name": "MinimumAmountInsufficient",
292
440
  "type": "error"
293
441
  },
442
+ {
443
+ "inputs": [],
444
+ "name": "ModuleAlreadyRegistered",
445
+ "type": "error"
446
+ },
447
+ {
448
+ "inputs": [],
449
+ "name": "NewOwnerIsZeroAddress",
450
+ "type": "error"
451
+ },
452
+ {
453
+ "inputs": [],
454
+ "name": "NoHandoverRequest",
455
+ "type": "error"
456
+ },
457
+ {
458
+ "inputs": [],
459
+ "name": "NotOwnerNorApproved",
460
+ "type": "error"
461
+ },
294
462
  {
295
463
  "inputs": [],
296
464
  "name": "NotPoolManager",
297
465
  "type": "error"
298
466
  },
299
467
  {
300
- "inputs": [
301
- {
302
- "internalType": "bytes",
303
- "name": "reason",
304
- "type": "bytes"
305
- }
306
- ],
307
- "name": "UnexpectedRevertBytes",
468
+ "inputs": [],
469
+ "name": "PositionLocked",
308
470
  "type": "error"
309
471
  },
310
472
  {
311
- "inputs": [
312
- {
313
- "internalType": "int256",
314
- "name": "perpDelta",
315
- "type": "int256"
316
- },
317
- {
318
- "internalType": "int256",
319
- "name": "usdDelta",
320
- "type": "int256"
321
- }
322
- ],
323
- "name": "ZeroSizePosition",
473
+ "inputs": [],
474
+ "name": "SqrtPriceImpactLimitNotRegistered",
324
475
  "type": "error"
325
476
  },
326
477
  {
327
- "anonymous": false,
328
- "inputs": [
329
- {
330
- "indexed": false,
331
- "internalType": "PoolId",
332
- "name": "perpId",
333
- "type": "bytes32"
334
- },
478
+ "inputs": [],
479
+ "name": "TokenAlreadyExists",
480
+ "type": "error"
481
+ },
482
+ {
483
+ "inputs": [],
484
+ "name": "TokenDoesNotExist",
485
+ "type": "error"
486
+ },
487
+ {
488
+ "inputs": [],
489
+ "name": "TransferFromIncorrectOwner",
490
+ "type": "error"
491
+ },
492
+ {
493
+ "inputs": [],
494
+ "name": "TransferToNonERC721ReceiverImplementer",
495
+ "type": "error"
496
+ },
497
+ {
498
+ "inputs": [],
499
+ "name": "TransferToZeroAddress",
500
+ "type": "error"
501
+ },
502
+ {
503
+ "inputs": [],
504
+ "name": "Unauthorized",
505
+ "type": "error"
506
+ },
507
+ {
508
+ "inputs": [],
509
+ "name": "ZeroDelta",
510
+ "type": "error"
511
+ },
512
+ {
513
+ "anonymous": false,
514
+ "inputs": [
515
+ {
516
+ "indexed": true,
517
+ "internalType": "address",
518
+ "name": "owner",
519
+ "type": "address"
520
+ },
521
+ {
522
+ "indexed": true,
523
+ "internalType": "address",
524
+ "name": "account",
525
+ "type": "address"
526
+ },
527
+ {
528
+ "indexed": true,
529
+ "internalType": "uint256",
530
+ "name": "id",
531
+ "type": "uint256"
532
+ }
533
+ ],
534
+ "name": "Approval",
535
+ "type": "event"
536
+ },
537
+ {
538
+ "anonymous": false,
539
+ "inputs": [
540
+ {
541
+ "indexed": true,
542
+ "internalType": "address",
543
+ "name": "owner",
544
+ "type": "address"
545
+ },
546
+ {
547
+ "indexed": true,
548
+ "internalType": "address",
549
+ "name": "operator",
550
+ "type": "address"
551
+ },
552
+ {
553
+ "indexed": false,
554
+ "internalType": "bool",
555
+ "name": "isApproved",
556
+ "type": "bool"
557
+ }
558
+ ],
559
+ "name": "ApprovalForAll",
560
+ "type": "event"
561
+ },
562
+ {
563
+ "anonymous": false,
564
+ "inputs": [
565
+ {
566
+ "indexed": false,
567
+ "internalType": "contract IFees",
568
+ "name": "feesModule",
569
+ "type": "address"
570
+ }
571
+ ],
572
+ "name": "FeesModuleRegistered",
573
+ "type": "event"
574
+ },
575
+ {
576
+ "anonymous": false,
577
+ "inputs": [
578
+ {
579
+ "indexed": false,
580
+ "internalType": "contract ILockupPeriod",
581
+ "name": "lockupPeriodModule",
582
+ "type": "address"
583
+ }
584
+ ],
585
+ "name": "LockupPeriodModuleRegistered",
586
+ "type": "event"
587
+ },
588
+ {
589
+ "anonymous": false,
590
+ "inputs": [
591
+ {
592
+ "indexed": false,
593
+ "internalType": "PoolId",
594
+ "name": "perpId",
595
+ "type": "bytes32"
596
+ },
335
597
  {
336
598
  "indexed": false,
337
599
  "internalType": "uint256",
@@ -345,7 +607,108 @@ var PERP_MANAGER_ABI = [
345
607
  "type": "uint256"
346
608
  }
347
609
  ],
348
- "name": "MarginAdded",
610
+ "name": "MarginAdjusted",
611
+ "type": "event"
612
+ },
613
+ {
614
+ "anonymous": false,
615
+ "inputs": [
616
+ {
617
+ "indexed": false,
618
+ "internalType": "contract IMarginRatios",
619
+ "name": "marginRatiosModule",
620
+ "type": "address"
621
+ }
622
+ ],
623
+ "name": "MarginRatiosModuleRegistered",
624
+ "type": "event"
625
+ },
626
+ {
627
+ "anonymous": false,
628
+ "inputs": [
629
+ {
630
+ "indexed": false,
631
+ "internalType": "PoolId",
632
+ "name": "perpId",
633
+ "type": "bytes32"
634
+ },
635
+ {
636
+ "indexed": false,
637
+ "internalType": "uint256",
638
+ "name": "sqrtPriceX96",
639
+ "type": "uint256"
640
+ },
641
+ {
642
+ "indexed": false,
643
+ "internalType": "uint256",
644
+ "name": "longOI",
645
+ "type": "uint256"
646
+ },
647
+ {
648
+ "indexed": false,
649
+ "internalType": "uint256",
650
+ "name": "shortOI",
651
+ "type": "uint256"
652
+ },
653
+ {
654
+ "indexed": false,
655
+ "internalType": "uint256",
656
+ "name": "posId",
657
+ "type": "uint256"
658
+ },
659
+ {
660
+ "indexed": false,
661
+ "internalType": "int256",
662
+ "name": "newPerpDelta",
663
+ "type": "int256"
664
+ }
665
+ ],
666
+ "name": "NotionalAdjusted",
667
+ "type": "event"
668
+ },
669
+ {
670
+ "anonymous": false,
671
+ "inputs": [
672
+ {
673
+ "indexed": true,
674
+ "internalType": "address",
675
+ "name": "pendingOwner",
676
+ "type": "address"
677
+ }
678
+ ],
679
+ "name": "OwnershipHandoverCanceled",
680
+ "type": "event"
681
+ },
682
+ {
683
+ "anonymous": false,
684
+ "inputs": [
685
+ {
686
+ "indexed": true,
687
+ "internalType": "address",
688
+ "name": "pendingOwner",
689
+ "type": "address"
690
+ }
691
+ ],
692
+ "name": "OwnershipHandoverRequested",
693
+ "type": "event"
694
+ },
695
+ {
696
+ "anonymous": false,
697
+ "inputs": [
698
+ {
699
+ "indexed": true,
700
+ "internalType": "address",
701
+ "name": "oldOwner",
702
+ "type": "address"
703
+ },
704
+ {
705
+ "indexed": true,
706
+ "internalType": "address",
707
+ "name": "newOwner",
708
+ "type": "address"
709
+ }
710
+ ],
711
+ "name": "OwnershipTransferred",
349
712
  "type": "event"
350
713
  },
351
714
  {
@@ -366,7 +729,7 @@ var PERP_MANAGER_ABI = [
366
729
  {
367
730
  "indexed": false,
368
731
  "internalType": "uint256",
369
- "name": "startingSqrtPriceX96",
732
+ "name": "sqrtPriceX96",
370
733
  "type": "uint256"
371
734
  },
372
735
  {
@@ -391,32 +754,26 @@ var PERP_MANAGER_ABI = [
391
754
  {
392
755
  "indexed": false,
393
756
  "internalType": "uint256",
394
- "name": "posId",
757
+ "name": "sqrtPriceX96",
395
758
  "type": "uint256"
396
759
  },
397
760
  {
398
761
  "indexed": false,
399
- "internalType": "address",
400
- "name": "holder",
401
- "type": "address"
402
- },
403
- {
404
- "indexed": false,
405
- "internalType": "bool",
406
- "name": "wasMaker",
407
- "type": "bool"
762
+ "internalType": "uint256",
763
+ "name": "longOI",
764
+ "type": "uint256"
408
765
  },
409
766
  {
410
767
  "indexed": false,
411
- "internalType": "int256",
412
- "name": "perpDelta",
413
- "type": "int256"
768
+ "internalType": "uint256",
769
+ "name": "shortOI",
770
+ "type": "uint256"
414
771
  },
415
772
  {
416
773
  "indexed": false,
417
- "internalType": "int256",
418
- "name": "pnl",
419
- "type": "int256"
774
+ "internalType": "uint256",
775
+ "name": "posId",
776
+ "type": "uint256"
420
777
  },
421
778
  {
422
779
  "indexed": false,
@@ -426,15 +783,9 @@ var PERP_MANAGER_ABI = [
426
783
  },
427
784
  {
428
785
  "indexed": false,
429
- "internalType": "uint256",
430
- "name": "sqrtPriceX96",
431
- "type": "uint256"
432
- },
433
- {
434
- "indexed": false,
435
- "internalType": "int256",
436
- "name": "fundingPremiumPerSecX96",
437
- "type": "int256"
786
+ "internalType": "bool",
787
+ "name": "wasPartialClose",
788
+ "type": "bool"
438
789
  }
439
790
  ],
440
791
  "name": "PositionClosed",
@@ -452,37 +803,37 @@ var PERP_MANAGER_ABI = [
452
803
  {
453
804
  "indexed": false,
454
805
  "internalType": "uint256",
455
- "name": "posId",
806
+ "name": "sqrtPriceX96",
456
807
  "type": "uint256"
457
808
  },
458
809
  {
459
810
  "indexed": false,
460
- "internalType": "address",
461
- "name": "holder",
462
- "type": "address"
811
+ "internalType": "uint256",
812
+ "name": "longOI",
813
+ "type": "uint256"
463
814
  },
464
815
  {
465
816
  "indexed": false,
466
- "internalType": "bool",
467
- "name": "isMaker",
468
- "type": "bool"
817
+ "internalType": "uint256",
818
+ "name": "shortOI",
819
+ "type": "uint256"
469
820
  },
470
821
  {
471
822
  "indexed": false,
472
- "internalType": "int256",
473
- "name": "perpDelta",
474
- "type": "int256"
823
+ "internalType": "uint256",
824
+ "name": "posId",
825
+ "type": "uint256"
475
826
  },
476
827
  {
477
828
  "indexed": false,
478
- "internalType": "uint256",
479
- "name": "sqrtPriceX96",
480
- "type": "uint256"
829
+ "internalType": "bool",
830
+ "name": "isMaker",
831
+ "type": "bool"
481
832
  },
482
833
  {
483
834
  "indexed": false,
484
835
  "internalType": "int256",
485
- "name": "fundingPremiumPerSecX96",
836
+ "name": "entryPerpDelta",
486
837
  "type": "int256"
487
838
  }
488
839
  ],
@@ -490,74 +841,283 @@ var PERP_MANAGER_ABI = [
490
841
  "type": "event"
491
842
  },
492
843
  {
493
- "inputs": [],
494
- "name": "POOL_MANAGER",
495
- "outputs": [
844
+ "anonymous": false,
845
+ "inputs": [
496
846
  {
497
- "internalType": "contract IPoolManager",
498
- "name": "",
847
+ "indexed": false,
848
+ "internalType": "contract ISqrtPriceImpactLimit",
849
+ "name": "sqrtPriceImpactLimitModule",
499
850
  "type": "address"
500
851
  }
501
852
  ],
502
- "stateMutability": "view",
503
- "type": "function"
853
+ "name": "SqrtPriceImpactLimitModuleRegistered",
854
+ "type": "event"
504
855
  },
505
856
  {
506
- "inputs": [],
507
- "name": "USDC",
508
- "outputs": [
857
+ "anonymous": false,
858
+ "inputs": [
509
859
  {
860
+ "indexed": true,
510
861
  "internalType": "address",
511
- "name": "",
862
+ "name": "from",
863
+ "type": "address"
864
+ },
865
+ {
866
+ "indexed": true,
867
+ "internalType": "address",
868
+ "name": "to",
512
869
  "type": "address"
870
+ },
871
+ {
872
+ "indexed": true,
873
+ "internalType": "uint256",
874
+ "name": "id",
875
+ "type": "uint256"
513
876
  }
514
877
  ],
515
- "stateMutability": "view",
516
- "type": "function"
878
+ "name": "Transfer",
879
+ "type": "event"
517
880
  },
518
881
  {
519
- "inputs": [
882
+ "inputs": [],
883
+ "name": "ERC721_NAME",
884
+ "outputs": [
520
885
  {
521
- "internalType": "PoolId",
522
- "name": "perpId",
523
- "type": "bytes32"
524
- },
886
+ "internalType": "string",
887
+ "name": "",
888
+ "type": "string"
889
+ }
890
+ ],
891
+ "stateMutability": "view",
892
+ "type": "function"
893
+ },
894
+ {
895
+ "inputs": [],
896
+ "name": "ERC721_SYMBOL",
897
+ "outputs": [
898
+ {
899
+ "internalType": "string",
900
+ "name": "",
901
+ "type": "string"
902
+ }
903
+ ],
904
+ "stateMutability": "view",
905
+ "type": "function"
906
+ },
907
+ {
908
+ "inputs": [],
909
+ "name": "ERC721_URI",
910
+ "outputs": [
911
+ {
912
+ "internalType": "string",
913
+ "name": "",
914
+ "type": "string"
915
+ }
916
+ ],
917
+ "stateMutability": "view",
918
+ "type": "function"
919
+ },
920
+ {
921
+ "inputs": [],
922
+ "name": "MAX_PROTOCOL_FEE",
923
+ "outputs": [
924
+ {
925
+ "internalType": "uint24",
926
+ "name": "",
927
+ "type": "uint24"
928
+ }
929
+ ],
930
+ "stateMutability": "view",
931
+ "type": "function"
932
+ },
933
+ {
934
+ "inputs": [
525
935
  {
526
936
  "components": [
527
937
  {
528
- "internalType": "uint128",
938
+ "internalType": "uint256",
529
939
  "name": "posId",
530
- "type": "uint128"
940
+ "type": "uint256"
531
941
  },
942
+ {
943
+ "internalType": "int256",
944
+ "name": "marginDelta",
945
+ "type": "int256"
946
+ }
947
+ ],
948
+ "internalType": "struct IPerpManager.AdjustMarginParams",
949
+ "name": "params",
950
+ "type": "tuple"
951
+ }
952
+ ],
953
+ "name": "adjustMargin",
954
+ "outputs": [],
955
+ "stateMutability": "nonpayable",
956
+ "type": "function"
957
+ },
958
+ {
959
+ "inputs": [
960
+ {
961
+ "components": [
532
962
  {
533
963
  "internalType": "uint256",
534
- "name": "margin",
964
+ "name": "posId",
535
965
  "type": "uint256"
966
+ },
967
+ {
968
+ "internalType": "int256",
969
+ "name": "perpDelta",
970
+ "type": "int256"
971
+ },
972
+ {
973
+ "internalType": "uint128",
974
+ "name": "usdLimit",
975
+ "type": "uint128"
536
976
  }
537
977
  ],
538
- "internalType": "struct IPerpManager.AddMarginParams",
978
+ "internalType": "struct IPerpManager.AdjustNotionalParams",
539
979
  "name": "params",
540
980
  "type": "tuple"
541
981
  }
542
982
  ],
543
- "name": "addMargin",
983
+ "name": "adjustNotional",
544
984
  "outputs": [],
545
985
  "stateMutability": "nonpayable",
546
986
  "type": "function"
547
987
  },
988
+ {
989
+ "inputs": [
990
+ {
991
+ "internalType": "address",
992
+ "name": "account",
993
+ "type": "address"
994
+ },
995
+ {
996
+ "internalType": "uint256",
997
+ "name": "id",
998
+ "type": "uint256"
999
+ }
1000
+ ],
1001
+ "name": "approve",
1002
+ "outputs": [],
1003
+ "stateMutability": "payable",
1004
+ "type": "function"
1005
+ },
1006
+ {
1007
+ "inputs": [
1008
+ {
1009
+ "internalType": "address",
1010
+ "name": "owner",
1011
+ "type": "address"
1012
+ }
1013
+ ],
1014
+ "name": "balanceOf",
1015
+ "outputs": [
1016
+ {
1017
+ "internalType": "uint256",
1018
+ "name": "result",
1019
+ "type": "uint256"
1020
+ }
1021
+ ],
1022
+ "stateMutability": "view",
1023
+ "type": "function"
1024
+ },
1025
+ {
1026
+ "inputs": [],
1027
+ "name": "cancelOwnershipHandover",
1028
+ "outputs": [],
1029
+ "stateMutability": "payable",
1030
+ "type": "function"
1031
+ },
548
1032
  {
549
1033
  "inputs": [
550
1034
  {
551
1035
  "internalType": "PoolId",
552
- "name": "perpId",
1036
+ "name": "",
553
1037
  "type": "bytes32"
1038
+ }
1039
+ ],
1040
+ "name": "cfgs",
1041
+ "outputs": [
1042
+ {
1043
+ "components": [
1044
+ {
1045
+ "internalType": "Currency",
1046
+ "name": "currency0",
1047
+ "type": "address"
1048
+ },
1049
+ {
1050
+ "internalType": "Currency",
1051
+ "name": "currency1",
1052
+ "type": "address"
1053
+ },
1054
+ {
1055
+ "internalType": "uint24",
1056
+ "name": "fee",
1057
+ "type": "uint24"
1058
+ },
1059
+ {
1060
+ "internalType": "int24",
1061
+ "name": "tickSpacing",
1062
+ "type": "int24"
1063
+ },
1064
+ {
1065
+ "internalType": "contract IHooks",
1066
+ "name": "hooks",
1067
+ "type": "address"
1068
+ }
1069
+ ],
1070
+ "internalType": "struct PoolKey",
1071
+ "name": "key",
1072
+ "type": "tuple"
1073
+ },
1074
+ {
1075
+ "internalType": "address",
1076
+ "name": "creator",
1077
+ "type": "address"
1078
+ },
1079
+ {
1080
+ "internalType": "address",
1081
+ "name": "vault",
1082
+ "type": "address"
1083
+ },
1084
+ {
1085
+ "internalType": "address",
1086
+ "name": "beacon",
1087
+ "type": "address"
1088
+ },
1089
+ {
1090
+ "internalType": "contract IFees",
1091
+ "name": "fees",
1092
+ "type": "address"
1093
+ },
1094
+ {
1095
+ "internalType": "contract IMarginRatios",
1096
+ "name": "marginRatios",
1097
+ "type": "address"
554
1098
  },
1099
+ {
1100
+ "internalType": "contract ILockupPeriod",
1101
+ "name": "lockupPeriod",
1102
+ "type": "address"
1103
+ },
1104
+ {
1105
+ "internalType": "contract ISqrtPriceImpactLimit",
1106
+ "name": "sqrtPriceImpactLimit",
1107
+ "type": "address"
1108
+ }
1109
+ ],
1110
+ "stateMutability": "view",
1111
+ "type": "function"
1112
+ },
1113
+ {
1114
+ "inputs": [
555
1115
  {
556
1116
  "components": [
557
1117
  {
558
- "internalType": "uint128",
1118
+ "internalType": "uint256",
559
1119
  "name": "posId",
560
- "type": "uint128"
1120
+ "type": "uint256"
561
1121
  },
562
1122
  {
563
1123
  "internalType": "uint128",
@@ -581,29 +1141,69 @@ var PERP_MANAGER_ABI = [
581
1141
  }
582
1142
  ],
583
1143
  "name": "closePosition",
584
- "outputs": [
1144
+ "outputs": [],
1145
+ "stateMutability": "nonpayable",
1146
+ "type": "function"
1147
+ },
1148
+ {
1149
+ "inputs": [
585
1150
  {
586
- "internalType": "uint128",
587
- "name": "posId",
588
- "type": "uint128"
1151
+ "internalType": "address",
1152
+ "name": "recipient",
1153
+ "type": "address"
589
1154
  }
590
1155
  ],
1156
+ "name": "collectProtocolFees",
1157
+ "outputs": [],
591
1158
  "stateMutability": "nonpayable",
592
1159
  "type": "function"
593
1160
  },
1161
+ {
1162
+ "inputs": [
1163
+ {
1164
+ "internalType": "address",
1165
+ "name": "pendingOwner",
1166
+ "type": "address"
1167
+ }
1168
+ ],
1169
+ "name": "completeOwnershipHandover",
1170
+ "outputs": [],
1171
+ "stateMutability": "payable",
1172
+ "type": "function"
1173
+ },
594
1174
  {
595
1175
  "inputs": [
596
1176
  {
597
1177
  "components": [
598
- {
599
- "internalType": "uint160",
600
- "name": "startingSqrtPriceX96",
601
- "type": "uint160"
602
- },
603
1178
  {
604
1179
  "internalType": "address",
605
1180
  "name": "beacon",
606
1181
  "type": "address"
1182
+ },
1183
+ {
1184
+ "internalType": "contract IFees",
1185
+ "name": "fees",
1186
+ "type": "address"
1187
+ },
1188
+ {
1189
+ "internalType": "contract IMarginRatios",
1190
+ "name": "marginRatios",
1191
+ "type": "address"
1192
+ },
1193
+ {
1194
+ "internalType": "contract ILockupPeriod",
1195
+ "name": "lockupPeriod",
1196
+ "type": "address"
1197
+ },
1198
+ {
1199
+ "internalType": "contract ISqrtPriceImpactLimit",
1200
+ "name": "sqrtPriceImpactLimit",
1201
+ "type": "address"
1202
+ },
1203
+ {
1204
+ "internalType": "uint160",
1205
+ "name": "startingSqrtPriceX96",
1206
+ "type": "uint160"
607
1207
  }
608
1208
  ],
609
1209
  "internalType": "struct IPerpManager.CreatePerpParams",
@@ -624,31 +1224,21 @@ var PERP_MANAGER_ABI = [
624
1224
  },
625
1225
  {
626
1226
  "inputs": [
627
- {
628
- "internalType": "int24",
629
- "name": "tickA",
630
- "type": "int24"
631
- },
632
- {
633
- "internalType": "int24",
634
- "name": "tickB",
635
- "type": "int24"
636
- },
637
1227
  {
638
1228
  "internalType": "uint256",
639
- "name": "amount1",
1229
+ "name": "id",
640
1230
  "type": "uint256"
641
1231
  }
642
1232
  ],
643
- "name": "estimateLiquidityForAmount1",
1233
+ "name": "getApproved",
644
1234
  "outputs": [
645
1235
  {
646
- "internalType": "uint128",
647
- "name": "liquidity",
648
- "type": "uint128"
1236
+ "internalType": "address",
1237
+ "name": "result",
1238
+ "type": "address"
649
1239
  }
650
1240
  ],
651
- "stateMutability": "pure",
1241
+ "stateMutability": "view",
652
1242
  "type": "function"
653
1243
  },
654
1244
  {
@@ -657,29 +1247,37 @@ var PERP_MANAGER_ABI = [
657
1247
  "internalType": "PoolId",
658
1248
  "name": "perpId",
659
1249
  "type": "bytes32"
1250
+ },
1251
+ {
1252
+ "internalType": "uint16",
1253
+ "name": "cardinalityCap",
1254
+ "type": "uint16"
660
1255
  }
661
1256
  ],
662
- "name": "fees",
663
- "outputs": [
1257
+ "name": "increaseCardinalityCap",
1258
+ "outputs": [],
1259
+ "stateMutability": "nonpayable",
1260
+ "type": "function"
1261
+ },
1262
+ {
1263
+ "inputs": [
664
1264
  {
665
- "internalType": "uint24",
666
- "name": "creatorFee",
667
- "type": "uint24"
668
- },
669
- {
670
- "internalType": "uint24",
671
- "name": "insurnaceFee",
672
- "type": "uint24"
1265
+ "internalType": "address",
1266
+ "name": "owner",
1267
+ "type": "address"
673
1268
  },
674
1269
  {
675
- "internalType": "uint24",
676
- "name": "lpFee",
677
- "type": "uint24"
678
- },
1270
+ "internalType": "address",
1271
+ "name": "operator",
1272
+ "type": "address"
1273
+ }
1274
+ ],
1275
+ "name": "isApprovedForAll",
1276
+ "outputs": [
679
1277
  {
680
- "internalType": "uint24",
681
- "name": "liquidationFee",
682
- "type": "uint24"
1278
+ "internalType": "bool",
1279
+ "name": "result",
1280
+ "type": "bool"
683
1281
  }
684
1282
  ],
685
1283
  "stateMutability": "view",
@@ -688,91 +1286,17 @@ var PERP_MANAGER_ABI = [
688
1286
  {
689
1287
  "inputs": [
690
1288
  {
691
- "internalType": "PoolId",
692
- "name": "perpId",
693
- "type": "bytes32"
694
- },
695
- {
696
- "internalType": "uint128",
697
- "name": "posId",
698
- "type": "uint128"
1289
+ "internalType": "contract IFees",
1290
+ "name": "",
1291
+ "type": "address"
699
1292
  }
700
1293
  ],
701
- "name": "getPosition",
1294
+ "name": "isFeesRegistered",
702
1295
  "outputs": [
703
1296
  {
704
- "components": [
705
- {
706
- "internalType": "address",
707
- "name": "holder",
708
- "type": "address"
709
- },
710
- {
711
- "internalType": "uint256",
712
- "name": "margin",
713
- "type": "uint256"
714
- },
715
- {
716
- "internalType": "int256",
717
- "name": "perpDelta",
718
- "type": "int256"
719
- },
720
- {
721
- "internalType": "int256",
722
- "name": "usdDelta",
723
- "type": "int256"
724
- },
725
- {
726
- "internalType": "int256",
727
- "name": "entryTwPremiumX96",
728
- "type": "int256"
729
- },
730
- {
731
- "components": [
732
- {
733
- "internalType": "uint32",
734
- "name": "entryTimestamp",
735
- "type": "uint32"
736
- },
737
- {
738
- "internalType": "int24",
739
- "name": "tickLower",
740
- "type": "int24"
741
- },
742
- {
743
- "internalType": "int24",
744
- "name": "tickUpper",
745
- "type": "int24"
746
- },
747
- {
748
- "internalType": "uint128",
749
- "name": "liquidity",
750
- "type": "uint128"
751
- },
752
- {
753
- "internalType": "int256",
754
- "name": "entryTwPremiumGrowthInsideX96",
755
- "type": "int256"
756
- },
757
- {
758
- "internalType": "int256",
759
- "name": "entryTwPremiumDivBySqrtPriceGrowthInsideX96",
760
- "type": "int256"
761
- },
762
- {
763
- "internalType": "int256",
764
- "name": "entryTwPremiumGrowthBelowX96",
765
- "type": "int256"
766
- }
767
- ],
768
- "internalType": "struct IPerpManager.MakerDetails",
769
- "name": "makerDetails",
770
- "type": "tuple"
771
- }
772
- ],
773
- "internalType": "struct IPerpManager.Position",
1297
+ "internalType": "bool",
774
1298
  "name": "",
775
- "type": "tuple"
1299
+ "type": "bool"
776
1300
  }
777
1301
  ],
778
1302
  "stateMutability": "view",
@@ -781,22 +1305,17 @@ var PERP_MANAGER_ABI = [
781
1305
  {
782
1306
  "inputs": [
783
1307
  {
784
- "internalType": "PoolId",
785
- "name": "perpId",
786
- "type": "bytes32"
787
- },
788
- {
789
- "internalType": "uint32",
790
- "name": "secondsAgo",
791
- "type": "uint32"
1308
+ "internalType": "contract ILockupPeriod",
1309
+ "name": "",
1310
+ "type": "address"
792
1311
  }
793
1312
  ],
794
- "name": "getTimeWeightedAvg",
1313
+ "name": "isLockupPeriodRegistered",
795
1314
  "outputs": [
796
1315
  {
797
- "internalType": "uint256",
1316
+ "internalType": "bool",
798
1317
  "name": "",
799
- "type": "uint256"
1318
+ "type": "bool"
800
1319
  }
801
1320
  ],
802
1321
  "stateMutability": "view",
@@ -805,63 +1324,65 @@ var PERP_MANAGER_ABI = [
805
1324
  {
806
1325
  "inputs": [
807
1326
  {
808
- "internalType": "PoolId",
809
- "name": "perpId",
810
- "type": "bytes32"
811
- },
1327
+ "internalType": "contract IMarginRatios",
1328
+ "name": "",
1329
+ "type": "address"
1330
+ }
1331
+ ],
1332
+ "name": "isMarginRatiosRegistered",
1333
+ "outputs": [
812
1334
  {
813
- "internalType": "uint32",
814
- "name": "cardinalityNext",
815
- "type": "uint32"
1335
+ "internalType": "bool",
1336
+ "name": "",
1337
+ "type": "bool"
816
1338
  }
817
1339
  ],
818
- "name": "increaseCardinalityNext",
819
- "outputs": [],
820
- "stateMutability": "nonpayable",
1340
+ "stateMutability": "view",
821
1341
  "type": "function"
822
1342
  },
823
1343
  {
824
1344
  "inputs": [
825
1345
  {
826
- "internalType": "PoolId",
827
- "name": "perpId",
828
- "type": "bytes32"
829
- },
830
- {
831
- "internalType": "uint128",
832
- "name": "posId",
833
- "type": "uint128"
1346
+ "internalType": "contract ISqrtPriceImpactLimit",
1347
+ "name": "",
1348
+ "type": "address"
834
1349
  }
835
1350
  ],
836
- "name": "livePositionDetails",
1351
+ "name": "isSqrtPriceImpactLimitRegistered",
837
1352
  "outputs": [
838
- {
839
- "internalType": "int256",
840
- "name": "pnl",
841
- "type": "int256"
842
- },
843
- {
844
- "internalType": "int256",
845
- "name": "fundingPayment",
846
- "type": "int256"
847
- },
848
- {
849
- "internalType": "int256",
850
- "name": "effectiveMargin",
851
- "type": "int256"
852
- },
853
1353
  {
854
1354
  "internalType": "bool",
855
- "name": "isLiquidatable",
1355
+ "name": "",
856
1356
  "type": "bool"
857
- },
1357
+ }
1358
+ ],
1359
+ "stateMutability": "view",
1360
+ "type": "function"
1361
+ },
1362
+ {
1363
+ "inputs": [],
1364
+ "name": "name",
1365
+ "outputs": [
1366
+ {
1367
+ "internalType": "string",
1368
+ "name": "",
1369
+ "type": "string"
1370
+ }
1371
+ ],
1372
+ "stateMutability": "pure",
1373
+ "type": "function"
1374
+ },
1375
+ {
1376
+ "inputs": [],
1377
+ "name": "nextPosId",
1378
+ "outputs": [
858
1379
  {
859
1380
  "internalType": "uint256",
860
- "name": "newPriceX96",
1381
+ "name": "",
861
1382
  "type": "uint256"
862
1383
  }
863
1384
  ],
864
- "stateMutability": "nonpayable",
1385
+ "stateMutability": "view",
865
1386
  "type": "function"
866
1387
  },
867
1388
  {
@@ -873,6 +1394,11 @@ var PERP_MANAGER_ABI = [
873
1394
  },
874
1395
  {
875
1396
  "components": [
1397
+ {
1398
+ "internalType": "address",
1399
+ "name": "holder",
1400
+ "type": "address"
1401
+ },
876
1402
  {
877
1403
  "internalType": "uint256",
878
1404
  "name": "margin",
@@ -909,12 +1435,12 @@ var PERP_MANAGER_ABI = [
909
1435
  "type": "tuple"
910
1436
  }
911
1437
  ],
912
- "name": "openMakerPosition",
1438
+ "name": "openMakerPos",
913
1439
  "outputs": [
914
1440
  {
915
- "internalType": "uint128",
916
- "name": "makerPosId",
917
- "type": "uint128"
1441
+ "internalType": "uint256",
1442
+ "name": "posId",
1443
+ "type": "uint256"
918
1444
  }
919
1445
  ],
920
1446
  "stateMutability": "nonpayable",
@@ -929,6 +1455,11 @@ var PERP_MANAGER_ABI = [
929
1455
  },
930
1456
  {
931
1457
  "components": [
1458
+ {
1459
+ "internalType": "address",
1460
+ "name": "holder",
1461
+ "type": "address"
1462
+ },
932
1463
  {
933
1464
  "internalType": "bool",
934
1465
  "name": "isLong",
@@ -955,264 +1486,233 @@ var PERP_MANAGER_ABI = [
955
1486
  "type": "tuple"
956
1487
  }
957
1488
  ],
958
- "name": "openTakerPosition",
1489
+ "name": "openTakerPos",
959
1490
  "outputs": [
960
1491
  {
961
- "internalType": "uint128",
962
- "name": "takerPosId",
963
- "type": "uint128"
1492
+ "internalType": "uint256",
1493
+ "name": "posId",
1494
+ "type": "uint256"
964
1495
  }
965
1496
  ],
966
1497
  "stateMutability": "nonpayable",
967
1498
  "type": "function"
968
1499
  },
1500
+ {
1501
+ "inputs": [],
1502
+ "name": "owner",
1503
+ "outputs": [
1504
+ {
1505
+ "internalType": "address",
1506
+ "name": "result",
1507
+ "type": "address"
1508
+ }
1509
+ ],
1510
+ "stateMutability": "view",
1511
+ "type": "function"
1512
+ },
969
1513
  {
970
1514
  "inputs": [
971
1515
  {
972
- "internalType": "PoolId",
973
- "name": "",
974
- "type": "bytes32"
1516
+ "internalType": "uint256",
1517
+ "name": "id",
1518
+ "type": "uint256"
975
1519
  }
976
1520
  ],
977
- "name": "perps",
1521
+ "name": "ownerOf",
978
1522
  "outputs": [
979
1523
  {
980
1524
  "internalType": "address",
981
- "name": "vault",
982
- "type": "address"
983
- },
984
- {
985
- "internalType": "address",
986
- "name": "beacon",
1525
+ "name": "result",
987
1526
  "type": "address"
988
- },
1527
+ }
1528
+ ],
1529
+ "stateMutability": "view",
1530
+ "type": "function"
1531
+ },
1532
+ {
1533
+ "inputs": [
989
1534
  {
990
1535
  "internalType": "address",
991
- "name": "creator",
1536
+ "name": "pendingOwner",
992
1537
  "type": "address"
993
- },
994
- {
995
- "internalType": "uint32",
996
- "name": "creationTimestamp",
997
- "type": "uint32"
998
- },
999
- {
1000
- "internalType": "uint32",
1001
- "name": "makerLockupPeriod",
1002
- "type": "uint32"
1003
- },
1538
+ }
1539
+ ],
1540
+ "name": "ownershipHandoverExpiresAt",
1541
+ "outputs": [
1004
1542
  {
1005
- "internalType": "uint32",
1006
- "name": "twapWindow",
1007
- "type": "uint32"
1008
- },
1543
+ "internalType": "uint256",
1544
+ "name": "result",
1545
+ "type": "uint256"
1546
+ }
1547
+ ],
1548
+ "stateMutability": "view",
1549
+ "type": "function"
1550
+ },
1551
+ {
1552
+ "inputs": [
1009
1553
  {
1010
- "internalType": "uint32",
1011
- "name": "lastTwPremiumsUpdate",
1012
- "type": "uint32"
1013
- },
1554
+ "internalType": "uint256",
1555
+ "name": "",
1556
+ "type": "uint256"
1557
+ }
1558
+ ],
1559
+ "name": "positions",
1560
+ "outputs": [
1014
1561
  {
1015
- "internalType": "uint24",
1016
- "name": "creatorFee",
1017
- "type": "uint24"
1562
+ "internalType": "PoolId",
1563
+ "name": "perpId",
1564
+ "type": "bytes32"
1018
1565
  },
1019
1566
  {
1020
- "internalType": "uint24",
1021
- "name": "insuranceFee",
1022
- "type": "uint24"
1567
+ "internalType": "uint256",
1568
+ "name": "margin",
1569
+ "type": "uint256"
1023
1570
  },
1024
1571
  {
1025
- "internalType": "uint24",
1026
- "name": "liquidationFee",
1027
- "type": "uint24"
1572
+ "internalType": "int256",
1573
+ "name": "entryPerpDelta",
1574
+ "type": "int256"
1028
1575
  },
1029
1576
  {
1030
- "internalType": "uint24",
1031
- "name": "liquidatorFeeSplit",
1032
- "type": "uint24"
1577
+ "internalType": "int256",
1578
+ "name": "entryUsdDelta",
1579
+ "type": "int256"
1033
1580
  },
1034
1581
  {
1035
- "internalType": "uint128",
1036
- "name": "nextPosId",
1037
- "type": "uint128"
1582
+ "internalType": "int256",
1583
+ "name": "entryCumlFundingX96",
1584
+ "type": "int256"
1038
1585
  },
1039
1586
  {
1040
1587
  "internalType": "uint256",
1041
- "name": "sqrtPriceLowerMultiX96",
1588
+ "name": "entryCumlBadDebtX96",
1042
1589
  "type": "uint256"
1043
1590
  },
1044
1591
  {
1045
1592
  "internalType": "uint256",
1046
- "name": "sqrtPriceUpperMultiX96",
1593
+ "name": "entryCumlUtilizationX96",
1047
1594
  "type": "uint256"
1048
1595
  },
1049
- {
1050
- "internalType": "uint24",
1051
- "name": "minOpeningMargin",
1052
- "type": "uint24"
1053
- },
1054
- {
1055
- "internalType": "uint24",
1056
- "name": "minMakerOpeningMarginRatio",
1057
- "type": "uint24"
1058
- },
1059
- {
1060
- "internalType": "uint24",
1061
- "name": "maxMakerOpeningMarginRatio",
1062
- "type": "uint24"
1063
- },
1064
- {
1065
- "internalType": "uint24",
1066
- "name": "makerLiquidationMarginRatio",
1067
- "type": "uint24"
1068
- },
1069
- {
1070
- "internalType": "uint24",
1071
- "name": "minTakerOpeningMarginRatio",
1072
- "type": "uint24"
1073
- },
1074
- {
1075
- "internalType": "uint24",
1076
- "name": "maxTakerOpeningMarginRatio",
1077
- "type": "uint24"
1078
- },
1079
- {
1080
- "internalType": "uint24",
1081
- "name": "takerLiquidationMarginRatio",
1082
- "type": "uint24"
1083
- },
1084
- {
1085
- "internalType": "int256",
1086
- "name": "twPremiumX96",
1087
- "type": "int256"
1088
- },
1089
- {
1090
- "internalType": "int256",
1091
- "name": "twPremiumDivBySqrtPriceX96",
1092
- "type": "int256"
1093
- },
1094
- {
1095
- "internalType": "int256",
1096
- "name": "premiumPerSecondX96",
1097
- "type": "int256"
1098
- },
1099
1596
  {
1100
1597
  "components": [
1101
- {
1102
- "internalType": "Currency",
1103
- "name": "currency0",
1104
- "type": "address"
1105
- },
1106
- {
1107
- "internalType": "Currency",
1108
- "name": "currency1",
1109
- "type": "address"
1110
- },
1111
1598
  {
1112
1599
  "internalType": "uint24",
1113
- "name": "fee",
1600
+ "name": "min",
1114
1601
  "type": "uint24"
1115
1602
  },
1116
1603
  {
1117
- "internalType": "int24",
1118
- "name": "tickSpacing",
1119
- "type": "int24"
1604
+ "internalType": "uint24",
1605
+ "name": "max",
1606
+ "type": "uint24"
1120
1607
  },
1121
1608
  {
1122
- "internalType": "contract IHooks",
1123
- "name": "hooks",
1124
- "type": "address"
1609
+ "internalType": "uint24",
1610
+ "name": "liq",
1611
+ "type": "uint24"
1125
1612
  }
1126
1613
  ],
1127
- "internalType": "struct PoolKey",
1128
- "name": "key",
1614
+ "internalType": "struct IMarginRatios.MarginRatios",
1615
+ "name": "marginRatios",
1129
1616
  "type": "tuple"
1130
1617
  },
1131
1618
  {
1132
1619
  "components": [
1133
1620
  {
1134
- "internalType": "uint128",
1135
- "name": "baseFeeX96",
1136
- "type": "uint128"
1137
- },
1138
- {
1139
- "internalType": "uint128",
1140
- "name": "startFeeX96",
1141
- "type": "uint128"
1142
- },
1143
- {
1144
- "internalType": "uint128",
1145
- "name": "targetFeeX96",
1146
- "type": "uint128"
1621
+ "internalType": "uint32",
1622
+ "name": "unlockTimestamp",
1623
+ "type": "uint32"
1147
1624
  },
1148
1625
  {
1149
- "internalType": "uint128",
1150
- "name": "decay",
1151
- "type": "uint128"
1626
+ "internalType": "int24",
1627
+ "name": "tickLower",
1628
+ "type": "int24"
1152
1629
  },
1153
1630
  {
1154
- "internalType": "uint128",
1155
- "name": "volatilityScalerX96",
1156
- "type": "uint128"
1631
+ "internalType": "int24",
1632
+ "name": "tickUpper",
1633
+ "type": "int24"
1157
1634
  },
1158
1635
  {
1159
1636
  "internalType": "uint128",
1160
- "name": "maxFeeMultiplierX96",
1637
+ "name": "liquidity",
1161
1638
  "type": "uint128"
1162
- }
1163
- ],
1164
- "internalType": "struct TradingFee.Config",
1165
- "name": "tradingFeeConfig",
1166
- "type": "tuple"
1167
- },
1168
- {
1169
- "components": [
1170
- {
1171
- "internalType": "uint32",
1172
- "name": "index",
1173
- "type": "uint32"
1174
1639
  },
1175
1640
  {
1176
- "internalType": "uint32",
1177
- "name": "cardinality",
1178
- "type": "uint32"
1641
+ "internalType": "int256",
1642
+ "name": "entryCumlFundingBelowX96",
1643
+ "type": "int256"
1179
1644
  },
1180
1645
  {
1181
- "internalType": "uint32",
1182
- "name": "cardinalityNext",
1183
- "type": "uint32"
1646
+ "internalType": "int256",
1647
+ "name": "entryCumlFundingWithinX96",
1648
+ "type": "int256"
1184
1649
  },
1185
1650
  {
1186
- "components": [
1187
- {
1188
- "internalType": "uint32",
1189
- "name": "blockTimestamp",
1190
- "type": "uint32"
1191
- },
1192
- {
1193
- "internalType": "uint216",
1194
- "name": "cumulativeValue",
1195
- "type": "uint216"
1196
- },
1197
- {
1198
- "internalType": "bool",
1199
- "name": "initialized",
1200
- "type": "bool"
1201
- }
1202
- ],
1203
- "internalType": "struct TimeWeightedAvg.Observation[65535]",
1204
- "name": "observations",
1205
- "type": "tuple[65535]"
1651
+ "internalType": "int256",
1652
+ "name": "entryCumlFundingDivSqrtPWithinX96",
1653
+ "type": "int256"
1206
1654
  }
1207
1655
  ],
1208
- "internalType": "struct TimeWeightedAvg.State",
1209
- "name": "twapState",
1656
+ "internalType": "struct IPerpManager.MakerDetails",
1657
+ "name": "makerDetails",
1210
1658
  "type": "tuple"
1211
1659
  }
1212
1660
  ],
1213
1661
  "stateMutability": "view",
1214
1662
  "type": "function"
1215
1663
  },
1664
+ {
1665
+ "inputs": [],
1666
+ "name": "protocolFee",
1667
+ "outputs": [
1668
+ {
1669
+ "internalType": "uint24",
1670
+ "name": "",
1671
+ "type": "uint24"
1672
+ }
1673
+ ],
1674
+ "stateMutability": "view",
1675
+ "type": "function"
1676
+ },
1677
+ {
1678
+ "inputs": [
1679
+ {
1680
+ "internalType": "uint256",
1681
+ "name": "posId",
1682
+ "type": "uint256"
1683
+ }
1684
+ ],
1685
+ "name": "quoteClosePosition",
1686
+ "outputs": [
1687
+ {
1688
+ "internalType": "bool",
1689
+ "name": "success",
1690
+ "type": "bool"
1691
+ },
1692
+ {
1693
+ "internalType": "int256",
1694
+ "name": "pnl",
1695
+ "type": "int256"
1696
+ },
1697
+ {
1698
+ "internalType": "int256",
1699
+ "name": "funding",
1700
+ "type": "int256"
1701
+ },
1702
+ {
1703
+ "internalType": "uint256",
1704
+ "name": "netMargin",
1705
+ "type": "uint256"
1706
+ },
1707
+ {
1708
+ "internalType": "bool",
1709
+ "name": "wasLiquidated",
1710
+ "type": "bool"
1711
+ }
1712
+ ],
1713
+ "stateMutability": "nonpayable",
1714
+ "type": "function"
1715
+ },
1216
1716
  {
1217
1717
  "inputs": [
1218
1718
  {
@@ -1222,6 +1722,11 @@ var PERP_MANAGER_ABI = [
1222
1722
  },
1223
1723
  {
1224
1724
  "components": [
1725
+ {
1726
+ "internalType": "address",
1727
+ "name": "holder",
1728
+ "type": "address"
1729
+ },
1225
1730
  {
1226
1731
  "internalType": "uint256",
1227
1732
  "name": "margin",
@@ -1258,7 +1763,7 @@ var PERP_MANAGER_ABI = [
1258
1763
  "type": "tuple"
1259
1764
  }
1260
1765
  ],
1261
- "name": "quoteMakerPosition",
1766
+ "name": "quoteOpenMakerPosition",
1262
1767
  "outputs": [
1263
1768
  {
1264
1769
  "internalType": "bool",
@@ -1274,21 +1779,6 @@ var PERP_MANAGER_ABI = [
1274
1779
  "internalType": "int256",
1275
1780
  "name": "usdDelta",
1276
1781
  "type": "int256"
1277
- },
1278
- {
1279
- "internalType": "uint256",
1280
- "name": "creatorFeeAmt",
1281
- "type": "uint256"
1282
- },
1283
- {
1284
- "internalType": "uint256",
1285
- "name": "insuranceFeeAmt",
1286
- "type": "uint256"
1287
- },
1288
- {
1289
- "internalType": "uint256",
1290
- "name": "lpFeeAmt",
1291
- "type": "uint256"
1292
1782
  }
1293
1783
  ],
1294
1784
  "stateMutability": "nonpayable",
@@ -1303,6 +1793,11 @@ var PERP_MANAGER_ABI = [
1303
1793
  },
1304
1794
  {
1305
1795
  "components": [
1796
+ {
1797
+ "internalType": "address",
1798
+ "name": "holder",
1799
+ "type": "address"
1800
+ },
1306
1801
  {
1307
1802
  "internalType": "bool",
1308
1803
  "name": "isLong",
@@ -1329,7 +1824,7 @@ var PERP_MANAGER_ABI = [
1329
1824
  "type": "tuple"
1330
1825
  }
1331
1826
  ],
1332
- "name": "quoteTakerPosition",
1827
+ "name": "quoteOpenTakerPosition",
1333
1828
  "outputs": [
1334
1829
  {
1335
1830
  "internalType": "bool",
@@ -1345,21 +1840,6 @@ var PERP_MANAGER_ABI = [
1345
1840
  "internalType": "int256",
1346
1841
  "name": "usdDelta",
1347
1842
  "type": "int256"
1348
- },
1349
- {
1350
- "internalType": "uint256",
1351
- "name": "creatorFeeAmt",
1352
- "type": "uint256"
1353
- },
1354
- {
1355
- "internalType": "uint256",
1356
- "name": "insuranceFeeAmt",
1357
- "type": "uint256"
1358
- },
1359
- {
1360
- "internalType": "uint256",
1361
- "name": "lpFeeAmt",
1362
- "type": "uint256"
1363
1843
  }
1364
1844
  ],
1365
1845
  "stateMutability": "nonpayable",
@@ -1368,268 +1848,314 @@ var PERP_MANAGER_ABI = [
1368
1848
  {
1369
1849
  "inputs": [
1370
1850
  {
1371
- "internalType": "PoolId",
1372
- "name": "perpId",
1373
- "type": "bytes32"
1851
+ "internalType": "contract IFees",
1852
+ "name": "feesModule",
1853
+ "type": "address"
1374
1854
  }
1375
1855
  ],
1376
- "name": "sqrtPriceX96",
1377
- "outputs": [
1856
+ "name": "registerFeesModule",
1857
+ "outputs": [],
1858
+ "stateMutability": "nonpayable",
1859
+ "type": "function"
1860
+ },
1861
+ {
1862
+ "inputs": [
1378
1863
  {
1379
- "internalType": "uint160",
1380
- "name": "sqrtPrice",
1381
- "type": "uint160"
1864
+ "internalType": "contract ILockupPeriod",
1865
+ "name": "lockupPeriodModule",
1866
+ "type": "address"
1382
1867
  }
1383
1868
  ],
1384
- "stateMutability": "view",
1869
+ "name": "registerLockupPeriodModule",
1870
+ "outputs": [],
1871
+ "stateMutability": "nonpayable",
1385
1872
  "type": "function"
1386
1873
  },
1387
1874
  {
1388
1875
  "inputs": [
1389
1876
  {
1390
- "internalType": "PoolId",
1391
- "name": "perpId",
1392
- "type": "bytes32"
1877
+ "internalType": "contract IMarginRatios",
1878
+ "name": "marginRatiosModule",
1879
+ "type": "address"
1393
1880
  }
1394
1881
  ],
1395
- "name": "tickSpacing",
1396
- "outputs": [
1882
+ "name": "registerMarginRatiosModule",
1883
+ "outputs": [],
1884
+ "stateMutability": "nonpayable",
1885
+ "type": "function"
1886
+ },
1887
+ {
1888
+ "inputs": [
1397
1889
  {
1398
- "internalType": "int24",
1399
- "name": "",
1400
- "type": "int24"
1890
+ "internalType": "contract ISqrtPriceImpactLimit",
1891
+ "name": "sqrtPriceImpactLimitModule",
1892
+ "type": "address"
1401
1893
  }
1402
1894
  ],
1403
- "stateMutability": "view",
1895
+ "name": "registerSqrtPriceImpactLimitModule",
1896
+ "outputs": [],
1897
+ "stateMutability": "nonpayable",
1898
+ "type": "function"
1899
+ },
1900
+ {
1901
+ "inputs": [],
1902
+ "name": "renounceOwnership",
1903
+ "outputs": [],
1904
+ "stateMutability": "payable",
1905
+ "type": "function"
1906
+ },
1907
+ {
1908
+ "inputs": [],
1909
+ "name": "requestOwnershipHandover",
1910
+ "outputs": [],
1911
+ "stateMutability": "payable",
1404
1912
  "type": "function"
1405
1913
  },
1406
1914
  {
1407
1915
  "inputs": [
1408
1916
  {
1409
- "internalType": "PoolId",
1410
- "name": "perpId",
1411
- "type": "bytes32"
1917
+ "internalType": "address",
1918
+ "name": "from",
1919
+ "type": "address"
1920
+ },
1921
+ {
1922
+ "internalType": "address",
1923
+ "name": "to",
1924
+ "type": "address"
1925
+ },
1926
+ {
1927
+ "internalType": "uint256",
1928
+ "name": "id",
1929
+ "type": "uint256"
1412
1930
  }
1413
1931
  ],
1414
- "name": "tradingBounds",
1415
- "outputs": [
1932
+ "name": "safeTransferFrom",
1933
+ "outputs": [],
1934
+ "stateMutability": "payable",
1935
+ "type": "function"
1936
+ },
1937
+ {
1938
+ "inputs": [
1416
1939
  {
1417
- "internalType": "uint24",
1418
- "name": "minOpeningMargin",
1419
- "type": "uint24"
1940
+ "internalType": "address",
1941
+ "name": "from",
1942
+ "type": "address"
1420
1943
  },
1421
1944
  {
1422
- "internalType": "uint24",
1423
- "name": "minMakerMarginRatio",
1424
- "type": "uint24"
1945
+ "internalType": "address",
1946
+ "name": "to",
1947
+ "type": "address"
1425
1948
  },
1426
1949
  {
1427
- "internalType": "uint24",
1428
- "name": "maxMakerMarginRatio",
1429
- "type": "uint24"
1950
+ "internalType": "uint256",
1951
+ "name": "id",
1952
+ "type": "uint256"
1430
1953
  },
1431
1954
  {
1432
- "internalType": "uint24",
1433
- "name": "makerLiquidationMarginRatio",
1434
- "type": "uint24"
1435
- },
1955
+ "internalType": "bytes",
1956
+ "name": "data",
1957
+ "type": "bytes"
1958
+ }
1959
+ ],
1960
+ "name": "safeTransferFrom",
1961
+ "outputs": [],
1962
+ "stateMutability": "payable",
1963
+ "type": "function"
1964
+ },
1965
+ {
1966
+ "inputs": [
1436
1967
  {
1437
- "internalType": "uint24",
1438
- "name": "minTakerMarginRatio",
1439
- "type": "uint24"
1968
+ "internalType": "address",
1969
+ "name": "operator",
1970
+ "type": "address"
1440
1971
  },
1441
1972
  {
1442
- "internalType": "uint24",
1443
- "name": "maxTakerMarginRatio",
1444
- "type": "uint24"
1445
- },
1973
+ "internalType": "bool",
1974
+ "name": "isApproved",
1975
+ "type": "bool"
1976
+ }
1977
+ ],
1978
+ "name": "setApprovalForAll",
1979
+ "outputs": [],
1980
+ "stateMutability": "nonpayable",
1981
+ "type": "function"
1982
+ },
1983
+ {
1984
+ "inputs": [
1446
1985
  {
1447
1986
  "internalType": "uint24",
1448
- "name": "takerLiquidationMarginRatio",
1987
+ "name": "newProtocolFee",
1449
1988
  "type": "uint24"
1450
1989
  }
1451
1990
  ],
1452
- "stateMutability": "view",
1991
+ "name": "setProtocolFee",
1992
+ "outputs": [],
1993
+ "stateMutability": "nonpayable",
1453
1994
  "type": "function"
1454
1995
  },
1455
1996
  {
1456
1997
  "inputs": [
1457
1998
  {
1458
- "internalType": "bytes",
1459
- "name": "data",
1460
- "type": "bytes"
1999
+ "internalType": "bytes4",
2000
+ "name": "interfaceId",
2001
+ "type": "bytes4"
1461
2002
  }
1462
2003
  ],
1463
- "name": "unlockCallback",
2004
+ "name": "supportsInterface",
1464
2005
  "outputs": [
1465
2006
  {
1466
- "internalType": "bytes",
1467
- "name": "encodedDelta",
1468
- "type": "bytes"
2007
+ "internalType": "bool",
2008
+ "name": "result",
2009
+ "type": "bool"
1469
2010
  }
1470
2011
  ],
1471
- "stateMutability": "nonpayable",
2012
+ "stateMutability": "view",
2013
+ "type": "function"
2014
+ },
2015
+ {
2016
+ "inputs": [],
2017
+ "name": "symbol",
2018
+ "outputs": [
2019
+ {
2020
+ "internalType": "string",
2021
+ "name": "",
2022
+ "type": "string"
2023
+ }
2024
+ ],
2025
+ "stateMutability": "pure",
2026
+ "type": "function"
2027
+ },
2028
+ {
2029
+ "inputs": [
2030
+ {
2031
+ "internalType": "PoolId",
2032
+ "name": "perpId",
2033
+ "type": "bytes32"
2034
+ }
2035
+ ],
2036
+ "name": "takerOpenInterest",
2037
+ "outputs": [
2038
+ {
2039
+ "internalType": "uint128",
2040
+ "name": "longOI",
2041
+ "type": "uint128"
2042
+ },
2043
+ {
2044
+ "internalType": "uint128",
2045
+ "name": "shortOI",
2046
+ "type": "uint128"
2047
+ }
2048
+ ],
2049
+ "stateMutability": "view",
2050
+ "type": "function"
2051
+ },
2052
+ {
2053
+ "inputs": [
2054
+ {
2055
+ "internalType": "PoolId",
2056
+ "name": "perpId",
2057
+ "type": "bytes32"
2058
+ },
2059
+ {
2060
+ "internalType": "uint32",
2061
+ "name": "lookbackWindow",
2062
+ "type": "uint32"
2063
+ }
2064
+ ],
2065
+ "name": "timeWeightedAvgSqrtPriceX96",
2066
+ "outputs": [
2067
+ {
2068
+ "internalType": "uint256",
2069
+ "name": "twAvg",
2070
+ "type": "uint256"
2071
+ }
2072
+ ],
2073
+ "stateMutability": "view",
2074
+ "type": "function"
2075
+ },
2076
+ {
2077
+ "inputs": [
2078
+ {
2079
+ "internalType": "uint256",
2080
+ "name": "posId",
2081
+ "type": "uint256"
2082
+ }
2083
+ ],
2084
+ "name": "tokenURI",
2085
+ "outputs": [
2086
+ {
2087
+ "internalType": "string",
2088
+ "name": "",
2089
+ "type": "string"
2090
+ }
2091
+ ],
2092
+ "stateMutability": "pure",
2093
+ "type": "function"
2094
+ },
2095
+ {
2096
+ "inputs": [
2097
+ {
2098
+ "internalType": "address",
2099
+ "name": "from",
2100
+ "type": "address"
2101
+ },
2102
+ {
2103
+ "internalType": "address",
2104
+ "name": "to",
2105
+ "type": "address"
2106
+ },
2107
+ {
2108
+ "internalType": "uint256",
2109
+ "name": "id",
2110
+ "type": "uint256"
2111
+ }
2112
+ ],
2113
+ "name": "transferFrom",
2114
+ "outputs": [],
2115
+ "stateMutability": "payable",
2116
+ "type": "function"
2117
+ },
2118
+ {
2119
+ "inputs": [
2120
+ {
2121
+ "internalType": "address",
2122
+ "name": "newOwner",
2123
+ "type": "address"
2124
+ }
2125
+ ],
2126
+ "name": "transferOwnership",
2127
+ "outputs": [],
2128
+ "stateMutability": "payable",
2129
+ "type": "function"
2130
+ },
2131
+ {
2132
+ "inputs": [
2133
+ {
2134
+ "internalType": "bytes",
2135
+ "name": "data",
2136
+ "type": "bytes"
2137
+ }
2138
+ ],
2139
+ "name": "unlockCallback",
2140
+ "outputs": [
2141
+ {
2142
+ "internalType": "bytes",
2143
+ "name": "encodedDelta",
2144
+ "type": "bytes"
2145
+ }
2146
+ ],
2147
+ "stateMutability": "nonpayable",
1472
2148
  "type": "function"
1473
2149
  }
1474
- ];
1475
-
1476
- // src/utils/liquidity.ts
1477
- async function estimateLiquidity(context, tickLower, tickUpper, usdScaled) {
1478
- return await context.walletClient.readContract({
1479
- address: context.deployments().perpManager,
1480
- abi: PERP_MANAGER_ABI,
1481
- functionName: "estimateLiquidityForAmount1",
1482
- args: [tickLower, tickUpper, usdScaled]
1483
- });
1484
- }
1485
-
1486
- // src/utils/errors.ts
1487
- var import_viem2 = require("viem");
1488
- var PerpCityError = class extends Error {
1489
- constructor(message, cause) {
1490
- super(message);
1491
- this.cause = cause;
1492
- this.name = "PerpCityError";
1493
- }
1494
- };
1495
- var ContractError = class extends PerpCityError {
1496
- constructor(message, errorName, args, cause) {
1497
- super(message, cause);
1498
- this.errorName = errorName;
1499
- this.args = args;
1500
- this.name = "ContractError";
1501
- }
1502
- };
1503
- var TransactionRejectedError = class extends PerpCityError {
1504
- constructor(message = "Transaction rejected by user", cause) {
1505
- super(message, cause);
1506
- this.name = "TransactionRejectedError";
1507
- }
1508
- };
1509
- var InsufficientFundsError = class extends PerpCityError {
1510
- constructor(message = "Insufficient funds for transaction", cause) {
1511
- super(message, cause);
1512
- this.name = "InsufficientFundsError";
1513
- }
1514
- };
1515
- var GraphQLError = class extends PerpCityError {
1516
- constructor(message, cause) {
1517
- super(message, cause);
1518
- this.name = "GraphQLError";
1519
- }
1520
- };
1521
- var RPCError = class extends PerpCityError {
1522
- constructor(message, cause) {
1523
- super(message, cause);
1524
- this.name = "RPCError";
1525
- }
1526
- };
1527
- var ValidationError = class extends PerpCityError {
1528
- constructor(message, cause) {
1529
- super(message, cause);
1530
- this.name = "ValidationError";
1531
- }
1532
- };
1533
- function parseContractError(error) {
1534
- if (error instanceof PerpCityError) {
1535
- return error;
1536
- }
1537
- if (error instanceof import_viem2.BaseError) {
1538
- const revertError = error.walk((err) => err instanceof import_viem2.ContractFunctionRevertedError);
1539
- if (revertError instanceof import_viem2.ContractFunctionRevertedError) {
1540
- const errorName = revertError.data?.errorName ?? "Unknown";
1541
- const args = revertError.data?.args ?? [];
1542
- const message = formatContractError(errorName, args);
1543
- return new ContractError(message, errorName, args, error);
1544
- }
1545
- if (error.message?.includes("User rejected") || error.code === 4001) {
1546
- return new TransactionRejectedError(error.message, error);
1547
- }
1548
- if (error.message?.includes("insufficient funds")) {
1549
- return new InsufficientFundsError(error.message, error);
1550
- }
1551
- return new PerpCityError(error.shortMessage || error.message, error);
1552
- }
1553
- if (error instanceof Error) {
1554
- return new PerpCityError(error.message, error);
1555
- }
1556
- return new PerpCityError(String(error));
1557
- }
1558
- function formatContractError(errorName, args) {
1559
- switch (errorName) {
1560
- case "InvalidBeaconAddress":
1561
- return `Invalid beacon address: ${args[0]}`;
1562
- case "InvalidTradingFeeSplits":
1563
- return `Invalid trading fee splits. Insurance split: ${args[0]}, Creator split: ${args[1]}`;
1564
- case "InvalidMaxOpeningLev":
1565
- return `Invalid maximum opening leverage: ${args[0]}`;
1566
- case "InvalidLiquidationLev":
1567
- return `Invalid liquidation leverage: ${args[0]}. Must be less than max opening leverage: ${args[1]}`;
1568
- case "InvalidLiquidationFee":
1569
- return `Invalid liquidation fee: ${args[0]}`;
1570
- case "InvalidLiquidatorFeeSplit":
1571
- return `Invalid liquidator fee split: ${args[0]}`;
1572
- case "InvalidClose":
1573
- return `Cannot close position. Caller: ${args[0]}, Holder: ${args[1]}, Is Liquidated: ${args[2]}`;
1574
- case "InvalidCaller":
1575
- return `Invalid caller. Expected: ${args[1]}, Got: ${args[0]}`;
1576
- case "InvalidLiquidity":
1577
- return `Invalid liquidity amount: ${args[0]}`;
1578
- case "InvalidMargin":
1579
- return `Invalid margin amount: ${args[0]}`;
1580
- case "InvalidLevX96":
1581
- return `Invalid leverage: ${args[0]}. Maximum allowed: ${args[1]}`;
1582
- case "MakerPositionLocked":
1583
- return `Maker position is locked until ${new Date(Number(args[1]) * 1e3).toISOString()}. Current time: ${new Date(Number(args[0]) * 1e3).toISOString()}`;
1584
- case "MaximumAmountExceeded":
1585
- return `Maximum amount exceeded. Maximum: ${args[0]}, Requested: ${args[1]}`;
1586
- case "MinimumAmountInsufficient":
1587
- return `Minimum amount not met. Required: ${args[0]}, Received: ${args[1]}`;
1588
- case "PriceImpactTooHigh":
1589
- return `Price impact too high. Current price: ${args[0]}, Min acceptable: ${args[1]}, Max acceptable: ${args[2]}`;
1590
- case "SwapReverted":
1591
- return "Swap failed. This may be due to insufficient liquidity or slippage tolerance.";
1592
- case "ZeroSizePosition":
1593
- return `Cannot create zero-size position. Perp delta: ${args[0]}, USD delta: ${args[1]}`;
1594
- case "InvalidFundingInterval":
1595
- return `Invalid funding interval: ${args[0]}`;
1596
- case "InvalidPriceImpactBand":
1597
- return `Invalid price impact band: ${args[0]}`;
1598
- case "InvalidMarketDeathThreshold":
1599
- return `Invalid market death threshold: ${args[0]}`;
1600
- case "InvalidTickRange":
1601
- return `Invalid tick range. Lower: ${args[0]}, Upper: ${args[1]}`;
1602
- case "MarketNotKillable":
1603
- return `Market health (${args[0]}) is above death threshold (${args[1]}). Market cannot be killed yet.`;
1604
- case "InvalidStartingSqrtPriceX96":
1605
- return `Invalid starting sqrt price: ${args[0]}`;
1606
- default:
1607
- return `Contract error: ${errorName}${args.length > 0 ? ` (${args.join(", ")})` : ""}`;
1608
- }
1609
- }
1610
- async function withErrorHandling(fn, context) {
1611
- try {
1612
- return await fn();
1613
- } catch (error) {
1614
- const parsedError = parseContractError(error);
1615
- parsedError.message = `${context}: ${parsedError.message}`;
1616
- throw parsedError;
1617
- }
1618
- }
2150
+ ];
1619
2151
 
1620
2152
  // src/context.ts
1621
2153
  var import_viem4 = require("viem");
1622
2154
  var PerpCityContext = class {
1623
2155
  constructor(config) {
2156
+ this.configCache = /* @__PURE__ */ new Map();
1624
2157
  this.walletClient = config.walletClient.extend(import_viem3.publicActions);
1625
2158
  this._deployments = config.deployments;
1626
- const headers = {};
1627
- if (config.goldskyBearerToken) {
1628
- headers.authorization = `Bearer ${config.goldskyBearerToken}`;
1629
- }
1630
- this.goldskyClient = new import_graphql_request.GraphQLClient(config.goldskyEndpoint, {
1631
- headers
1632
- });
1633
2159
  }
1634
2160
  deployments() {
1635
2161
  return this._deployments;
@@ -1637,154 +2163,68 @@ var PerpCityContext = class {
1637
2163
  // Optimized batch data fetching methods
1638
2164
  async fetchPerpData(perpId) {
1639
2165
  return withErrorHandling(async () => {
1640
- const perpQuery = (0, import_graphql.parse)(`
1641
- query ($perpId: Bytes!) {
1642
- perp(id: $perpId) {
1643
- beacon { id }
1644
- }
1645
- perpSnapshots(
1646
- orderBy: timestamp
1647
- orderDirection: asc
1648
- where: { perp: $perpId }
1649
- ) {
1650
- timestamp
1651
- markPrice
1652
- takerLongNotional
1653
- takerShortNotional
1654
- fundingRate
1655
- }
1656
- }
1657
- `);
1658
- const beaconQuery = (0, import_graphql.parse)(`
1659
- query ($beaconAddr: Bytes!) {
1660
- beaconSnapshots(
1661
- orderBy: timestamp
1662
- orderDirection: asc
1663
- where: { beacon: $beaconAddr }
1664
- ) {
1665
- timestamp
1666
- indexPrice
1667
- }
1668
- }
1669
- `);
1670
- let perpResponse;
1671
- try {
1672
- perpResponse = await this.goldskyClient.request(perpQuery, { perpId });
1673
- } catch (error) {
1674
- throw new GraphQLError(`Failed to fetch perp data for ${perpId}: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : void 0);
1675
- }
1676
- if (!perpResponse.perp || !perpResponse.perp.beacon) {
1677
- throw new GraphQLError(`Perp ${perpId} not found or has no beacon`);
1678
- }
1679
- let beaconResponse;
1680
- let contractData;
1681
- try {
1682
- [beaconResponse, contractData] = await Promise.all([
1683
- this.goldskyClient.request(beaconQuery, { beaconAddr: perpResponse.perp.beacon.id }),
1684
- this.fetchPerpContractData(perpId)
1685
- ]);
1686
- } catch (error) {
1687
- if (error instanceof GraphQLError || error instanceof RPCError) {
1688
- throw error;
1689
- }
1690
- throw new GraphQLError(`Failed to fetch beacon or contract data: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error : void 0);
1691
- }
1692
- if (perpResponse.perpSnapshots.length === 0) {
1693
- throw new GraphQLError(`No perpSnapshots found for perp ${perpId}. This perp may be newly created with no trading activity yet.`);
1694
- }
1695
- if (beaconResponse.beaconSnapshots.length === 0) {
1696
- throw new GraphQLError(`No beaconSnapshots found for perp ${perpId} beacon ${perpResponse.perp.beacon.id}. The beacon may not have any price updates yet.`);
1697
- }
1698
- const markTimeSeries = perpResponse.perpSnapshots.map((snapshot) => ({
1699
- timestamp: Number(snapshot.timestamp),
1700
- value: Number((0, import_viem3.formatUnits)(BigInt(snapshot.markPrice), 6))
1701
- }));
1702
- const indexTimeSeries = beaconResponse.beaconSnapshots.map((snapshot) => ({
1703
- timestamp: Number(snapshot.timestamp),
1704
- value: Number((0, import_viem3.formatUnits)(BigInt(snapshot.indexPrice), 6))
1705
- }));
1706
- const openInterestTimeSeries = perpResponse.perpSnapshots.map((snapshot) => ({
1707
- timestamp: Number(snapshot.timestamp),
1708
- value: {
1709
- takerLongNotional: Number((0, import_viem3.formatUnits)(BigInt(snapshot.takerLongNotional), 6)),
1710
- takerShortNotional: Number((0, import_viem3.formatUnits)(BigInt(snapshot.takerShortNotional), 6))
1711
- }
1712
- }));
1713
- const fundingRateTimeSeries = perpResponse.perpSnapshots.map((snapshot) => ({
1714
- timestamp: Number(snapshot.timestamp),
1715
- value: Number((0, import_viem3.formatUnits)(BigInt(snapshot.fundingRate), 6))
1716
- }));
1717
- const latestSnapshot = perpResponse.perpSnapshots[perpResponse.perpSnapshots.length - 1];
1718
- const latestBeaconSnapshot = beaconResponse.beaconSnapshots[beaconResponse.beaconSnapshots.length - 1];
2166
+ const contractData = await this.fetchPerpContractData(perpId);
2167
+ const config = await this.getPerpConfig(perpId);
1719
2168
  const perpData = {
1720
2169
  id: perpId,
1721
2170
  tickSpacing: contractData.tickSpacing,
1722
2171
  mark: sqrtPriceX96ToPrice(contractData.sqrtPriceX96),
1723
- index: Number((0, import_viem3.formatUnits)(BigInt(latestBeaconSnapshot.indexPrice), 6)),
1724
- beacon: perpResponse.perp.beacon.id,
1725
- lastIndexUpdate: Number(latestBeaconSnapshot.timestamp),
1726
- openInterest: {
1727
- takerLongNotional: Number((0, import_viem3.formatUnits)(BigInt(latestSnapshot.takerLongNotional), 6)),
1728
- takerShortNotional: Number((0, import_viem3.formatUnits)(BigInt(latestSnapshot.takerShortNotional), 6))
1729
- },
1730
- markTimeSeries,
1731
- indexTimeSeries,
1732
- fundingRate: Number((0, import_viem3.formatUnits)(BigInt(latestSnapshot.fundingRate), 6)),
2172
+ beacon: config.beacon,
1733
2173
  bounds: contractData.bounds,
1734
- fees: contractData.fees,
1735
- openInterestTimeSeries,
1736
- fundingRateTimeSeries,
1737
- totalOpenMakerPnl: 0,
1738
- // These will be calculated by functions
1739
- totalOpenTakerPnl: 0
1740
- // These will be calculated by functions
2174
+ fees: contractData.fees
1741
2175
  };
1742
2176
  return perpData;
1743
2177
  }, `fetchPerpData for perp ${perpId}`);
1744
2178
  }
1745
- async fetchPerpContractData(perpId) {
2179
+ /**
2180
+ * Fetches and caches the config for a perpId
2181
+ * The config includes module addresses (fees, marginRatios, etc.) and pool settings
2182
+ */
2183
+ async getPerpConfig(perpId) {
2184
+ const cached = this.configCache.get(perpId);
2185
+ if (cached) {
2186
+ return cached;
2187
+ }
2188
+ const cfg = await this.walletClient.readContract({
2189
+ address: this.deployments().perpManager,
2190
+ abi: PERP_MANAGER_ABI,
2191
+ functionName: "cfgs",
2192
+ args: [perpId]
2193
+ });
2194
+ this.configCache.set(perpId, cfg);
2195
+ return cfg;
2196
+ }
2197
+ async fetchPerpContractData(perpId, markPrice) {
1746
2198
  return withErrorHandling(async () => {
1747
- const [tickSpacing, sqrtPriceX96, boundsRaw, feesRaw] = await Promise.all([
1748
- this.walletClient.readContract({
1749
- address: this.deployments().perpManager,
1750
- abi: PERP_MANAGER_ABI,
1751
- functionName: "tickSpacing",
1752
- args: [perpId]
1753
- }),
1754
- this.walletClient.readContract({
1755
- address: this.deployments().perpManager,
1756
- abi: PERP_MANAGER_ABI,
1757
- functionName: "sqrtPriceX96",
1758
- args: [perpId]
1759
- }),
1760
- this.walletClient.readContract({
1761
- address: this.deployments().perpManager,
1762
- abi: PERP_MANAGER_ABI,
1763
- functionName: "tradingBounds",
1764
- args: [perpId]
1765
- }),
1766
- this.walletClient.readContract({
2199
+ const cfg = await this.getPerpConfig(perpId);
2200
+ const tickSpacing = Number(cfg.key.tickSpacing);
2201
+ let sqrtPriceX96;
2202
+ if (markPrice) {
2203
+ const sqrtPrice = Math.sqrt(markPrice);
2204
+ sqrtPriceX96 = BigInt(Math.floor(sqrtPrice * 2 ** 96));
2205
+ } else {
2206
+ sqrtPriceX96 = await this.walletClient.readContract({
1767
2207
  address: this.deployments().perpManager,
1768
2208
  abi: PERP_MANAGER_ABI,
1769
- functionName: "fees",
1770
- args: [perpId]
1771
- })
1772
- ]);
1773
- const bounds = boundsRaw;
1774
- const fees = feesRaw;
2209
+ functionName: "timeWeightedAvgSqrtPriceX96",
2210
+ args: [perpId, 1]
2211
+ });
2212
+ }
1775
2213
  return {
1776
- tickSpacing: Number(tickSpacing),
2214
+ tickSpacing,
1777
2215
  sqrtPriceX96,
1778
2216
  bounds: {
1779
- minMargin: Number((0, import_viem3.formatUnits)(bounds[0], 6)),
1780
- minTakerLeverage: marginRatioToLeverage(Number((0, import_viem3.formatUnits)(bounds[4], 6))),
1781
- maxTakerLeverage: marginRatioToLeverage(Number((0, import_viem3.formatUnits)(bounds[5], 6)))
2217
+ minMargin: 10,
2218
+ // Placeholder - would need to call cfg.marginRatios contract
2219
+ minTakerLeverage: 1.1,
2220
+ maxTakerLeverage: 20
1782
2221
  },
1783
2222
  fees: {
1784
- creatorFee: Number((0, import_viem3.formatUnits)(fees[0], 6)),
1785
- insuranceFee: Number((0, import_viem3.formatUnits)(fees[1], 6)),
1786
- lpFee: Number((0, import_viem3.formatUnits)(fees[2], 6)),
1787
- liquidationFee: Number((0, import_viem3.formatUnits)(fees[3], 6))
2223
+ creatorFee: 1e-4,
2224
+ // Placeholder - would need to call cfg.fees contract
2225
+ insuranceFee: 1e-4,
2226
+ lpFee: 3e-4,
2227
+ liquidationFee: 0.01
1788
2228
  }
1789
2229
  };
1790
2230
  }, `fetchPerpContractData for perp ${perpId}`);
@@ -1795,283 +2235,73 @@ var PerpCityContext = class {
1795
2235
  async getPerpData(perpId) {
1796
2236
  return this.fetchPerpData(perpId);
1797
2237
  }
1798
- /**
1799
- * Fetch data for multiple perps efficiently with true batching
1800
- * This fetches all perps in just 2 Goldsky requests total (not 2N!)
1801
- */
1802
- async getMultiplePerpData(perpIds) {
1803
- if (perpIds.length === 0) {
1804
- return /* @__PURE__ */ new Map();
1805
- }
1806
- if (perpIds.length === 1) {
1807
- const data = await this.fetchPerpData(perpIds[0]);
1808
- return /* @__PURE__ */ new Map([[perpIds[0], data]]);
1809
- }
1810
- const batchPerpQuery = (0, import_graphql.parse)(`
1811
- query ($perpIds: [Bytes!]!) {
1812
- perps(where: { id_in: $perpIds }) {
1813
- id
1814
- beacon { id }
1815
- }
1816
- perpSnapshots(
1817
- orderBy: timestamp
1818
- orderDirection: asc
1819
- where: { perp_in: $perpIds }
1820
- ) {
1821
- perp { id }
1822
- timestamp
1823
- markPrice
1824
- takerLongNotional
1825
- takerShortNotional
1826
- fundingRate
1827
- }
1828
- }
1829
- `);
1830
- const perpResponse = await this.goldskyClient.request(batchPerpQuery, { perpIds });
1831
- const beaconIds = [...new Set(perpResponse.perps.map((p) => p.beacon.id))];
1832
- const batchBeaconQuery = (0, import_graphql.parse)(`
1833
- query ($beaconIds: [Bytes!]!) {
1834
- beaconSnapshots(
1835
- orderBy: timestamp
1836
- orderDirection: asc
1837
- where: { beacon_in: $beaconIds }
1838
- ) {
1839
- beacon { id }
1840
- timestamp
1841
- indexPrice
1842
- }
1843
- }
1844
- `);
1845
- const [beaconResponse, contractDataMap] = await Promise.all([
1846
- this.goldskyClient.request(batchBeaconQuery, { beaconIds }),
1847
- this.fetchMultiplePerpContractData(perpIds)
1848
- ]);
1849
- const snapshotsByPerp = /* @__PURE__ */ new Map();
1850
- perpResponse.perpSnapshots.forEach((snapshot) => {
1851
- const perpId = snapshot.perp.id;
1852
- if (!snapshotsByPerp.has(perpId)) {
1853
- snapshotsByPerp.set(perpId, []);
1854
- }
1855
- snapshotsByPerp.get(perpId).push(snapshot);
1856
- });
1857
- const snapshotsByBeacon = /* @__PURE__ */ new Map();
1858
- beaconResponse.beaconSnapshots.forEach((snapshot) => {
1859
- const beaconId = snapshot.beacon.id;
1860
- if (!snapshotsByBeacon.has(beaconId)) {
1861
- snapshotsByBeacon.set(beaconId, []);
1862
- }
1863
- snapshotsByBeacon.get(beaconId).push(snapshot);
2238
+ async fetchUserData(userAddress, positions) {
2239
+ const usdcBalance = await this.walletClient.readContract({
2240
+ address: this.deployments().usdc,
2241
+ abi: import_viem4.erc20Abi,
2242
+ functionName: "balanceOf",
2243
+ args: [userAddress]
1864
2244
  });
1865
- const perpLookup = new Map(
1866
- perpResponse.perps.map((p) => [
1867
- p.id,
1868
- p
1869
- ])
1870
- );
1871
- const resultMap = /* @__PURE__ */ new Map();
1872
- for (const perpId of perpIds) {
1873
- const perp = perpLookup.get(perpId);
1874
- if (!perp) {
1875
- throw new Error(`Perp ${perpId} not found`);
1876
- }
1877
- const beaconId = perp.beacon.id;
1878
- const snapshots = snapshotsByPerp.get(perpId) || [];
1879
- const beaconSnapshots = snapshotsByBeacon.get(beaconId) || [];
1880
- const contractData = contractDataMap.get(perpId);
1881
- if (!contractData) {
1882
- throw new Error(`Contract data for perp ${perpId} not found`);
1883
- }
1884
- if (snapshots.length === 0) {
1885
- throw new Error(`No snapshots found for perp ${perpId}`);
1886
- }
1887
- if (beaconSnapshots.length === 0) {
1888
- throw new Error(`No beacon snapshots found for perp ${perpId}`);
1889
- }
1890
- const markTimeSeries = snapshots.map((snapshot) => ({
1891
- timestamp: Number(snapshot.timestamp),
1892
- value: Number((0, import_viem3.formatUnits)(BigInt(snapshot.markPrice), 6))
1893
- }));
1894
- const indexTimeSeries = beaconSnapshots.map((snapshot) => ({
1895
- timestamp: Number(snapshot.timestamp),
1896
- value: Number((0, import_viem3.formatUnits)(BigInt(snapshot.indexPrice), 6))
1897
- }));
1898
- const openInterestTimeSeries = snapshots.map((snapshot) => ({
1899
- timestamp: Number(snapshot.timestamp),
1900
- value: {
1901
- takerLongNotional: Number((0, import_viem3.formatUnits)(BigInt(snapshot.takerLongNotional), 6)),
1902
- takerShortNotional: Number((0, import_viem3.formatUnits)(BigInt(snapshot.takerShortNotional), 6))
1903
- }
1904
- }));
1905
- const fundingRateTimeSeries = snapshots.map((snapshot) => ({
1906
- timestamp: Number(snapshot.timestamp),
1907
- value: Number((0, import_viem3.formatUnits)(BigInt(snapshot.fundingRate), 6))
1908
- }));
1909
- const latestSnapshot = snapshots[snapshots.length - 1];
1910
- const latestBeaconSnapshot = beaconSnapshots[beaconSnapshots.length - 1];
1911
- const perpData = {
1912
- id: perpId,
1913
- tickSpacing: contractData.tickSpacing,
1914
- mark: sqrtPriceX96ToPrice(contractData.sqrtPriceX96),
1915
- index: Number((0, import_viem3.formatUnits)(BigInt(latestBeaconSnapshot.indexPrice), 6)),
1916
- beacon: beaconId,
1917
- lastIndexUpdate: Number(latestBeaconSnapshot.timestamp),
1918
- openInterest: {
1919
- takerLongNotional: Number((0, import_viem3.formatUnits)(BigInt(latestSnapshot.takerLongNotional), 6)),
1920
- takerShortNotional: Number((0, import_viem3.formatUnits)(BigInt(latestSnapshot.takerShortNotional), 6))
1921
- },
1922
- markTimeSeries,
1923
- indexTimeSeries,
1924
- fundingRate: Number((0, import_viem3.formatUnits)(BigInt(latestSnapshot.fundingRate), 6)),
1925
- bounds: contractData.bounds,
1926
- fees: contractData.fees,
1927
- openInterestTimeSeries,
1928
- fundingRateTimeSeries,
1929
- totalOpenMakerPnl: 0,
1930
- totalOpenTakerPnl: 0
1931
- };
1932
- resultMap.set(perpId, perpData);
1933
- }
1934
- return resultMap;
1935
- }
1936
- async fetchMultiplePerpContractData(perpIds) {
1937
- const results = await Promise.all(
1938
- perpIds.map(async (perpId) => ({
1939
- perpId,
1940
- data: await this.fetchPerpContractData(perpId)
1941
- }))
1942
- );
1943
- return new Map(results.map(({ perpId, data }) => [perpId, data]));
1944
- }
1945
- async fetchUserData(userAddress) {
1946
- const [usdcBalance, openPositionsData, closedPositionsData] = await Promise.all([
1947
- this.walletClient.readContract({
1948
- address: this.deployments().usdc,
1949
- abi: import_viem4.erc20Abi,
1950
- functionName: "balanceOf",
1951
- args: [userAddress]
1952
- }),
1953
- this.fetchUserOpenPositions(userAddress),
1954
- this.fetchUserClosedPositions(userAddress)
1955
- ]);
1956
- const realizedPnl = closedPositionsData.reduce((acc, position) => acc + position.pnlAtClose, 0);
1957
- const unrealizedPnl = openPositionsData.reduce(
1958
- (acc, position) => acc + position.liveDetails.pnl - position.liveDetails.fundingPayment,
1959
- 0
1960
- );
1961
- return {
1962
- walletAddress: userAddress,
1963
- usdcBalance: Number((0, import_viem3.formatUnits)(usdcBalance, 6)),
1964
- openPositions: openPositionsData,
1965
- closedPositions: closedPositionsData,
1966
- realizedPnl,
1967
- unrealizedPnl
1968
- };
1969
- }
1970
- async fetchUserOpenPositions(userAddress) {
1971
- const query = (0, import_graphql.parse)(`
1972
- query ($holder: Bytes!) {
1973
- openPositions(
1974
- where: { holder: $holder }
1975
- ) {
1976
- perp { id }
1977
- inContractPosId
1978
- isLong
1979
- isMaker
1980
- }
1981
- }
1982
- `);
1983
- const response = await this.goldskyClient.request(query, { holder: userAddress });
1984
- const positionsWithDetails = await Promise.all(
1985
- response.openPositions.map(async (position) => {
1986
- const positionId = typeof position.inContractPosId === "bigint" ? position.inContractPosId : BigInt(position.inContractPosId);
1987
- const liveDetails = await this.fetchPositionLiveDetailsFromContract(
1988
- position.perp.id,
1989
- positionId
1990
- );
2245
+ const openPositionsData = await Promise.all(
2246
+ positions.map(async ({ perpId, positionId, isLong, isMaker }) => {
2247
+ const liveDetails = await this.fetchPositionLiveDetailsFromContract(perpId, positionId);
1991
2248
  return {
1992
- perpId: position.perp.id,
2249
+ perpId,
1993
2250
  positionId,
1994
- isLong: position.isLong,
1995
- isMaker: position.isMaker,
2251
+ isLong,
2252
+ isMaker,
1996
2253
  liveDetails
1997
2254
  };
1998
2255
  })
1999
2256
  );
2000
- return positionsWithDetails;
2001
- }
2002
- async fetchUserClosedPositions(userAddress) {
2003
- const query = (0, import_graphql.parse)(`
2004
- query ($holder: Bytes!) {
2005
- closedPositions(
2006
- where: { holder: $holder }
2007
- ) {
2008
- perp { id }
2009
- wasMaker
2010
- wasLong
2011
- pnlAtClose
2012
- }
2013
- }
2014
- `);
2015
- const response = await this.goldskyClient.request(query, { holder: userAddress });
2016
- return response.closedPositions.map((position) => ({
2017
- perpId: position.perp.id,
2018
- wasMaker: position.wasMaker,
2019
- wasLong: position.wasLong,
2020
- pnlAtClose: Number((0, import_viem3.formatUnits)(BigInt(position.pnlAtClose), 6))
2021
- }));
2257
+ return {
2258
+ walletAddress: userAddress,
2259
+ usdcBalance: Number((0, import_viem3.formatUnits)(usdcBalance, 6)),
2260
+ openPositions: openPositionsData
2261
+ };
2022
2262
  }
2023
2263
  async fetchPositionLiveDetailsFromContract(perpId, positionId) {
2024
2264
  return withErrorHandling(async () => {
2025
2265
  const result = await this.walletClient.readContract({
2026
2266
  address: this.deployments().perpManager,
2027
2267
  abi: PERP_MANAGER_ABI,
2028
- functionName: "livePositionDetails",
2029
- args: [perpId, positionId]
2268
+ functionName: "quoteClosePosition",
2269
+ args: [positionId]
2030
2270
  });
2271
+ const [success, pnl, funding, netMargin, wasLiquidated] = result;
2272
+ if (!success) {
2273
+ throw new Error(`Failed to quote position ${positionId} - position may be invalid or already closed`);
2274
+ }
2031
2275
  return {
2032
- pnl: Number((0, import_viem3.formatUnits)(result[0], 6)),
2033
- fundingPayment: Number((0, import_viem3.formatUnits)(result[1], 6)),
2034
- effectiveMargin: Number((0, import_viem3.formatUnits)(result[2], 6)),
2035
- isLiquidatable: result[3]
2276
+ pnl: Number((0, import_viem3.formatUnits)(pnl, 6)),
2277
+ fundingPayment: Number((0, import_viem3.formatUnits)(funding, 6)),
2278
+ effectiveMargin: Number((0, import_viem3.formatUnits)(netMargin, 6)),
2279
+ isLiquidatable: wasLiquidated
2036
2280
  };
2037
2281
  }, `fetchPositionLiveDetailsFromContract for position ${positionId}`);
2038
2282
  }
2039
2283
  /**
2040
- * Fetch comprehensive user data with all positions in a single batched request
2284
+ * Fetch comprehensive user data with live details for all positions
2285
+ * @param userAddress - The user's wallet address
2286
+ * @param positions - Array of position metadata (perpId, positionId, isLong, isMaker) tracked from transaction receipts
2041
2287
  */
2042
- async getUserData(userAddress) {
2043
- return this.fetchUserData(userAddress);
2288
+ async getUserData(userAddress, positions) {
2289
+ return this.fetchUserData(userAddress, positions);
2044
2290
  }
2045
2291
  /**
2046
2292
  * Fetch open position data with live details
2293
+ * @param perpId - The perpetual market ID
2294
+ * @param positionId - The position ID
2295
+ * @param isLong - Whether the position is long (true) or short (false)
2296
+ * @param isMaker - Whether the position is a maker (LP) position
2047
2297
  */
2048
- async getOpenPositionData(perpId, positionId) {
2049
- const query = (0, import_graphql.parse)(`
2050
- query ($perpId: Bytes!, $posId: BigInt!) {
2051
- openPositions(
2052
- where: { perp: $perpId, inContractPosId: $posId }
2053
- first: 1
2054
- ) {
2055
- isLong
2056
- isMaker
2057
- }
2058
- }
2059
- `);
2060
- const [positionResponse, liveDetails] = await Promise.all([
2061
- this.goldskyClient.request(query, { perpId, posId: positionId.toString() }),
2062
- this.fetchPositionLiveDetailsFromContract(perpId, positionId)
2063
- ]);
2064
- const position = positionResponse.openPositions[0];
2065
- if (!position) {
2066
- throw new Error(
2067
- `Position not found in GraphQL: perpId=${perpId}, positionId=${positionId}. The position may not exist or may have been closed.`
2068
- );
2069
- }
2298
+ async getOpenPositionData(perpId, positionId, isLong, isMaker) {
2299
+ const liveDetails = await this.fetchPositionLiveDetailsFromContract(perpId, positionId);
2070
2300
  return {
2071
2301
  perpId,
2072
2302
  positionId,
2073
- isLong: position.isLong,
2074
- isMaker: position.isMaker,
2303
+ isLong,
2304
+ isMaker,
2075
2305
  liveDetails
2076
2306
  };
2077
2307
  }
@@ -2333,6 +2563,26 @@ var BEACON_ABI = [
2333
2563
  }
2334
2564
  ];
2335
2565
 
2566
+ // src/functions/perp.ts
2567
+ function getPerpMark(perpData) {
2568
+ return perpData.mark;
2569
+ }
2570
+ function getPerpBeacon(perpData) {
2571
+ return perpData.beacon;
2572
+ }
2573
+ function getPerpBounds(perpData) {
2574
+ return perpData.bounds;
2575
+ }
2576
+ function getPerpFees(perpData) {
2577
+ return perpData.fees;
2578
+ }
2579
+ function getPerpTickSpacing(perpData) {
2580
+ return perpData.tickSpacing;
2581
+ }
2582
+
2583
+ // src/functions/perp-manager.ts
2584
+ var import_viem6 = require("viem");
2585
+
2336
2586
  // src/functions/open-position.ts
2337
2587
  var import_viem5 = require("viem");
2338
2588
  var OpenPosition = class _OpenPosition {
@@ -2351,11 +2601,11 @@ var OpenPosition = class _OpenPosition {
2351
2601
  minAmt1Out: scale6Decimals(params.minAmt1Out),
2352
2602
  maxAmt1In: scale6Decimals(params.maxAmt1In)
2353
2603
  };
2354
- const { result, request } = await this.context.walletClient.extend(import_viem5.publicActions).simulateContract({
2604
+ const { request } = await this.context.walletClient.extend(import_viem5.publicActions).simulateContract({
2355
2605
  address: this.context.deployments().perpManager,
2356
2606
  abi: PERP_MANAGER_ABI,
2357
2607
  functionName: "closePosition",
2358
- args: [this.perpId, contractParams],
2608
+ args: [contractParams],
2359
2609
  account: this.context.walletClient.account
2360
2610
  });
2361
2611
  const txHash = await this.context.walletClient.writeContract(request);
@@ -2364,21 +2614,35 @@ var OpenPosition = class _OpenPosition {
2364
2614
  if (receipt.status === "reverted") {
2365
2615
  throw new Error(`Transaction reverted. Hash: ${txHash}`);
2366
2616
  }
2367
- let newPositionId = result && result !== 0n ? result : null;
2617
+ let newPositionId = null;
2618
+ let wasFullyClosed = false;
2368
2619
  for (const log of receipt.logs) {
2369
2620
  try {
2370
- const closedDecoded = (0, import_viem5.decodeEventLog)({
2621
+ const openedDecoded = (0, import_viem5.decodeEventLog)({
2371
2622
  abi: PERP_MANAGER_ABI,
2372
2623
  data: log.data,
2373
2624
  topics: log.topics,
2374
- eventName: "PositionClosed"
2625
+ eventName: "PositionOpened"
2375
2626
  });
2376
- if (closedDecoded.args.perpId === this.perpId && closedDecoded.args.posId === this.positionId) {
2377
- newPositionId = null;
2627
+ if (openedDecoded.args.perpId === this.perpId) {
2628
+ newPositionId = openedDecoded.args.posId;
2378
2629
  break;
2379
2630
  }
2380
2631
  } catch (e) {
2381
- continue;
2632
+ try {
2633
+ const closedDecoded = (0, import_viem5.decodeEventLog)({
2634
+ abi: PERP_MANAGER_ABI,
2635
+ data: log.data,
2636
+ topics: log.topics,
2637
+ eventName: "PositionClosed"
2638
+ });
2639
+ if (closedDecoded.args.perpId === this.perpId && closedDecoded.args.posId === this.positionId) {
2640
+ wasFullyClosed = true;
2641
+ break;
2642
+ }
2643
+ } catch (e2) {
2644
+ continue;
2645
+ }
2382
2646
  }
2383
2647
  }
2384
2648
  if (!newPositionId) {
@@ -2392,141 +2656,42 @@ var OpenPosition = class _OpenPosition {
2392
2656
  const result = await this.context.walletClient.readContract({
2393
2657
  address: this.context.deployments().perpManager,
2394
2658
  abi: PERP_MANAGER_ABI,
2395
- functionName: "livePositionDetails",
2396
- args: [this.perpId, this.positionId]
2659
+ functionName: "quoteClosePosition",
2660
+ args: [this.positionId]
2397
2661
  });
2662
+ const [success, pnl, funding, netMargin, wasLiquidated] = result;
2663
+ if (!success) {
2664
+ throw new Error(`Failed to quote position ${this.positionId} - position may be invalid or already closed`);
2665
+ }
2398
2666
  return {
2399
- pnl: Number((0, import_viem5.formatUnits)(result[0], 6)),
2400
- fundingPayment: Number((0, import_viem5.formatUnits)(result[1], 6)),
2401
- effectiveMargin: Number((0, import_viem5.formatUnits)(result[2], 6)),
2402
- isLiquidatable: result[3]
2667
+ pnl: Number((0, import_viem5.formatUnits)(pnl, 6)),
2668
+ fundingPayment: Number((0, import_viem5.formatUnits)(funding, 6)),
2669
+ effectiveMargin: Number((0, import_viem5.formatUnits)(netMargin, 6)),
2670
+ isLiquidatable: wasLiquidated
2403
2671
  };
2404
2672
  }, `liveDetails for position ${this.positionId}`);
2405
2673
  }
2406
2674
  };
2407
2675
 
2408
- // src/functions/perp.ts
2409
- function getPerpMark(perpData) {
2410
- return perpData.mark;
2411
- }
2412
- function getPerpIndex(perpData) {
2413
- return perpData.index;
2414
- }
2415
- function getPerpBeacon(perpData) {
2416
- return perpData.beacon;
2417
- }
2418
- function getPerpLastIndexUpdate(perpData) {
2419
- return perpData.lastIndexUpdate;
2420
- }
2421
- function getPerpOpenInterest(perpData) {
2422
- return perpData.openInterest;
2423
- }
2424
- function getPerpMarkTimeSeries(perpData) {
2425
- return perpData.markTimeSeries;
2426
- }
2427
- function getPerpIndexTimeSeries(perpData) {
2428
- return perpData.indexTimeSeries;
2429
- }
2430
- function getPerpFundingRate(perpData) {
2431
- return perpData.fundingRate;
2432
- }
2433
- function getPerpBounds(perpData) {
2434
- return perpData.bounds;
2435
- }
2436
- function getPerpFees(perpData) {
2437
- return perpData.fees;
2438
- }
2439
- function getPerpOpenInterestTimeSeries(perpData) {
2440
- return perpData.openInterestTimeSeries;
2441
- }
2442
- function getPerpFundingRateTimeSeries(perpData) {
2443
- return perpData.fundingRateTimeSeries;
2444
- }
2445
- function getPerpTickSpacing(perpData) {
2446
- return perpData.tickSpacing;
2447
- }
2448
- async function getAllMakerPositions(context, perpId) {
2449
- const query = `
2450
- query ($perpId: Bytes!) {
2451
- openPositions(
2452
- where: { perp: $perpId, isMaker: true }
2453
- ) {
2454
- perp { id }
2455
- inContractPosId
2456
- isLong
2457
- isMaker
2458
- }
2459
- }
2460
- `;
2461
- const response = await context.goldskyClient.request(query, { perpId });
2462
- return response.openPositions.map(
2463
- (position) => new OpenPosition(
2464
- context,
2465
- position.perp.id,
2466
- BigInt(position.inContractPosId),
2467
- position.isLong,
2468
- position.isMaker
2469
- )
2470
- );
2471
- }
2472
- async function getAllTakerPositions(context, perpId) {
2473
- const query = `
2474
- query ($perpId: Bytes!) {
2475
- openPositions(
2476
- where: { perp: $perpId, isMaker: false }
2477
- ) {
2478
- perp { id }
2479
- inContractPosId
2480
- isLong
2481
- isMaker
2482
- }
2483
- }
2484
- `;
2485
- const response = await context.goldskyClient.request(query, { perpId });
2486
- return response.openPositions.map(
2487
- (position) => new OpenPosition(
2488
- context,
2489
- position.perp.id,
2490
- BigInt(position.inContractPosId),
2491
- position.isLong,
2492
- position.isMaker
2493
- )
2494
- );
2495
- }
2496
- async function getTotalOpenMakerPnl(context, perpId) {
2497
- const positions = await getAllMakerPositions(context, perpId);
2498
- const liveDetails = await Promise.all(positions.map((position) => position.liveDetails()));
2499
- return liveDetails.reduce((acc, detail) => acc + detail.pnl - detail.fundingPayment, 0);
2500
- }
2501
- async function getTotalOpenTakerPnl(context, perpId) {
2502
- const positions = await getAllTakerPositions(context, perpId);
2503
- const liveDetails = await Promise.all(positions.map((position) => position.liveDetails()));
2504
- return liveDetails.reduce((acc, detail) => acc + detail.pnl - detail.fundingPayment, 0);
2505
- }
2506
-
2507
2676
  // src/functions/perp-manager.ts
2508
- var import_viem6 = require("viem");
2509
- var import_graphql_request2 = require("graphql-request");
2510
- var import_graphql2 = require("graphql");
2511
- async function getPerps(context) {
2512
- return withErrorHandling(async () => {
2513
- const query = (0, import_graphql2.parse)(import_graphql_request2.gql`
2514
- {
2515
- perps {
2516
- id
2517
- }
2518
- }
2519
- `);
2520
- const response = await context.goldskyClient.request(query);
2521
- return response.perps.map((perpData) => perpData.id);
2522
- }, "getPerps");
2523
- }
2524
2677
  async function createPerp(context, params) {
2525
2678
  return withErrorHandling(async () => {
2526
2679
  const sqrtPriceX96 = priceToSqrtPriceX96(params.startingPrice);
2680
+ const deployments = context.deployments();
2681
+ const fees = params.fees ?? deployments.feesModule;
2682
+ const marginRatios = params.marginRatios ?? deployments.marginRatiosModule;
2683
+ const lockupPeriod = params.lockupPeriod ?? deployments.lockupPeriodModule;
2684
+ const sqrtPriceImpactLimit = params.sqrtPriceImpactLimit ?? deployments.sqrtPriceImpactLimitModule;
2685
+ if (!fees || !marginRatios || !lockupPeriod || !sqrtPriceImpactLimit) {
2686
+ throw new Error("Module addresses must be provided either in params or deployment config");
2687
+ }
2527
2688
  const contractParams = {
2528
- startingSqrtPriceX96: sqrtPriceX96,
2529
- beacon: params.beacon
2689
+ beacon: params.beacon,
2690
+ fees,
2691
+ marginRatios,
2692
+ lockupPeriod,
2693
+ sqrtPriceImpactLimit,
2694
+ startingSqrtPriceX96: sqrtPriceX96
2530
2695
  };
2531
2696
  const { request } = await context.walletClient.simulateContract({
2532
2697
  address: context.deployments().perpManager,
@@ -2563,6 +2728,7 @@ async function openTakerPosition(context, perpId, params) {
2563
2728
  await approveUsdc(context, marginScaled);
2564
2729
  const levX96 = scaleToX96(params.leverage);
2565
2730
  const contractParams = {
2731
+ holder: context.walletClient.account.address,
2566
2732
  isLong: params.isLong,
2567
2733
  margin: marginScaled,
2568
2734
  levX96,
@@ -2571,7 +2737,7 @@ async function openTakerPosition(context, perpId, params) {
2571
2737
  const { request } = await context.walletClient.simulateContract({
2572
2738
  address: context.deployments().perpManager,
2573
2739
  abi: PERP_MANAGER_ABI,
2574
- functionName: "openTakerPosition",
2740
+ functionName: "openTakerPos",
2575
2741
  args: [perpId, contractParams],
2576
2742
  account: context.walletClient.account
2577
2743
  });
@@ -2615,6 +2781,7 @@ async function openMakerPosition(context, perpId, params) {
2615
2781
  const alignedTickLower = Math.floor(tickLower / tickSpacing) * tickSpacing;
2616
2782
  const alignedTickUpper = Math.ceil(tickUpper / tickSpacing) * tickSpacing;
2617
2783
  const contractParams = {
2784
+ holder: context.walletClient.account.address,
2618
2785
  margin: marginScaled,
2619
2786
  liquidity: params.liquidity,
2620
2787
  tickLower: alignedTickLower,
@@ -2625,7 +2792,7 @@ async function openMakerPosition(context, perpId, params) {
2625
2792
  const { request } = await context.walletClient.simulateContract({
2626
2793
  address: context.deployments().perpManager,
2627
2794
  abi: PERP_MANAGER_ABI,
2628
- functionName: "openMakerPosition",
2795
+ functionName: "openMakerPos",
2629
2796
  args: [perpId, contractParams],
2630
2797
  account: context.walletClient.account
2631
2798
  });
@@ -2666,15 +2833,6 @@ function getUserUsdcBalance(userData) {
2666
2833
  function getUserOpenPositions(userData) {
2667
2834
  return userData.openPositions;
2668
2835
  }
2669
- function getUserClosedPositions(userData) {
2670
- return userData.closedPositions;
2671
- }
2672
- function getUserRealizedPnl(userData) {
2673
- return userData.realizedPnl;
2674
- }
2675
- function getUserUnrealizedPnl(userData) {
2676
- return userData.unrealizedPnl;
2677
- }
2678
2836
  function getUserWalletAddress(userData) {
2679
2837
  return userData.walletAddress;
2680
2838
  }
@@ -2721,7 +2879,7 @@ async function closePosition(context, perpId, positionId, params) {
2721
2879
  address: context.deployments().perpManager,
2722
2880
  abi: PERP_MANAGER_ABI,
2723
2881
  functionName: "closePosition",
2724
- args: [perpId, contractParams],
2882
+ args: [contractParams],
2725
2883
  account: context.walletClient.account
2726
2884
  });
2727
2885
  const txHash = await context.walletClient.writeContract(request);
@@ -2762,14 +2920,18 @@ async function getPositionLiveDetailsFromContract(context, perpId, positionId) {
2762
2920
  const result = await context.walletClient.readContract({
2763
2921
  address: context.deployments().perpManager,
2764
2922
  abi: PERP_MANAGER_ABI,
2765
- functionName: "livePositionDetails",
2766
- args: [perpId, positionId]
2923
+ functionName: "quoteClosePosition",
2924
+ args: [positionId]
2767
2925
  });
2926
+ const [success, pnl, funding, netMargin, wasLiquidated] = result;
2927
+ if (!success) {
2928
+ throw new Error(`Failed to quote position ${positionId} - position may be invalid or already closed`);
2929
+ }
2768
2930
  return {
2769
- pnl: Number((0, import_viem7.formatUnits)(result[0], 6)),
2770
- fundingPayment: Number((0, import_viem7.formatUnits)(result[1], 6)),
2771
- effectiveMargin: Number((0, import_viem7.formatUnits)(result[2], 6)),
2772
- isLiquidatable: result[3]
2931
+ pnl: Number((0, import_viem7.formatUnits)(pnl, 6)),
2932
+ fundingPayment: Number((0, import_viem7.formatUnits)(funding, 6)),
2933
+ effectiveMargin: Number((0, import_viem7.formatUnits)(netMargin, 6)),
2934
+ isLiquidatable: wasLiquidated
2773
2935
  };
2774
2936
  }, `getPositionLiveDetailsFromContract for position ${positionId}`);
2775
2937
  }
@@ -2778,7 +2940,6 @@ async function getPositionLiveDetailsFromContract(context, perpId, positionId) {
2778
2940
  BEACON_ABI,
2779
2941
  BIGINT_1E6,
2780
2942
  ContractError,
2781
- GraphQLError,
2782
2943
  InsufficientFundsError,
2783
2944
  NUMBER_1E6,
2784
2945
  OpenPosition,
@@ -2793,22 +2954,11 @@ async function getPositionLiveDetailsFromContract(context, perpId, positionId) {
2793
2954
  closePosition,
2794
2955
  createPerp,
2795
2956
  estimateLiquidity,
2796
- getAllMakerPositions,
2797
- getAllTakerPositions,
2798
2957
  getPerpBeacon,
2799
2958
  getPerpBounds,
2800
2959
  getPerpFees,
2801
- getPerpFundingRate,
2802
- getPerpFundingRateTimeSeries,
2803
- getPerpIndex,
2804
- getPerpIndexTimeSeries,
2805
- getPerpLastIndexUpdate,
2806
2960
  getPerpMark,
2807
- getPerpMarkTimeSeries,
2808
- getPerpOpenInterest,
2809
- getPerpOpenInterestTimeSeries,
2810
2961
  getPerpTickSpacing,
2811
- getPerps,
2812
2962
  getPositionEffectiveMargin,
2813
2963
  getPositionFundingPayment,
2814
2964
  getPositionId,
@@ -2819,12 +2969,8 @@ async function getPositionLiveDetailsFromContract(context, perpId, positionId) {
2819
2969
  getPositionLiveDetailsFromContract,
2820
2970
  getPositionPerpId,
2821
2971
  getPositionPnl,
2822
- getTotalOpenMakerPnl,
2823
- getTotalOpenTakerPnl,
2824
- getUserClosedPositions,
2972
+ getRpcUrl,
2825
2973
  getUserOpenPositions,
2826
- getUserRealizedPnl,
2827
- getUserUnrealizedPnl,
2828
2974
  getUserUsdcBalance,
2829
2975
  getUserWalletAddress,
2830
2976
  marginRatioToLeverage,