perps-sdk-ts 1.0.1

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.
Files changed (117) hide show
  1. package/.claude/settings.local.json +11 -0
  2. package/CONTRACT_METHOD_FIXES.md +189 -0
  3. package/INTEGRATION_SUMMARY.md +219 -0
  4. package/OPTIMIZATION_GUIDE.md +238 -0
  5. package/README.md +384 -0
  6. package/SNAPSHOT_FIX_SUMMARY.md +161 -0
  7. package/SNAPSHOT_OPTIMIZATION_SUMMARY.md +199 -0
  8. package/dist/abis/Referral.d.ts +36 -0
  9. package/dist/abis/Referral.js +4 -0
  10. package/dist/abis/Trading.d.ts +57 -0
  11. package/dist/abis/Trading.js +742 -0
  12. package/dist/abis/erc20.d.ts +51 -0
  13. package/dist/abis/erc20.js +4 -0
  14. package/dist/abis/index.d.ts +8 -0
  15. package/dist/abis/index.js +24 -0
  16. package/dist/abis/multicall.d.ts +85 -0
  17. package/dist/abis/multicall.js +4 -0
  18. package/dist/abis/pairInfos.d.ts +77 -0
  19. package/dist/abis/pairInfos.js +4 -0
  20. package/dist/abis/pairStorage.d.ts +124 -0
  21. package/dist/abis/pairStorage.js +4 -0
  22. package/dist/abis/priceAggregator.d.ts +77 -0
  23. package/dist/abis/priceAggregator.js +4 -0
  24. package/dist/abis/tardingStorage.d.ts +97 -0
  25. package/dist/abis/tardingStorage.js +1295 -0
  26. package/dist/abis.d.ts +623 -0
  27. package/dist/abis.js +49 -0
  28. package/dist/client.d.ts +118 -0
  29. package/dist/client.js +224 -0
  30. package/dist/config.d.ts +43 -0
  31. package/dist/config.js +42 -0
  32. package/dist/crypto/spki.d.ts +55 -0
  33. package/dist/crypto/spki.js +160 -0
  34. package/dist/feed/feed_client.d.ts +68 -0
  35. package/dist/feed/feed_client.js +239 -0
  36. package/dist/index.d.ts +28 -0
  37. package/dist/index.js +87 -0
  38. package/dist/rpc/asset_parameters.d.ts +62 -0
  39. package/dist/rpc/asset_parameters.js +169 -0
  40. package/dist/rpc/blended.d.ts +23 -0
  41. package/dist/rpc/blended.js +55 -0
  42. package/dist/rpc/category_parameters.d.ts +34 -0
  43. package/dist/rpc/category_parameters.js +105 -0
  44. package/dist/rpc/delegation.d.ts +81 -0
  45. package/dist/rpc/delegation.js +180 -0
  46. package/dist/rpc/fee_parameters.d.ts +46 -0
  47. package/dist/rpc/fee_parameters.js +113 -0
  48. package/dist/rpc/multicall.d.ts +83 -0
  49. package/dist/rpc/multicall.js +117 -0
  50. package/dist/rpc/pair_info_queries.d.ts +101 -0
  51. package/dist/rpc/pair_info_queries.js +161 -0
  52. package/dist/rpc/pairs_cache.d.ts +62 -0
  53. package/dist/rpc/pairs_cache.js +240 -0
  54. package/dist/rpc/referral_operations.d.ts +67 -0
  55. package/dist/rpc/referral_operations.js +143 -0
  56. package/dist/rpc/snapshot.d.ts +49 -0
  57. package/dist/rpc/snapshot.js +162 -0
  58. package/dist/rpc/trade.d.ts +84 -0
  59. package/dist/rpc/trade.js +249 -0
  60. package/dist/rpc/trading_operations.d.ts +103 -0
  61. package/dist/rpc/trading_operations.js +295 -0
  62. package/dist/rpc/trading_parameters.d.ts +49 -0
  63. package/dist/rpc/trading_parameters.js +94 -0
  64. package/dist/signers/base.d.ts +24 -0
  65. package/dist/signers/base.js +10 -0
  66. package/dist/signers/kms.d.ts +47 -0
  67. package/dist/signers/kms.js +172 -0
  68. package/dist/signers/local.d.ts +43 -0
  69. package/dist/signers/local.js +64 -0
  70. package/dist/types.d.ts +1419 -0
  71. package/dist/types.js +245 -0
  72. package/dist/utils.d.ts +52 -0
  73. package/dist/utils.js +134 -0
  74. package/examples/advanced-queries.ts +181 -0
  75. package/examples/basic-usage.ts +78 -0
  76. package/examples/delegation-and-referrals.ts +130 -0
  77. package/examples/get-pyth-ids.ts +61 -0
  78. package/examples/kms-signer.ts +31 -0
  79. package/examples/optimized-snapshot.ts +153 -0
  80. package/examples/price-feed-with-sdk-ids.ts +97 -0
  81. package/examples/price-feed.ts +36 -0
  82. package/examples/trading-operations.ts +149 -0
  83. package/package.json +41 -0
  84. package/src/abis/Referral.ts +3 -0
  85. package/src/abis/Trading.ts +741 -0
  86. package/src/abis/erc20.ts +3 -0
  87. package/src/abis/index.ts +8 -0
  88. package/src/abis/multicall.ts +3 -0
  89. package/src/abis/pairInfos.ts +3 -0
  90. package/src/abis/pairStorage.ts +3 -0
  91. package/src/abis/priceAggregator.ts +3 -0
  92. package/src/abis/tardingStorage.ts +1294 -0
  93. package/src/abis.ts +56 -0
  94. package/src/client.ts +373 -0
  95. package/src/config.ts +62 -0
  96. package/src/crypto/spki.ts +197 -0
  97. package/src/feed/feed_client.ts +288 -0
  98. package/src/index.ts +114 -0
  99. package/src/rpc/asset_parameters.ts +217 -0
  100. package/src/rpc/blended.ts +77 -0
  101. package/src/rpc/category_parameters.ts +128 -0
  102. package/src/rpc/delegation.ts +225 -0
  103. package/src/rpc/fee_parameters.ts +150 -0
  104. package/src/rpc/multicall.ts +164 -0
  105. package/src/rpc/pair_info_queries.ts +208 -0
  106. package/src/rpc/pairs_cache.ts +268 -0
  107. package/src/rpc/referral_operations.ts +164 -0
  108. package/src/rpc/snapshot.ts +210 -0
  109. package/src/rpc/trade.ts +306 -0
  110. package/src/rpc/trading_operations.ts +378 -0
  111. package/src/rpc/trading_parameters.ts +127 -0
  112. package/src/signers/base.ts +27 -0
  113. package/src/signers/kms.ts +212 -0
  114. package/src/signers/local.ts +70 -0
  115. package/src/types.ts +410 -0
  116. package/src/utils.ts +155 -0
  117. package/tsconfig.json +18 -0
