-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathperps.test.ts
More file actions
381 lines (329 loc) · 10.9 KB
/
Copy pathperps.test.ts
File metadata and controls
381 lines (329 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import type {
DecimalString,
PerpsInstrument,
PerpsOrderId,
PerpsSession,
TxHash,
} from '@polymarket/client';
import {
OrderSide,
PerpsTimeInForce,
RequestRejectedError,
} from '@polymarket/client';
import { expectNonEmptyArray } from '@polymarket/types';
import { vi } from 'vitest';
import {
describe,
expect,
it,
publicClient,
runMeteredTests,
} from './fixtures';
const DEFAULT_PERPS_CREDENTIAL_EXPIRES_IN = 7 * 24 * 60 * 60 * 1000;
const MAX_PERPS_PRICE_SIGNIFICANT_FIGURES = 5;
const MAX_SERVER_CLOCK_SKEW_MS = 60_000;
const [instrument] = await publicClient
.fetchPerpsInstruments()
.then(expectNonEmptyArray);
const [ticker] = await publicClient
.fetchPerpsTickers({ instrumentId: instrument.id })
.then(expectNonEmptyArray);
describe('Perps integration', () => {
it('fetches the Perps server time in epoch milliseconds', async ({
publicClient,
}) => {
const startedAt = Date.now();
const serverTime = await publicClient.getServerTime();
const completedAt = Date.now();
expect(serverTime).toBeGreaterThanOrEqual(
startedAt - MAX_SERVER_CLOCK_SKEW_MS,
);
expect(serverTime).toBeLessThanOrEqual(
completedAt + MAX_SERVER_CLOCK_SKEW_MS,
);
});
it.runIf(runMeteredTests)(
'deposits and withdraws the same Perps amount',
async ({ secureClientWithDepositWallet }) => {
const approval = await secureClientWithDepositWallet.approveErc20({
amount: 'max',
spenderAddress:
secureClientWithDepositWallet.environment.contracts
.perpsDepositContract,
tokenAddress:
secureClientWithDepositWallet.environment.contracts.collateralToken,
});
await approval.wait();
const deposit = await secureClientWithDepositWallet.depositToPerps({
amount: 10_000_000n,
});
const depositOutcome = await deposit.wait();
expect(depositOutcome.transactionHash).toMatch(/^0x[0-9a-f]{64}$/i);
const session = await secureClientWithDepositWallet.openPerpsSession({
expiresIn: 30 * 60_000,
});
try {
await waitForConfirmedDeposit(
session,
depositOutcome.transactionHash,
'10',
);
const withdrawalId =
await secureClientWithDepositWallet.withdrawFromPerps({
amount: 10_000_000n,
});
expect(withdrawalId).toEqual(expect.any(Number));
} finally {
await session.close();
}
},
6 * 60_000,
);
it.runIf(runMeteredTests)(
'creates delegated Perps credentials with the default expiry',
async ({ secureClientWithDepositWallet }) => {
const startedAt = Date.now();
const session = await secureClientWithDepositWallet.openPerpsSession();
expect(session.credentials.proxy).toMatch(/^0x[0-9a-f]{40}$/i);
expect(session.credentials.privateKey).toMatch(/^0x[0-9a-f]{64}$/i);
expect(session.credentials.secret).toEqual(expect.any(String));
expect(session.credentials.expiresAt).toBeGreaterThanOrEqual(
startedAt + DEFAULT_PERPS_CREDENTIAL_EXPIRES_IN,
);
expect(session.credentials.expiresAt).toBeLessThanOrEqual(
Date.now() + DEFAULT_PERPS_CREDENTIAL_EXPIRES_IN,
);
await session.close();
},
);
it.runIf(runMeteredTests)(
'places and cancels one Perps order',
async ({ secureClientWithDepositWallet }) => {
const session = await secureClientWithDepositWallet.openPerpsSession();
const price = formatPerpsPrice(
Number(ticker.markPrice) / 2, // ensure the order is not immediately filled
instrument.priceDecimals,
);
try {
const { order } = await session.placeOrder({
instrumentId: instrument.id,
price,
quantity: minimalPerpsOrderQuantity(instrument, Number(price)),
side: OrderSide.BUY,
timeInForce: PerpsTimeInForce.GTC,
});
const cancelResult = await session.cancelOrder({ orderId: order.id });
expect(cancelResult.status).toBe('ok');
} finally {
await session.close();
}
},
6 * 60_000,
);
it.runIf(runMeteredTests)(
'places and cancels all Perps orders for one instrument',
async ({ secureClientWithDepositWallet }) => {
const session = await secureClientWithDepositWallet.openPerpsSession();
const orderIds: PerpsOrderId[] = [];
try {
const price = formatPerpsPrice(
Number(ticker.markPrice) / 2,
instrument.priceDecimals,
);
const quantity = minimalPerpsOrderQuantity(instrument, Number(price));
for (let index = 0; index < 2; index++) {
const { order } = await session.placeOrder({
instrumentId: instrument.id,
price,
quantity,
side: OrderSide.BUY,
timeInForce: PerpsTimeInForce.GTC,
});
orderIds.push(order.id);
}
await session.cancelAllOrders({ instrumentId: instrument.id });
await vi.waitFor(
async () => {
const openOrderIds = (
await session.fetchOpenOrders({
instrumentId: instrument.id,
})
).map((order) => order.id);
for (const orderId of orderIds) {
expect(openOrderIds).not.toContain(orderId);
}
},
{ interval: 1_000, timeout: 30_000 },
);
} finally {
if (orderIds.length > 0) {
await session.cancelOrders({ orderIds }).catch(() => undefined);
}
await session.close();
}
},
6 * 60_000,
);
it.runIf(runMeteredTests)(
'places and cancels one Perps order with TP/SL',
async ({ secureClientWithDepositWallet }) => {
const session = await secureClientWithDepositWallet.openPerpsSession();
const markPrice = Number(ticker.markPrice);
const price = formatPerpsPrice(
markPrice / 2, // ensure the order is not immediately filled
instrument.priceDecimals,
);
try {
const result = await session.placeOrder({
instrumentId: instrument.id,
price,
quantity: minimalPerpsOrderQuantity(instrument, Number(price)),
side: OrderSide.BUY,
timeInForce: PerpsTimeInForce.GTC,
stopLoss: {
triggerPrice: formatPerpsPrice(
markPrice / 4,
instrument.priceDecimals,
),
},
takeProfit: {
triggerPrice: formatPerpsPrice(
markPrice * 2,
instrument.priceDecimals,
),
},
});
expect(result.tpSl.takeProfit?.orderId).toEqual(expect.any(Number));
expect(result.tpSl.stopLoss?.orderId).toEqual(expect.any(Number));
const cancelResult = await session.cancelOrder({
orderId: result.order.id,
});
expect(cancelResult.status).toBe('ok');
} finally {
await session.close();
}
},
6 * 60_000,
);
it.runIf(runMeteredTests)(
'arms, reads, and disarms the auto-cancel switch',
async ({ secureClientWithDepositWallet }) => {
const session = await secureClientWithDepositWallet.openPerpsSession();
try {
// Far enough out that the switch can never fire mid-suite.
const cancelAt = Date.now() + 10 * 60_000;
try {
await session.armAutoCancel({ cancelAt });
const armed = await session.fetchAutoCancelStatus();
expect(armed.deadline).toBe(cancelAt);
expect(armed.dailyLimit).toBeGreaterThan(0);
} finally {
await session.disarmAutoCancel();
}
const disarmed = await session.fetchAutoCancelStatus();
expect(disarmed.deadline).toBeNull();
} finally {
await session.close();
}
},
);
it.runIf(runMeteredTests)(
'resumes existing delegated Perps credentials',
async ({ secureClientWithDepositWallet }) => {
const initialSession =
await secureClientWithDepositWallet.openPerpsSession({
expiresIn: 30 * 60_000,
});
try {
const resumedSession =
await secureClientWithDepositWallet.openPerpsSession({
credentials: initialSession.credentials,
});
expect(resumedSession.credentials).toEqual(initialSession.credentials);
await resumedSession.close();
} finally {
await initialSession.close();
}
},
);
it.runIf(runMeteredTests)(
'revokes delegated Perps credentials',
async ({ secureClientWithDepositWallet }) => {
const session = await secureClientWithDepositWallet.openPerpsSession({
expiresIn: 30 * 60_000,
});
const credentials = session.credentials;
await session.close();
await secureClientWithDepositWallet.revokePerpsCredentials({
proxy: credentials.proxy,
});
await expect(
secureClientWithDepositWallet.openPerpsSession({ credentials }),
).rejects.toBeInstanceOf(RequestRejectedError);
},
);
it.runIf(runMeteredTests)(
'rejects delegated Perps credentials with an invalid secret',
async ({ secureClientWithDepositWallet }) => {
const session = await secureClientWithDepositWallet.openPerpsSession({
expiresIn: 30 * 60_000,
});
try {
await expect(
secureClientWithDepositWallet.openPerpsSession({
credentials: {
...session.credentials,
secret: 'invalid-secret',
},
}),
).rejects.toBeInstanceOf(RequestRejectedError);
} finally {
await session.close();
}
},
);
});
async function waitForConfirmedDeposit(
session: PerpsSession,
hash: TxHash,
amount: string,
): Promise<void> {
const startedAt = Date.now();
while (Date.now() - startedAt < 5 * 60_000) {
const page = await session.listDeposits({ hash }).firstPage();
const deposit = page.items.find((item) => item.hash === hash);
if (deposit?.status === 'confirmed') {
expect(deposit.amount).toBe(amount);
return;
}
await delay(5_000);
}
throw new Error(`Timed out waiting for Perps deposit ${hash} to confirm`);
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function formatPerpsPrice(price: number, priceDecimals: number): DecimalString {
const roundedPrice = Number(
price.toPrecision(MAX_PERPS_PRICE_SIGNIFICANT_FIGURES),
);
if (Number.isInteger(roundedPrice)) {
return roundedPrice.toFixed(0) as DecimalString;
}
return roundedPrice
.toFixed(priceDecimals)
.replace(/(\.\d*?)0+$/, '$1')
.replace(/\.$/, '') as DecimalString;
}
function minimalPerpsOrderQuantity(
instrument: PerpsInstrument,
price: number,
): DecimalString {
const quantity =
Math.ceil(
(Number(instrument.minNotional) / Number(price)) *
10 ** instrument.quantityDecimals,
) /
10 ** instrument.quantityDecimals;
return quantity.toFixed(instrument.quantityDecimals) as DecimalString;
}