-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathdepositWallet.test.ts
More file actions
432 lines (382 loc) · 12.3 KB
/
depositWallet.test.ts
File metadata and controls
432 lines (382 loc) · 12.3 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import { SignTypedDataVersion } from '@metamask/keyring-controller';
import type { Signer } from '../types';
import {
DEPOSIT_WALLET_FACTORY_ADDRESS,
deriveDepositWalletAddress,
executeDepositWalletBatch,
executeDepositWalletBatchAndWaitForCompletion,
getDepositWalletNonce,
requestDepositWalletCreate,
syncDepositWalletCollateralBalanceAllowance,
toDepositWalletCalls,
waitForDepositWalletDeployed,
waitForDepositWalletTransaction,
} from './depositWallet';
import { POLYMARKET_V2_PROTOCOL } from './protocol/definitions';
import { OperationType } from './safe/types';
import { getL2Headers } from './utils';
jest.mock('./utils', () => ({
getPolymarketEndpoints: jest.fn(() => ({
CLOB_RELAYER: 'https://predict.api.cx.metamask.io',
})),
getL2Headers: jest.fn(),
}));
const mockGetL2Headers = jest.mocked(getL2Headers);
const mockFetch = jest.fn();
type MockResponseBody = Record<string, unknown> | Record<string, unknown>[];
function mockResponse(body: MockResponseBody, ok = true): Response {
return {
ok,
status: ok ? 200 : 500,
text: jest.fn().mockResolvedValue(JSON.stringify(body)),
} as unknown as Response;
}
function getFetchBody(callIndex = 0): unknown {
return JSON.parse(String(mockFetch.mock.calls[callIndex][1]?.body));
}
const ownerAddress = '0x1111111111111111111111111111111111111111';
const signer: Signer = {
address: ownerAddress,
signTypedMessage: jest.fn().mockResolvedValue('0xsignature'),
signPersonalMessage: jest.fn(),
};
describe('depositWallet', () => {
beforeEach(() => {
jest.clearAllMocks();
global.fetch = mockFetch as unknown as typeof fetch;
mockGetL2Headers.mockResolvedValue({
POLY_ADDRESS: ownerAddress,
POLY_SIGNATURE: 'signature',
POLY_TIMESTAMP: '1',
POLY_API_KEY: 'api-key',
POLY_PASSPHRASE: 'passphrase',
});
});
it('derives the same address for checksum-equivalent owners', () => {
const lowerCaseAddress = ownerAddress.toLowerCase();
const checkSummedAddress = ownerAddress.toUpperCase().replace('0X', '0x');
const lowerResult = deriveDepositWalletAddress(lowerCaseAddress);
const checksumResult = deriveDepositWalletAddress(checkSummedAddress);
expect(lowerResult).toMatch(/^0x[a-fA-F0-9]{40}$/u);
expect(checksumResult).toBe(lowerResult);
});
it('maps Safe transactions to deposit-wallet calls', () => {
expect(
toDepositWalletCalls([
{
to: POLYMARKET_V2_PROTOCOL.collateral.tradingToken,
value: '0',
data: '0x1234',
operation: OperationType.Call,
},
]),
).toEqual([
{
target: POLYMARKET_V2_PROTOCOL.collateral.tradingToken,
value: '0',
data: '0x1234',
},
]);
});
it('requests wallet creation through the relayer proxy envelope', async () => {
mockFetch.mockResolvedValue(mockResponse({ transactionID: 'relayer-1' }));
const result = await requestDepositWalletCreate({ ownerAddress });
expect(result.transactionID).toBe('relayer-1');
expect(mockFetch).toHaveBeenCalledWith(
'https://predict.api.cx.metamask.io/transaction',
expect.objectContaining({ method: 'POST' }),
);
expect(getFetchBody()).toEqual({
path: '/submit',
method: 'POST',
body: {
type: 'WALLET-CREATE',
from: ownerAddress,
to: DEPOSIT_WALLET_FACTORY_ADDRESS,
},
});
});
it('reads wallet nonce through the relayer proxy envelope', async () => {
mockFetch.mockResolvedValue(mockResponse({ nonce: '7' }));
const nonce = await getDepositWalletNonce({ ownerAddress });
expect(nonce).toBe('7');
expect(getFetchBody()).toEqual({
path: '/nonce',
method: 'GET',
query: {
address: ownerAddress,
type: 'WALLET',
},
});
});
it('signs and submits wallet batches through the relayer proxy envelope', async () => {
const walletAddress = deriveDepositWalletAddress(ownerAddress);
const calls = [
{
target: POLYMARKET_V2_PROTOCOL.collateral.tradingToken,
value: '0',
data: '0x1234',
},
];
mockFetch
.mockResolvedValueOnce(mockResponse({ nonce: '9' }))
.mockResolvedValueOnce(mockResponse({ transactionID: 'relayer-2' }));
const result = await executeDepositWalletBatch({
signer,
walletAddress,
calls,
});
expect(result.transactionID).toBe('relayer-2');
expect(signer.signTypedMessage).toHaveBeenCalledWith(
expect.objectContaining({
from: ownerAddress,
data: expect.objectContaining({
primaryType: 'Batch',
message: expect.objectContaining({
wallet: walletAddress,
nonce: '9',
calls,
}),
}),
}),
SignTypedDataVersion.V4,
);
expect(getFetchBody(1)).toEqual({
path: '/submit',
method: 'POST',
body: expect.objectContaining({
type: 'WALLET',
from: ownerAddress,
to: DEPOSIT_WALLET_FACTORY_ADDRESS,
nonce: '9',
signature: '0xsignature',
depositWalletParams: expect.objectContaining({
depositWallet: walletAddress,
calls,
}),
}),
});
});
it('polls by relayer id until wallet transaction hash is available', async () => {
mockFetch.mockResolvedValue(
mockResponse({
state: 'STATE_MINED',
transactionHash:
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
}),
);
const hash = await waitForDepositWalletTransaction({
transactionID: 'relayer-mined',
pollIntervalMs: 0,
});
expect(hash).toBe(
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
);
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(getFetchBody()).toEqual({
path: '/transaction',
method: 'GET',
query: { id: 'relayer-mined' },
});
});
it('returns hash before completion when completion is not required', async () => {
mockFetch.mockResolvedValue(
mockResponse({
state: 'STATE_NEW',
transactionHash:
'0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
}),
);
const hash = await waitForDepositWalletTransaction({
transactionID: 'relayer-hash',
pollIntervalMs: 0,
});
expect(hash).toBe(
'0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
);
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it('polls until wallet transaction is confirmed when completion is required', async () => {
mockFetch
.mockResolvedValueOnce(
mockResponse({
state: 'STATE_NEW',
transactionHash:
'0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',
}),
)
.mockResolvedValueOnce(
mockResponse({
state: 'STATE_CONFIRMED',
transactionHash:
'0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',
}),
);
const hash = await waitForDepositWalletTransaction({
transactionID: 'relayer-3',
requireCompletion: true,
pollIntervalMs: 0,
});
expect(hash).toBe(
'0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',
);
expect(mockFetch).toHaveBeenCalledTimes(2);
});
it.each(['STATE_FAILED', 'STATE_INVALID'])(
'throws when wallet transaction polling reaches %s',
async (state) => {
mockFetch.mockResolvedValue(mockResponse({ state }));
await expect(
waitForDepositWalletTransaction({
transactionID: 'relayer-4',
pollIntervalMs: 0,
}),
).rejects.toThrow(state);
},
);
it('keeps polling when completion succeeds without a hash', async () => {
mockFetch
.mockResolvedValueOnce(mockResponse({ state: 'STATE_CONFIRMED' }))
.mockResolvedValueOnce(
mockResponse({
state: 'STATE_CONFIRMED',
transactionHash:
'0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',
}),
);
const hash = await waitForDepositWalletTransaction({
transactionID: 'relayer-no-hash-yet',
requireCompletion: true,
pollIntervalMs: 0,
});
expect(hash).toBe(
'0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',
);
expect(mockFetch).toHaveBeenCalledTimes(2);
});
it('throws when wallet transaction polling times out', async () => {
mockFetch.mockResolvedValue(mockResponse({ state: 'STATE_NEW' }));
await expect(
waitForDepositWalletTransaction({
transactionID: 'relayer-timeout',
maxPolls: 2,
pollIntervalMs: 0,
}),
).rejects.toThrow('Timed out');
});
it('executes a wallet batch and waits for relayer completion', async () => {
const walletAddress = deriveDepositWalletAddress(ownerAddress);
const calls = [
{
target: POLYMARKET_V2_PROTOCOL.collateral.tradingToken,
value: '0',
data: '0x1234',
},
];
mockFetch
.mockResolvedValueOnce(mockResponse({ nonce: '11' }))
.mockResolvedValueOnce(mockResponse({ transactionID: 'relayer-5' }))
.mockResolvedValueOnce(
mockResponse({
state: 'STATE_CONFIRMED',
transactionHash:
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
}),
);
const hash = await executeDepositWalletBatchAndWaitForCompletion({
signer,
walletAddress,
calls,
});
expect(hash).toBe(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
);
expect(getFetchBody(2)).toEqual({
path: '/transaction',
method: 'GET',
query: { id: 'relayer-5' },
});
});
it('throws when completed wallet batch response is missing transactionID', async () => {
const walletAddress = deriveDepositWalletAddress(ownerAddress);
const calls = [
{
target: POLYMARKET_V2_PROTOCOL.collateral.tradingToken,
value: '0',
data: '0x1234',
},
];
mockFetch
.mockResolvedValueOnce(mockResponse({ nonce: '12' }))
.mockResolvedValueOnce(mockResponse({}));
await expect(
executeDepositWalletBatchAndWaitForCompletion({
signer,
walletAddress,
calls,
}),
).rejects.toThrow('missing transactionID');
});
it('polls relayer deployment status through the MetaMask proxy until the wallet is registered', async () => {
const walletAddress = deriveDepositWalletAddress(ownerAddress);
mockFetch
.mockResolvedValueOnce(mockResponse({ deployed: false }))
.mockResolvedValueOnce(mockResponse({ deployed: true }));
await waitForDepositWalletDeployed({
walletAddress,
pollIntervalMs: 0,
});
expect(mockFetch).toHaveBeenCalledTimes(2);
expect(mockFetch).toHaveBeenCalledWith(
'https://predict.api.cx.metamask.io/transaction',
expect.objectContaining({ method: 'POST' }),
);
expect(getFetchBody()).toEqual({
path: '/deployed',
method: 'GET',
query: {
address: walletAddress,
type: 'WALLET',
},
});
});
it('throws when relayer deployment status times out', async () => {
const walletAddress = deriveDepositWalletAddress(ownerAddress);
mockFetch.mockResolvedValue(mockResponse({ deployed: false }));
await expect(
waitForDepositWalletDeployed({
walletAddress,
maxPolls: 2,
pollIntervalMs: 0,
}),
).rejects.toThrow('Timed out');
});
it('syncs collateral balance allowance through direct CLOB endpoint', async () => {
mockFetch.mockResolvedValue(mockResponse({ ok: true }));
await syncDepositWalletCollateralBalanceAllowance({
protocol: POLYMARKET_V2_PROTOCOL,
signerAddress: ownerAddress,
apiKey: {
apiKey: 'api-key',
secret: 'secret',
passphrase: 'passphrase',
},
});
expect(mockGetL2Headers).toHaveBeenCalledWith({
l2HeaderArgs: {
method: 'GET',
requestPath: '/balance-allowance/update',
},
address: ownerAddress,
apiKey: {
apiKey: 'api-key',
secret: 'secret',
passphrase: 'passphrase',
},
});
expect(mockFetch).toHaveBeenCalledWith(
'https://clob.polymarket.com/balance-allowance/update?asset_type=COLLATERAL&signature_type=3',
expect.objectContaining({ method: 'GET' }),
);
});
});