@@ -0,0 +1,68 @@
1
+ import { PriceFeedResponse } from "../types";
2
+ /**
3
+ * Callback function type for price updates
4
+ */
5
+ export type PriceUpdateCallback = (priceData: PriceFeedResponse) => void;
6
+ /**
7
+ * WebSocket client for real-time price feeds from Pyth Network
8
+ */
9
+ export declare class FeedClient {
10
+ private url;
11
+ private ws?;
12
+ private callbacks;
13
+ private onError?;
14
+ private onClose?;
15
+ private pairFeedMap;
16
+ private reconnectAttempts;
17
+ private maxReconnectAttempts;
18
+ private reconnectDelay;
19
+ constructor(url?: string, onError?: (error: Error) => void, onClose?: () => void);
20
+ /**
21
+ * Register a callback for a specific price feed
22
+ */
23
+ registerPriceFeedCallback(feedId: string, callback: PriceUpdateCallback): void;
24
+ /**
25
+ * Unregister a callback for a specific price feed
26
+ */
27
+ unregisterPriceFeedCallback(feedId: string, callback: PriceUpdateCallback): void;
28
+ /**
29
+ * Load pair to feed ID mappings
30
+ */
31
+ loadPairFeeds(pairFeeds: Map<string, string>): void;
32
+ /**
33
+ * Get feed ID for a trading pair
34
+ */
35
+ getFeedIdForPair(pairName: string): string | undefined;
36
+ /**
37
+ * Connect to WebSocket and listen for price updates
38
+ */
39
+ listenForPriceUpdates(): Promise<void>;
40
+ /**
41
+ * Subscribe to specific price feeds
42
+ */
43
+ private subscribeToPriceFeeds;
44
+ /**
45
+ * Unsubscribe from specific price feeds
46
+ */
47
+ private unsubscribeFromPriceFeeds;
48
+ /**
49
+ * Handle incoming price update
50
+ */
51
+ private handlePriceUpdate;
52
+ /**
53
+ * Attempt to reconnect to WebSocket
54
+ */
55
+ private attemptReconnect;
56
+ /**
57
+ * Get latest prices via HTTP
58
+ */
59
+ getLatestPriceUpdates(feedIds: string[]): Promise<any>;
60
+ /**
61
+ * Close the WebSocket connection
62
+ */
63
+ close(): void;
64
+ /**
65
+ * Check if WebSocket is connected
66
+ */
67
+ isConnected(): boolean;
68
+ }
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.FeedClient = void 0;
7
+ const ws_1 = __importDefault(require("ws"));
8
+ const types_1 = require("../types");
9
+ const config_1 = require("../config");
10
+ /**
11
+ * Normalize feed ID: remove 0x prefix and lowercase
12
+ * Pyth WebSocket sends IDs WITHOUT 0x prefix
13
+ */
14
+ function normalizeFeedId(feedId) {
15
+ let normalized = feedId.toLowerCase();
16
+ if (normalized.startsWith('0x')) {
17
+ normalized = normalized.slice(2);
18
+ }
19
+ return normalized;
20
+ }
21
+ /**
22
+ * WebSocket client for real-time price feeds from Pyth Network
23
+ */
24
+ class FeedClient {
25
+ constructor(url = config_1.API_ENDPOINTS.PYTH_WS, onError, onClose) {
26
+ this.callbacks = new Map();
27
+ this.pairFeedMap = new Map();
28
+ this.reconnectAttempts = 0;
29
+ this.maxReconnectAttempts = 5;
30
+ this.reconnectDelay = 1000;
31
+ this.url = url;
32
+ this.onError = onError;
33
+ this.onClose = onClose;
34
+ }
35
+ /**
36
+ * Register a callback for a specific price feed
37
+ */
38
+ registerPriceFeedCallback(feedId, callback) {
39
+ const id = normalizeFeedId(feedId);
40
+ if (!this.callbacks.has(id)) {
41
+ this.callbacks.set(id, []);
42
+ }
43
+ this.callbacks.get(id).push(callback);
44
+ if (this.callbacks.get(id).length === 1 && this.isConnected()) {
45
+ this.subscribeToPriceFeeds([id]);
46
+ }
47
+ }
48
+ /**
49
+ * Unregister a callback for a specific price feed
50
+ */
51
+ unregisterPriceFeedCallback(feedId, callback) {
52
+ const id = normalizeFeedId(feedId);
53
+ const cbs = this.callbacks.get(id);
54
+ if (!cbs)
55
+ return;
56
+ const idx = cbs.indexOf(callback);
57
+ if (idx > -1)
58
+ cbs.splice(idx, 1);
59
+ if (cbs.length === 0 && this.isConnected()) {
60
+ this.unsubscribeFromPriceFeeds([id]);
61
+ this.callbacks.delete(id);
62
+ }
63
+ }
64
+ /**
65
+ * Load pair to feed ID mappings
66
+ */
67
+ loadPairFeeds(pairFeeds) {
68
+ this.pairFeedMap = pairFeeds;
69
+ }
70
+ /**
71
+ * Get feed ID for a trading pair
72
+ */
73
+ getFeedIdForPair(pairName) {
74
+ return this.pairFeedMap.get(pairName);
75
+ }
76
+ /**
77
+ * Connect to WebSocket and listen for price updates
78
+ */
79
+ async listenForPriceUpdates() {
80
+ return new Promise((resolve, reject) => {
81
+ try {
82
+ this.ws = new ws_1.default(this.url);
83
+ this.ws.on("open", () => {
84
+ console.log("WebSocket connected to Pyth Network");
85
+ this.reconnectAttempts = 0;
86
+ const feedIds = Array.from(this.callbacks.keys());
87
+ if (feedIds.length > 0) {
88
+ this.subscribeToPriceFeeds(feedIds);
89
+ }
90
+ resolve();
91
+ });
92
+ this.ws.on("message", (data) => {
93
+ try {
94
+ const message = JSON.parse(data.toString());
95
+ if (message.type !== "price_update") {
96
+ console.log("Received non-update message:", message);
97
+ }
98
+ if (message.type === "price_update") {
99
+ this.handlePriceUpdate(message);
100
+ }
101
+ }
102
+ catch (error) {
103
+ console.error("Error parsing WebSocket message:", error);
104
+ }
105
+ });
106
+ this.ws.on("error", (error) => {
107
+ console.error("WebSocket error:", error);
108
+ if (this.onError) {
109
+ this.onError(error);
110
+ }
111
+ reject(error);
112
+ });
113
+ this.ws.on("close", () => {
114
+ console.log("WebSocket connection closed");
115
+ if (this.onClose) {
116
+ this.onClose();
117
+ }
118
+ this.attemptReconnect();
119
+ });
120
+ }
121
+ catch (error) {
122
+ reject(error);
123
+ }
124
+ });
125
+ }
126
+ /**
127
+ * Subscribe to specific price feeds
128
+ */
129
+ subscribeToPriceFeeds(feedIds) {
130
+ if (!this.ws || this.ws.readyState !== ws_1.default.OPEN)
131
+ return;
132
+ // Feed IDs should already be normalized, but ensure they are
133
+ const ids = feedIds.map(id => normalizeFeedId(id));
134
+ this.ws.send(JSON.stringify({ type: "subscribe", ids }));
135
+ console.log("Subscribed to Pyth feeds:", ids);
136
+ }
137
+ /**
138
+ * Unsubscribe from specific price feeds
139
+ */
140
+ unsubscribeFromPriceFeeds(feedIds) {
141
+ if (!this.ws || this.ws.readyState !== ws_1.default.OPEN)
142
+ return;
143
+ const ids = feedIds.map(id => normalizeFeedId(id));
144
+ this.ws.send(JSON.stringify({ type: "unsubscribe", ids }));
145
+ console.log("Unsubscribed from Pyth feeds:", ids);
146
+ }
147
+ /**
148
+ * Handle incoming price update
149
+ */
150
+ handlePriceUpdate(message) {
151
+ try {
152
+ if (message.price_feed) {
153
+ const priceUpdate = message.price_feed;
154
+ // ⭐ KEY FIX: Normalize the incoming feed ID (Pyth sends without 0x)
155
+ const feedId = normalizeFeedId(priceUpdate.id);
156
+ const priceFeed = {
157
+ id: feedId,
158
+ price: {
159
+ price: priceUpdate.price.price,
160
+ conf: priceUpdate.price.conf,
161
+ expo: priceUpdate.price.expo,
162
+ publishTime: priceUpdate.price.publish_time,
163
+ },
164
+ emaPrice: {
165
+ price: priceUpdate.ema_price.price,
166
+ conf: priceUpdate.ema_price.conf,
167
+ expo: priceUpdate.ema_price.expo,
168
+ publishTime: priceUpdate.ema_price.publish_time,
169
+ },
170
+ };
171
+ const validatedPriceFeed = types_1.PriceFeedResponseSchema.parse(priceFeed);
172
+ // Trigger callbacks
173
+ const callbacks = this.callbacks.get(validatedPriceFeed.id);
174
+ if (callbacks && callbacks.length > 0) {
175
+ console.log(`✅ Triggering ${callbacks.length} callback(s) for ${validatedPriceFeed.id}`);
176
+ callbacks.forEach((callback) => {
177
+ try {
178
+ callback(validatedPriceFeed);
179
+ }
180
+ catch (error) {
181
+ console.error("Error in price update callback:", error instanceof Error ? error.message : String(error));
182
+ }
183
+ });
184
+ }
185
+ else {
186
+ console.warn(`⚠️ No callbacks registered for feed: ${validatedPriceFeed.id}`);
187
+ console.log(`Registered feeds: [${Array.from(this.callbacks.keys()).join(", ")}]`);
188
+ }
189
+ }
190
+ }
191
+ catch (error) {
192
+ console.error("Error processing price update:", error instanceof Error ? error.message : String(error));
193
+ }
194
+ }
195
+ /**
196
+ * Attempt to reconnect to WebSocket
197
+ */
198
+ attemptReconnect() {
199
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
200
+ console.error("Max reconnection attempts reached");
201
+ return;
202
+ }
203
+ this.reconnectAttempts++;
204
+ const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
205
+ console.log(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
206
+ setTimeout(() => {
207
+ this.listenForPriceUpdates().catch((error) => {
208
+ console.error("Reconnection failed:", error);
209
+ });
210
+ }, delay);
211
+ }
212
+ /**
213
+ * Get latest prices via HTTP
214
+ */
215
+ async getLatestPriceUpdates(feedIds) {
216
+ const url = `${config_1.API_ENDPOINTS.PYTH_HTTP}?ids[]=${feedIds.join("&ids[]=")}`;
217
+ const response = await fetch(url);
218
+ if (!response.ok) {
219
+ throw new Error(`Failed to fetch prices: ${response.statusText}`);
220
+ }
221
+ return await response.json();
222
+ }
223
+ /**
224
+ * Close the WebSocket connection
225
+ */
226
+ close() {
227
+ if (this.ws) {
228
+ this.ws.close();
229
+ this.ws = undefined;
230
+ }
231
+ }
232
+ /**
233
+ * Check if WebSocket is connected
234
+ */
235
+ isConnected() {
236
+ return this.ws !== undefined && this.ws.readyState === ws_1.default.OPEN;
237
+ }
238
+ }
239
+ exports.FeedClient = FeedClient;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Avantis Trader SDK - TypeScript
3
+ *
4
+ * A comprehensive SDK for interacting with the Avantis decentralized
5
+ * leveraged trading platform.
6
+ */
7
+ export { TraderClient } from './client';
8
+ export { BaseSigner } from './signers/base';
9
+ export { LocalSigner } from './signers/local';
10
+ export { KMSSigner } from './signers/kms';
11
+ export { FeedClient, PriceUpdateCallback } from './feed/feed_client';
12
+ export { PairsCache } from './rpc/pairs_cache';
13
+ export { AssetParametersRPC } from './rpc/asset_parameters';
14
+ export { CategoryParametersRPC } from './rpc/category_parameters';
15
+ export { FeeParametersRPC } from './rpc/fee_parameters';
16
+ export { TradingParametersRPC } from './rpc/trading_parameters';
17
+ export { BlendedRPC } from './rpc/blended';
18
+ export { TradeRPC } from './rpc/trade';
19
+ export { SnapshotRPC } from './rpc/snapshot';
20
+ export { TradingOperationsRPC } from './rpc/trading_operations';
21
+ export { DelegationRPC } from './rpc/delegation';
22
+ export { PairInfoQueriesRPC } from './rpc/pair_info_queries';
23
+ export { ReferralOperationsRPC } from './rpc/referral_operations';
24
+ export { MulticallRPC, type MulticallCall, type MulticallResult } from './rpc/multicall';
25
+ export { TradeInputOrderType, MarginUpdateType, type Spread, type PairInfo, type TradeInput, type TradeResponse, type Price, type EmaPrice, type PriceFeedResponse, type OpenInterest, type OpenInterestLimits, type Utilization, type Skew, type Fee, type Depth, type LossProtectionInfo, type PairData, type Group, type Snapshot, type Trade, type TradeInfo, type OpenLimitOrder, type ReferralTier, type ReferralDiscount, type ContractCallOptions, type TransactionReceipt, type PairsBackendReturn, type ContractPairInfo, type PairStruct, type GroupStruct, type FeeStruct, type FeedStruct, type BackupFeedStruct, type LeverageStruct, type ValuesStruct, type PnlFeesStruct, fromBlockchain10, fromBlockchain6, toBlockchain10, toBlockchain6, fromBlockchain12, toBlockchain12, fromBlockchain18, toBlockchain18, } from './types';
26
+ export { CONTRACTS, API_ENDPOINTS, type ContractAddresses, type NetworkConfig, getContractAddress, setContractAddresses, } from './config';
27
+ export { isTupleType, isArrayType, processOutputTypes, decoder, hexToNumber, numberToHex, isValidAddress, toChecksumAddress, sleep, retryWithBackoff, } from './utils';
28
+ export { publicKeyIntToEthAddress, derEncodedPublicKeyToEthAddress, getSigRS, getSigV, getSigRSV, signatureToHex, } from './crypto/spki';
package/dist/index.js ADDED
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /**
3
+ * Avantis Trader SDK - TypeScript
4
+ *
5
+ * A comprehensive SDK for interacting with the Avantis decentralized
6
+ * leveraged trading platform.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.signatureToHex = exports.getSigRSV = exports.getSigV = exports.getSigRS = exports.derEncodedPublicKeyToEthAddress = exports.publicKeyIntToEthAddress = exports.retryWithBackoff = exports.sleep = exports.toChecksumAddress = exports.isValidAddress = exports.numberToHex = exports.hexToNumber = exports.decoder = exports.processOutputTypes = exports.isArrayType = exports.isTupleType = exports.setContractAddresses = exports.getContractAddress = exports.API_ENDPOINTS = exports.CONTRACTS = exports.toBlockchain18 = exports.fromBlockchain18 = exports.toBlockchain12 = exports.fromBlockchain12 = exports.toBlockchain6 = exports.toBlockchain10 = exports.fromBlockchain6 = exports.fromBlockchain10 = exports.MarginUpdateType = exports.TradeInputOrderType = exports.MulticallRPC = exports.ReferralOperationsRPC = exports.PairInfoQueriesRPC = exports.DelegationRPC = exports.TradingOperationsRPC = exports.SnapshotRPC = exports.TradeRPC = exports.BlendedRPC = exports.TradingParametersRPC = exports.FeeParametersRPC = exports.CategoryParametersRPC = exports.AssetParametersRPC = exports.PairsCache = exports.FeedClient = exports.KMSSigner = exports.LocalSigner = exports.BaseSigner = exports.TraderClient = void 0;
10
+ // Main client
11
+ var client_1 = require("./client");
12
+ Object.defineProperty(exports, "TraderClient", { enumerable: true, get: function () { return client_1.TraderClient; } });
13
+ // Signers
14
+ var base_1 = require("./signers/base");
15
+ Object.defineProperty(exports, "BaseSigner", { enumerable: true, get: function () { return base_1.BaseSigner; } });
16
+ var local_1 = require("./signers/local");
17
+ Object.defineProperty(exports, "LocalSigner", { enumerable: true, get: function () { return local_1.LocalSigner; } });
18
+ var kms_1 = require("./signers/kms");
19
+ Object.defineProperty(exports, "KMSSigner", { enumerable: true, get: function () { return kms_1.KMSSigner; } });
20
+ // Feed client
21
+ var feed_client_1 = require("./feed/feed_client");
22
+ Object.defineProperty(exports, "FeedClient", { enumerable: true, get: function () { return feed_client_1.FeedClient; } });
23
+ // RPC modules
24
+ var pairs_cache_1 = require("./rpc/pairs_cache");
25
+ Object.defineProperty(exports, "PairsCache", { enumerable: true, get: function () { return pairs_cache_1.PairsCache; } });
26
+ var asset_parameters_1 = require("./rpc/asset_parameters");
27
+ Object.defineProperty(exports, "AssetParametersRPC", { enumerable: true, get: function () { return asset_parameters_1.AssetParametersRPC; } });
28
+ var category_parameters_1 = require("./rpc/category_parameters");
29
+ Object.defineProperty(exports, "CategoryParametersRPC", { enumerable: true, get: function () { return category_parameters_1.CategoryParametersRPC; } });
30
+ var fee_parameters_1 = require("./rpc/fee_parameters");
31
+ Object.defineProperty(exports, "FeeParametersRPC", { enumerable: true, get: function () { return fee_parameters_1.FeeParametersRPC; } });
32
+ var trading_parameters_1 = require("./rpc/trading_parameters");
33
+ Object.defineProperty(exports, "TradingParametersRPC", { enumerable: true, get: function () { return trading_parameters_1.TradingParametersRPC; } });
34
+ var blended_1 = require("./rpc/blended");
35
+ Object.defineProperty(exports, "BlendedRPC", { enumerable: true, get: function () { return blended_1.BlendedRPC; } });
36
+ var trade_1 = require("./rpc/trade");
37
+ Object.defineProperty(exports, "TradeRPC", { enumerable: true, get: function () { return trade_1.TradeRPC; } });
38
+ var snapshot_1 = require("./rpc/snapshot");
39
+ Object.defineProperty(exports, "SnapshotRPC", { enumerable: true, get: function () { return snapshot_1.SnapshotRPC; } });
40
+ var trading_operations_1 = require("./rpc/trading_operations");
41
+ Object.defineProperty(exports, "TradingOperationsRPC", { enumerable: true, get: function () { return trading_operations_1.TradingOperationsRPC; } });
42
+ var delegation_1 = require("./rpc/delegation");
43
+ Object.defineProperty(exports, "DelegationRPC", { enumerable: true, get: function () { return delegation_1.DelegationRPC; } });
44
+ var pair_info_queries_1 = require("./rpc/pair_info_queries");
45
+ Object.defineProperty(exports, "PairInfoQueriesRPC", { enumerable: true, get: function () { return pair_info_queries_1.PairInfoQueriesRPC; } });
46
+ var referral_operations_1 = require("./rpc/referral_operations");
47
+ Object.defineProperty(exports, "ReferralOperationsRPC", { enumerable: true, get: function () { return referral_operations_1.ReferralOperationsRPC; } });
48
+ var multicall_1 = require("./rpc/multicall");
49
+ Object.defineProperty(exports, "MulticallRPC", { enumerable: true, get: function () { return multicall_1.MulticallRPC; } });
50
+ // Types and enums
51
+ var types_1 = require("./types");
52
+ Object.defineProperty(exports, "TradeInputOrderType", { enumerable: true, get: function () { return types_1.TradeInputOrderType; } });
53
+ Object.defineProperty(exports, "MarginUpdateType", { enumerable: true, get: function () { return types_1.MarginUpdateType; } });
54
+ Object.defineProperty(exports, "fromBlockchain10", { enumerable: true, get: function () { return types_1.fromBlockchain10; } });
55
+ Object.defineProperty(exports, "fromBlockchain6", { enumerable: true, get: function () { return types_1.fromBlockchain6; } });
56
+ Object.defineProperty(exports, "toBlockchain10", { enumerable: true, get: function () { return types_1.toBlockchain10; } });
57
+ Object.defineProperty(exports, "toBlockchain6", { enumerable: true, get: function () { return types_1.toBlockchain6; } });
58
+ Object.defineProperty(exports, "fromBlockchain12", { enumerable: true, get: function () { return types_1.fromBlockchain12; } });
59
+ Object.defineProperty(exports, "toBlockchain12", { enumerable: true, get: function () { return types_1.toBlockchain12; } });
60
+ Object.defineProperty(exports, "fromBlockchain18", { enumerable: true, get: function () { return types_1.fromBlockchain18; } });
61
+ Object.defineProperty(exports, "toBlockchain18", { enumerable: true, get: function () { return types_1.toBlockchain18; } });
62
+ // Configuration
63
+ var config_1 = require("./config");
64
+ Object.defineProperty(exports, "CONTRACTS", { enumerable: true, get: function () { return config_1.CONTRACTS; } });
65
+ Object.defineProperty(exports, "API_ENDPOINTS", { enumerable: true, get: function () { return config_1.API_ENDPOINTS; } });
66
+ Object.defineProperty(exports, "getContractAddress", { enumerable: true, get: function () { return config_1.getContractAddress; } });
67
+ Object.defineProperty(exports, "setContractAddresses", { enumerable: true, get: function () { return config_1.setContractAddresses; } });
68
+ // Utilities
69
+ var utils_1 = require("./utils");
70
+ Object.defineProperty(exports, "isTupleType", { enumerable: true, get: function () { return utils_1.isTupleType; } });
71
+ Object.defineProperty(exports, "isArrayType", { enumerable: true, get: function () { return utils_1.isArrayType; } });
72
+ Object.defineProperty(exports, "processOutputTypes", { enumerable: true, get: function () { return utils_1.processOutputTypes; } });
73
+ Object.defineProperty(exports, "decoder", { enumerable: true, get: function () { return utils_1.decoder; } });
74
+ Object.defineProperty(exports, "hexToNumber", { enumerable: true, get: function () { return utils_1.hexToNumber; } });
75
+ Object.defineProperty(exports, "numberToHex", { enumerable: true, get: function () { return utils_1.numberToHex; } });
76
+ Object.defineProperty(exports, "isValidAddress", { enumerable: true, get: function () { return utils_1.isValidAddress; } });
77
+ Object.defineProperty(exports, "toChecksumAddress", { enumerable: true, get: function () { return utils_1.toChecksumAddress; } });
78
+ Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return utils_1.sleep; } });
79
+ Object.defineProperty(exports, "retryWithBackoff", { enumerable: true, get: function () { return utils_1.retryWithBackoff; } });
80
+ // Crypto utilities (for advanced usage)
81
+ var spki_1 = require("./crypto/spki");
82
+ Object.defineProperty(exports, "publicKeyIntToEthAddress", { enumerable: true, get: function () { return spki_1.publicKeyIntToEthAddress; } });
83
+ Object.defineProperty(exports, "derEncodedPublicKeyToEthAddress", { enumerable: true, get: function () { return spki_1.derEncodedPublicKeyToEthAddress; } });
84
+ Object.defineProperty(exports, "getSigRS", { enumerable: true, get: function () { return spki_1.getSigRS; } });
85
+ Object.defineProperty(exports, "getSigV", { enumerable: true, get: function () { return spki_1.getSigV; } });
86
+ Object.defineProperty(exports, "getSigRSV", { enumerable: true, get: function () { return spki_1.getSigRSV; } });
87
+ Object.defineProperty(exports, "signatureToHex", { enumerable: true, get: function () { return spki_1.signatureToHex; } });
@@ -0,0 +1,62 @@
1
+ import { Contract, Provider } from 'ethers';
2
+ import { OpenInterest, OpenInterestLimits, Utilization, Skew, TradeInput } from '../types';
3
+ import { PairsCache } from './pairs_cache';
4
+ /**
5
+ * RPC module for retrieving asset-level parameters
6
+ */
7
+ export declare class AssetParametersRPC {
8
+ private provider;
9
+ private pairStorageContract;
10
+ private pairInfosContract;
11
+ private tradingStorageContract;
12
+ private pairsCache;
13
+ constructor(provider: Provider, pairStorageContract: Contract, pairInfosContract: Contract, pairsCache: PairsCache, tradingStorageContract: Contract);
14
+ /**
15
+ * Get open interest limits for all pairs
16
+ * @returns Map of pair index to OI limits
17
+ */
18
+ getOILimits(): Promise<Map<number, OpenInterestLimits>>;
19
+ /**
20
+ * Get current open interest for all pairs
21
+ * @returns Map of pair index to OI
22
+ */
23
+ getOI(): Promise<Map<number, OpenInterest>>;
24
+ /**
25
+ * Get utilization for all pairs
26
+ * @returns Map of pair index to utilization
27
+ */
28
+ getUtilization(): Promise<Map<number, Utilization>>;
29
+ /**
30
+ * Get asset skew (long / total) for all pairs
31
+ * @returns Map of pair index to skew
32
+ */
33
+ getAssetSkew(): Promise<Map<number, Skew>>;
34
+ /**
35
+ * Get price impact spread for opening a position
36
+ * @param positionSize - Position size in USDC
37
+ * @param isLong - True for long, false for short
38
+ * @param pairIndex - Pair index
39
+ * @returns Price impact spread percentage
40
+ */
41
+ getPriceImpactSpread(positionSize: number, isLong: boolean, pairIndex: number): Promise<number>;
42
+ /**
43
+ * Get skew impact spread
44
+ * @param pairIndex - Pair index
45
+ * @returns Skew impact spread
46
+ */
47
+ getSkewImpactSpread(pairIndex: number): Promise<number>;
48
+ /**
49
+ * Get opening price impact spread for a trade
50
+ * @param tradeInput - Trade input parameters
51
+ * @returns Opening price impact spread
52
+ */
53
+ getOpeningPriceImpactSpread(tradeInput: TradeInput): Promise<number>;
54
+ /**
55
+ * Get one percent depth (liquidity depth)
56
+ * @returns Map of pair index to depth
57
+ */
58
+ getOnePercentDepth(): Promise<Map<number, {
59
+ above: number;
60
+ below: number;
61
+ }>>;
62
+ }
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AssetParametersRPC = void 0;
4
+ const types_1 = require("../types");
5
+ /**
6
+ * RPC module for retrieving asset-level parameters
7
+ */
8
+ class AssetParametersRPC {
9
+ constructor(provider, pairStorageContract, pairInfosContract, pairsCache, tradingStorageContract) {
10
+ this.provider = provider;
11
+ this.pairStorageContract = pairStorageContract;
12
+ this.pairInfosContract = pairInfosContract;
13
+ this.tradingStorageContract = tradingStorageContract;
14
+ this.pairsCache = pairsCache;
15
+ }
16
+ /**
17
+ * Get open interest limits for all pairs
18
+ * @returns Map of pair index to OI limits
19
+ */
20
+ async getOILimits() {
21
+ const pairs = await this.pairsCache.getPairsInfo();
22
+ const limits = new Map();
23
+ for (const [pairIndex, pairInfo] of pairs) {
24
+ limits.set(pairIndex, {
25
+ pairIndex,
26
+ maxLong: pairInfo.maxLongOiP,
27
+ maxShort: pairInfo.maxShortOiP,
28
+ });
29
+ }
30
+ return limits;
31
+ }
32
+ /**
33
+ * Get current open interest for all pairs
34
+ * @returns Map of pair index to OI
35
+ */
36
+ async getOI() {
37
+ const pairs = await this.pairsCache.getPairsInfo();
38
+ const oi = new Map();
39
+ for (const [pairIndex] of pairs) {
40
+ try {
41
+ // Use TradingStorage contract which has openInterestUSDC method
42
+ const pairOILong = await this.tradingStorageContract.openInterestUSDC(pairIndex, 0); // 0 = long
43
+ const pairOIShort = await this.tradingStorageContract.openInterestUSDC(pairIndex, 1); // 1 = short
44
+ const limits = await this.getOILimits();
45
+ const maxOI = limits.get(pairIndex)?.maxLong || 0;
46
+ oi.set(pairIndex, {
47
+ long: (0, types_1.fromBlockchain6)(pairOILong),
48
+ short: (0, types_1.fromBlockchain6)(pairOIShort),
49
+ max: maxOI,
50
+ });
51
+ }
52
+ catch (error) {
53
+ console.error(`Error getting OI for pair ${pairIndex}:`, error);
54
+ // Set default values on error
55
+ oi.set(pairIndex, {
56
+ long: 0,
57
+ short: 0,
58
+ max: 0,
59
+ });
60
+ }
61
+ }
62
+ return oi;
63
+ }
64
+ /**
65
+ * Get utilization for all pairs
66
+ * @returns Map of pair index to utilization
67
+ */
68
+ async getUtilization() {
69
+ const oi = await this.getOI();
70
+ const utilization = new Map();
71
+ for (const [pairIndex, oiData] of oi) {
72
+ const utilizationLong = oiData.max > 0 ? (oiData.long / oiData.max) * 100 : 0;
73
+ const utilizationShort = oiData.max > 0 ? (oiData.short / oiData.max) * 100 : 0;
74
+ utilization.set(pairIndex, {
75
+ utilizationLong,
76
+ utilizationShort,
77
+ });
78
+ }
79
+ return utilization;
80
+ }
81
+ /**
82
+ * Get asset skew (long / total) for all pairs
83
+ * @returns Map of pair index to skew
84
+ */
85
+ async getAssetSkew() {
86
+ const oi = await this.getOI();
87
+ const skew = new Map();
88
+ for (const [pairIndex, oiData] of oi) {
89
+ const total = oiData.long + oiData.short;
90
+ const skewValue = total > 0 ? oiData.long / total : 0.5;
91
+ skew.set(pairIndex, { skew: skewValue });
92
+ }
93
+ return skew;
94
+ }
95
+ /**
96
+ * Get price impact spread for opening a position
97
+ * @param positionSize - Position size in USDC
98
+ * @param isLong - True for long, false for short
99
+ * @param pairIndex - Pair index
100
+ * @returns Price impact spread percentage
101
+ */
102
+ async getPriceImpactSpread(positionSize, isLong, pairIndex) {
103
+ try {
104
+ const result = await this.pairInfosContract.getPriceImpactP(pairIndex, isLong, BigInt(Math.floor(positionSize * 1e6)));
105
+ return (0, types_1.fromBlockchain10)(result);
106
+ }
107
+ catch (error) {
108
+ console.error('Error getting price impact spread:', error);
109
+ return 0;
110
+ }
111
+ }
112
+ /**
113
+ * Get skew impact spread
114
+ * @param pairIndex - Pair index
115
+ * @returns Skew impact spread
116
+ */
117
+ async getSkewImpactSpread(pairIndex) {
118
+ try {
119
+ const skewMap = await this.getAssetSkew();
120
+ const skew = skewMap.get(pairIndex);
121
+ if (!skew)
122
+ return 0;
123
+ // Simple skew impact calculation (can be customized)
124
+ const deviation = Math.abs(skew.skew - 0.5);
125
+ return deviation * 100; // Convert to basis points
126
+ }
127
+ catch (error) {
128
+ console.error('Error getting skew impact spread:', error);
129
+ return 0;
130
+ }
131
+ }
132
+ /**
133
+ * Get opening price impact spread for a trade
134
+ * @param tradeInput - Trade input parameters
135
+ * @returns Opening price impact spread
136
+ */
137
+ async getOpeningPriceImpactSpread(tradeInput) {
138
+ const pairIndex = await this.pairsCache.getPairIndex(tradeInput.pair);
139
+ if (pairIndex === undefined) {
140
+ throw new Error(`Pair ${tradeInput.pair} not found`);
141
+ }
142
+ const positionSize = tradeInput.collateralInTrade * tradeInput.leverage;
143
+ return await this.getPriceImpactSpread(positionSize, tradeInput.isLong, pairIndex);
144
+ }
145
+ /**
146
+ * Get one percent depth (liquidity depth)
147
+ * @returns Map of pair index to depth
148
+ */
149
+ async getOnePercentDepth() {
150
+ const pairs = await this.pairsCache.getPairsInfo();
151
+ const depth = new Map();
152
+ for (const [pairIndex] of pairs) {
153
+ try {
154
+ const depthAbove = await this.pairInfosContract.onePercentDepthAboveUsdc(pairIndex);
155
+ const depthBelow = await this.pairInfosContract.onePercentDepthBelowUsdc(pairIndex);
156
+ depth.set(pairIndex, {
157
+ above: (0, types_1.fromBlockchain6)(depthAbove),
158
+ below: (0, types_1.fromBlockchain6)(depthBelow),
159
+ });
160
+ }
161
+ catch (error) {
162
+ // If method doesn't exist, set default values
163
+ depth.set(pairIndex, { above: 0, below: 0 });
164
+ }
165
+ }
166
+ return depth;
167
+ }
168
+ }
169
+ exports.AssetParametersRPC = AssetParametersRPC;