@d8x/perpetuals-sdk 0.6.4 → 0.6.5

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 (48) hide show
  1. package/dist/cjs/version.d.ts +1 -1
  2. package/dist/cjs/version.js +1 -1
  3. package/dist/esm/version.d.ts +1 -1
  4. package/dist/esm/version.js +1 -1
  5. package/package.json +2 -1
  6. package/src/abi/ERC20.json +288 -0
  7. package/src/abi/IPerpetualManager.json +5888 -0
  8. package/src/abi/LimitOrderBook.json +1062 -0
  9. package/src/abi/LimitOrderBookFactory.json +161 -0
  10. package/src/abi/MockTokenSwap.json +186 -0
  11. package/src/abi/ShareToken.json +428 -0
  12. package/src/accountTrade.ts +428 -0
  13. package/src/brokerTool.ts +555 -0
  14. package/src/config/defaultConfig.json +62 -0
  15. package/src/config/mockSwap.json +6 -0
  16. package/src/config/priceFeedConfig.json +104 -0
  17. package/src/config/symbolList.json +13 -0
  18. package/src/contracts/ERC20.ts +444 -0
  19. package/src/contracts/IPerpetualManager.ts +7227 -0
  20. package/src/contracts/LimitOrderBook.ts +1251 -0
  21. package/src/contracts/LimitOrderBookFactory.ts +348 -0
  22. package/src/contracts/MockTokenSwap.ts +373 -0
  23. package/src/contracts/ShareToken.ts +695 -0
  24. package/src/contracts/common.ts +44 -0
  25. package/src/contracts/factories/ERC20__factory.ts +306 -0
  26. package/src/contracts/factories/IPerpetualManager__factory.ts +5912 -0
  27. package/src/contracts/factories/LimitOrderBookFactory__factory.ts +189 -0
  28. package/src/contracts/factories/LimitOrderBook__factory.ts +1086 -0
  29. package/src/contracts/factories/MockTokenSwap__factory.ts +207 -0
  30. package/src/contracts/factories/ShareToken__factory.ts +449 -0
  31. package/src/contracts/factories/index.ts +9 -0
  32. package/src/contracts/index.ts +16 -0
  33. package/src/d8XMath.ts +376 -0
  34. package/src/index.ts +29 -0
  35. package/src/liquidatorTool.ts +270 -0
  36. package/src/liquidityProviderTool.ts +148 -0
  37. package/src/marketData.ts +1310 -0
  38. package/src/nodeSDKTypes.ts +332 -0
  39. package/src/orderReferrerTool.ts +516 -0
  40. package/src/perpetualDataHandler.ts +1161 -0
  41. package/src/perpetualEventHandler.ts +455 -0
  42. package/src/priceFeeds.ts +382 -0
  43. package/src/traderDigests.ts +86 -0
  44. package/src/traderInterface.ts +172 -0
  45. package/src/triangulator.ts +105 -0
  46. package/src/utils.ts +134 -0
  47. package/src/version.ts +1 -0
  48. package/src/writeAccessHandler.ts +139 -0
@@ -0,0 +1,332 @@
1
+ import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
2
+ import { BytesLike } from "@ethersproject/bytes";
3
+ import { AddressZero, HashZero } from "@ethersproject/constants";
4
+ import { ContractInterface, ContractTransaction } from "@ethersproject/contracts";
5
+
6
+ export const ERC20_ABI = require("./abi/ERC20.json");
7
+ export const MOCK_TOKEN_SWAP_ABI = require("./abi/MockTokenSwap.json");
8
+ export const SYMBOL_LIST = new Map<string, string>(Object.entries(require(`./config/symbolList.json`)));
9
+ export const COLLATERAL_CURRENCY_QUOTE = 0;
10
+ export const COLLATERAL_CURRENCY_BASE = 1;
11
+ export const COLLATERAL_CURRENCY_QUANTO = 2;
12
+ export const PERP_STATE_STR = ["INVALID", "INITIALIZING", "NORMAL", "EMERGENCY", "CLEARED"];
13
+ export const ZERO_ADDRESS = AddressZero;
14
+ export const ZERO_ORDER_ID = HashZero;
15
+
16
+ export const ONE_64x64 = BigNumber.from("0x010000000000000000");
17
+ export const MAX_64x64 = BigNumber.from("0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
18
+ export const MAX_UINT_256 = BigNumber.from(2).pow(256).sub(BigNumber.from(1));
19
+ export const DECIMALS = BigNumber.from(10).pow(BigNumber.from(18));
20
+
21
+ export const ORDER_MAX_DURATION_SEC = 60 * 60 * 24 * 30 * 4;
22
+
23
+ export const MASK_CLOSE_ONLY = BigNumber.from("0x80000000");
24
+ export const MASK_LIMIT_ORDER = BigNumber.from("0x04000000");
25
+ export const MASK_MARKET_ORDER = BigNumber.from("0x40000000");
26
+ export const MASK_STOP_ORDER = BigNumber.from("0x20000000");
27
+ export const MASK_KEEP_POS_LEVERAGE = BigNumber.from("0x08000000");
28
+
29
+ export const ORDER_TYPE_LIMIT = "LIMIT";
30
+ export const ORDER_TYPE_MARKET = "MARKET";
31
+ export const ORDER_TYPE_STOP_MARKET = "STOP_MARKET";
32
+ export const ORDER_TYPE_STOP_LIMIT = "STOP_LIMIT";
33
+ export const BUY_SIDE = "BUY";
34
+ export const SELL_SIDE = "SELL";
35
+ export const CLOSED_SIDE = "CLOSED";
36
+ export interface NodeSDKConfig {
37
+ name: string | undefined;
38
+ chainId: number;
39
+ version: number;
40
+ nodeURL: string;
41
+ proxyAddr: string;
42
+ proxyABILocation: string;
43
+ shareTokenABILocation: string;
44
+ limitOrderBookABILocation: string;
45
+ limitOrderBookFactoryABILocation: string;
46
+ symbolListLocation: string;
47
+ priceFeedConfigNetwork: string;
48
+ gasLimit?: number | undefined;
49
+ proxyABI?: ContractInterface | undefined;
50
+ lobFactoryABI?: ContractInterface | undefined;
51
+ lobABI?: ContractInterface | undefined;
52
+ shareTokenABI?: ContractInterface | undefined;
53
+ }
54
+
55
+ export interface MarginAccount {
56
+ symbol: string;
57
+ positionNotionalBaseCCY: number;
58
+ side: string;
59
+ entryPrice: number;
60
+ leverage: number;
61
+ markPrice: number;
62
+ unrealizedPnlQuoteCCY: number;
63
+ unrealizedFundingCollateralCCY: number;
64
+ collateralCC: number;
65
+ liquidationPrice: [number, number | undefined];
66
+ liquidationLvg: number;
67
+ collToQuoteConversion: number;
68
+ }
69
+
70
+ export enum CollaterlCCY {
71
+ QUOTE = 0,
72
+ BASE,
73
+ QUANTO,
74
+ }
75
+
76
+ export interface PoolStaticInfo {
77
+ poolId: number;
78
+ poolMarginSymbol: string;
79
+ poolMarginTokenAddr: string;
80
+ shareTokenAddr: string;
81
+ oracleFactoryAddr: string;
82
+ isRunning: boolean;
83
+ }
84
+
85
+ export interface PerpetualStaticInfo {
86
+ id: number;
87
+ poolId: number;
88
+ limitOrderBookAddr: string;
89
+ initialMarginRate: number;
90
+ maintenanceMarginRate: number;
91
+ collateralCurrencyType: CollaterlCCY;
92
+ S2Symbol: string;
93
+ S3Symbol: string;
94
+ lotSizeBC: number;
95
+ referralRebate: number;
96
+ priceIds: string[];
97
+ }
98
+
99
+ /*
100
+ PerpetualStaticInfo {
101
+ uint24 id;
102
+ address limitOrderBookAddr;
103
+ int128 fInitialMarginRate;
104
+ int128 fMaintenanceMarginRate;
105
+ uint8 perpetualState;
106
+ AMMPerpLogic.CollateralCurrency collCurrencyType;
107
+ bytes4 S2BaseCCY; //base currency of S2
108
+ bytes4 S2QuoteCCY; //quote currency of S2
109
+ bytes4 S3BaseCCY; //base currency of S3
110
+ bytes4 S3QuoteCCY; //quote currency of S3
111
+ int128 fLotSizeBC;
112
+ int128 fReferralRebateCC;
113
+ bytes32[] priceIds;
114
+ bool[] isPyth;
115
+ }
116
+ */
117
+
118
+ /**
119
+ * @global
120
+ * @typedef {Object} ExchangeInfo
121
+ * @property {PoolState[]} pools Array of state objects for all pools in the exchange.
122
+ * @property {string} oracleFactoryAddr Address of the oracle factory used by the pools in the exchange.
123
+ */
124
+ export interface ExchangeInfo {
125
+ pools: PoolState[];
126
+ oracleFactoryAddr: string;
127
+ proxyAddr: string;
128
+ }
129
+
130
+ /**
131
+ * @global
132
+ * @typedef {Object} PoolState
133
+ * @property {boolean} isRunning True if the pool is running.
134
+ * @property {string} marginTokenAddr Address of the token used by the pool.
135
+ * This is the token used for margin deposits, liquidity provision, and trading fees.
136
+ * @property {string} poolShareTokenAddr Address of the pool share token.
137
+ * This is the token issued to external liquidity providers.
138
+ * @property {number} defaultFundCashCC Amount of cash in the default fund of this pool, denominated in margin tokens.
139
+ * @property {number} pnlParticipantCashCC Amount of cash in the PnL participation pool, i.e. cash deposited by external liquidity providers.
140
+ * @property {number} totalAMMFundCashCC Amount of cash aggregated across all perpetual AMM funds in this pool.
141
+ * @property {number} totalTargetAMMFundSizeCC Target AMM funds aggregated across all perpetuals in this pool.
142
+ * @property {number} brokerCollateralLotSize Price of one lot for brokers who wish to participate in this pool. Denominated in margin tokens.
143
+ * @property {PerpetualState[]} perpetuals Array of all perpetuals in this pool.
144
+ */
145
+ export interface PoolState {
146
+ isRunning: boolean;
147
+ poolSymbol: string;
148
+ marginTokenAddr: string;
149
+ poolShareTokenAddr: string;
150
+ defaultFundCashCC: number;
151
+ pnlParticipantCashCC: number;
152
+ totalAMMFundCashCC: number;
153
+ totalTargetAMMFundSizeCC: number;
154
+ brokerCollateralLotSize: number;
155
+ perpetuals: PerpetualState[];
156
+ }
157
+
158
+ export interface PerpetualState {
159
+ id: number;
160
+ state: string;
161
+ baseCurrency: string;
162
+ quoteCurrency: string;
163
+ indexPrice: number;
164
+ collToQuoteIndexPrice: number;
165
+ markPrice: number;
166
+ midPrice: number;
167
+ currentFundingRateBps: number;
168
+ openInterestBC: number;
169
+ isMarketClosed: boolean;
170
+ }
171
+
172
+ export interface OrderResponse {
173
+ tx: ContractTransaction;
174
+ orderId: string;
175
+ }
176
+
177
+ export interface OrderStruct {
178
+ orders: Order[];
179
+ orderIds: string[];
180
+ }
181
+
182
+ export interface Order {
183
+ symbol: string; //symbol of the form ETH-USD-MATIC
184
+ side: string;
185
+ type: string;
186
+ quantity: number;
187
+ reduceOnly?: boolean | undefined;
188
+ limitPrice?: number | undefined;
189
+ keepPositionLvg?: boolean | undefined;
190
+ brokerFeeTbps?: number | undefined;
191
+ brokerAddr?: string | undefined;
192
+ brokerSignature?: BytesLike | undefined;
193
+ stopPrice?: number | undefined;
194
+ leverage?: number | undefined;
195
+ deadline?: number | undefined;
196
+ executionTimestamp: number;
197
+ submittedTimestamp?: number;
198
+ parentChildOrderIds?: [string, string];
199
+ }
200
+
201
+ export interface TradeEvent {
202
+ perpetualId: number;
203
+ positionId: string;
204
+ orderId: string;
205
+ newPositionSizeBC: number;
206
+ executionPrice: number;
207
+ }
208
+
209
+ /**
210
+ * struct Order {
211
+ uint16 leverageTDR; // 12.43x leverage is represented by 1243 (two-digit integer representation); 0 if deposit and trade separate
212
+ uint16 brokerFeeTbps; // broker can set their own fee
213
+ uint24 iPerpetualId; // global id for perpetual
214
+ address traderAddr; // address of trader
215
+ uint32 executionTimestamp; // normally set to current timestamp; order will not be executed prior to this timestamp.
216
+ address brokerAddr; // address of the broker or zero
217
+ uint32 submittedTimestamp;
218
+ uint32 flags; // order flags
219
+ uint32 iDeadline; //deadline for price (seconds timestamp)
220
+ address referrerAddr; // address of the referrer set by contract
221
+ int128 fAmount; // amount in base currency to be traded
222
+ int128 fLimitPrice; // limit price
223
+ int128 fTriggerPrice; //trigger price. Non-zero for stop orders.
224
+ bytes brokerSignature; //signature of broker (or 0)
225
+ }
226
+ */
227
+ export interface SmartContractOrder {
228
+ flags: BigNumberish;
229
+ iPerpetualId: number;
230
+ brokerFeeTbps: number;
231
+ traderAddr: string;
232
+ brokerAddr: string;
233
+ referrerAddr: string;
234
+ brokerSignature: BytesLike;
235
+ fAmount: BigNumberish;
236
+ fLimitPrice: BigNumberish;
237
+ fTriggerPrice: BigNumberish;
238
+ leverageTDR: number;
239
+ iDeadline: number;
240
+ executionTimestamp: number;
241
+ submittedTimestamp: number;
242
+ }
243
+
244
+ /**
245
+ * struct ClientOrder {
246
+ uint24 iPerpetualId; // unique id of the perpetual
247
+ int128 fLimitPrice; // order will not execute if realized price is above (buy) or below (sell) this price
248
+ uint16 leverageTDR; // leverage, set to 0 if deposit margin and trade separate; format: two-digit integer (e.g., 12.34 -> 1234)
249
+ uint32 executionTimestamp; // the order will not be executed before this timestamp, allows TWAP orders
250
+ uint32 flags; // Order-flags are specified in OrderFlags.sol
251
+ uint32 iDeadline; // order will not be executed after this deadline
252
+ address brokerAddr; // can be empty, address of the broker
253
+ int128 fTriggerPrice; // trigger price for stop-orders|0. Order can be executed if the mark price is below this price (sell order) or above (buy)
254
+ int128 fAmount; // signed amount of base-currency. Will be rounded to lot size
255
+ bytes32 parentChildDigest1; // see notice in LimitOrderBook.sol
256
+ address traderAddr; // address of the trader
257
+ bytes32 parentChildDigest2; // see notice in LimitOrderBook.sol
258
+ uint16 brokerFeeTbps; // broker fee in tenth of a basis point
259
+ bytes brokerSignature; // signature, can be empty if no brokerAddr provided
260
+ //address referrerAddr; <- will be set by LimitOrderBook
261
+ //uint64 submittedBlock <- will be set by LimitOrderBook
262
+ }
263
+ */
264
+ export interface ClientOrder {
265
+ flags: BigNumberish;
266
+ iPerpetualId: BigNumberish;
267
+ brokerFeeTbps: BigNumberish;
268
+ traderAddr: string;
269
+ brokerAddr: string;
270
+ referrerAddr: string;
271
+ brokerSignature: BytesLike;
272
+ fAmount: BigNumberish;
273
+ fLimitPrice: BigNumberish;
274
+ fTriggerPrice: BigNumberish;
275
+ leverageTDR: BigNumberish;
276
+ iDeadline: BigNumberish;
277
+ executionTimestamp: BigNumberish;
278
+ parentChildDigest1: string;
279
+ parentChildDigest2: string;
280
+ }
281
+
282
+ export interface PriceFeedConfig {
283
+ network: string;
284
+ ids: Array<{ symbol: string; id: string; type: string; origin: string }>;
285
+ endpoints: Array<{ type: string; endpoint: string }>;
286
+ }
287
+
288
+ export interface PriceFeedSubmission {
289
+ symbols: string[];
290
+ priceFeedVaas: string[];
291
+ prices: number[];
292
+ isMarketClosed: boolean[];
293
+ timestamps: number[];
294
+ }
295
+
296
+ export interface PriceFeedFormat {
297
+ conf: BigNumber;
298
+ expo: number;
299
+ price: BigNumber;
300
+ publish_time: number;
301
+ }
302
+
303
+ export interface PythLatestPriceFeed {
304
+ ema_price: {
305
+ conf: string;
306
+ expo: number;
307
+ price: string;
308
+ publish_time: number;
309
+ };
310
+ id: string;
311
+ price: PriceFeedFormat;
312
+ vaa: string;
313
+ }
314
+
315
+ export const DEFAULT_CONFIG_MAINNET_NAME = "mainnet";
316
+ export const DEFAULT_CONFIG_TESTNET_NAME = "testnet";
317
+
318
+ export function loadABIs(config: NodeSDKConfig) {
319
+ if (config.proxyABILocation.length > 0) {
320
+ config.proxyABI = require(`./abi/${config.proxyABILocation}`);
321
+ config.lobFactoryABI = require(`./abi/${config.limitOrderBookFactoryABILocation}`);
322
+ config.lobABI = require(`./abi/${config.limitOrderBookABILocation}`);
323
+ config.shareTokenABI = require(`./abi/${config.shareTokenABILocation}`);
324
+ }
325
+ }
326
+
327
+ let constConfig = require("./config/defaultConfig.json") as NodeSDKConfig[];
328
+ for (let config of constConfig) {
329
+ loadABIs(config);
330
+ }
331
+
332
+ export const DEFAULT_CONFIG: NodeSDKConfig[] = constConfig;