-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathpolymarket-mocks.ts
More file actions
2240 lines (2068 loc) · 80.4 KB
/
polymarket-mocks.ts
File metadata and controls
2240 lines (2068 loc) · 80.4 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* File containing mock functionality for all Polymarket API endpoints
*/
import { Mockttp } from 'mockttp';
import { setupMockRequest } from '../../helpers/mockHelpers.ts';
import { safeGetBodyText } from '../../MockServerE2E.ts';
import {
POLYMARKET_CURRENT_POSITIONS_RESPONSE,
POLYMARKET_RESOLVED_LOST_POSITIONS_RESPONSE,
POLYMARKET_WINNING_POSITIONS_RESPONSE,
POLYMARKET_NEW_OPEN_POSITION_CELTICS_NETS_RESPONSE,
} from './polymarket-positions-response.ts';
import {
POLYMARKET_EVENT_DETAILS_BLUE_JAYS_MARINERS_RESPONSE,
POLYMARKET_EVENT_DETAILS_SPURS_PELICANS_RESPONSE,
POLYMARKET_EVENT_DETAILS_CELTICS_NETS_RESPONSE,
POLYMARKET_EVENT_DETAILS_COWBOYS_COMMANDERS_RESPONSE,
} from './polymarket-event-details-response.ts';
import { POLYMARKET_UPNL_RESPONSE } from './polymarket-upnl-response.ts';
import {
POLYMARKET_ACTIVITY_RESPONSE,
POLYMARKET_CLAIMED_POSITIONS_ACTIVITY_RESPONSE,
POLYMARKET_OPENED_POSITION_ACTIVITY_RESPONSE,
} from './polymarket-activity-response.ts';
import {
POLYMARKET_ORDER_BOOK_RESPONSE,
POLYMARKET_ZOHRAN_ORDER_BOOK_RESPONSE,
POLYMARKET_CHIEFS_ORDER_BOOK_RESPONSE,
POLYMARKET_CUOMO_ORDER_BOOK_RESPONSE,
POLYMARKET_BILLS_ORDER_BOOK_RESPONSE,
POLYMARKET_SPURS_ORDER_BOOK_RESPONSE,
POLYMARKET_PELICANS_ORDER_BOOK_RESPONSE,
POLYMARKET_CELTICS_ORDER_BOOK_RESPONSE,
} from './polymarket-order-book-response.ts';
import { POLYMARKET_SPORTS_FEED } from './market-feed-responses/polymarket-sports-feed.ts';
import { POLYMARKET_CRYPTO_FEED } from './market-feed-responses/polymarket-crypto-feed.ts';
import { POLYMARKET_POLITICS_FEED } from './market-feed-responses/polymarket-politics-feed.ts';
import { POLYMARKET_TRENDING_FEED } from './market-feed-responses/polymarket-trending-feed.ts';
import { MOCK_RPC_RESPONSES } from './polymarket-rpc-response.ts';
import { POLYMARKET_NEW_FEED } from './market-feed-responses/polymarket-new-feed.ts';
import {
PROXY_WALLET_ADDRESS,
USER_WALLET_ADDRESS,
SAFE_FACTORY_ADDRESS,
USDC_CONTRACT_ADDRESS,
POLYGON_PUSD_TOKEN_ADDRESS,
MULTICALL_CONTRACT_ADDRESS,
CONDITIONAL_TOKENS_CONTRACT_ADDRESS,
POST_CASH_OUT_USDC_BALANCE_WEI,
POST_CLAIM_USDC_BALANCE_WEI,
POST_OPEN_POSITION_USDC_BALANCE_WEI,
POLYGON_EIP7702_CONTRACT_ADDRESS,
EIP7702_CODE_FORMAT,
} from './polymarket-constants.ts';
import { createTransactionSentinelResponse } from './polymarket-transaction-sentinel-response.ts';
import { GEO_BLOCKED_COUNTRIES } from '../../../../app/components/UI/Predict/constants/geoblock.ts';
import { POLYMARKET_GEOBLOCK_ELIGIBLE } from '../defaults/polymarket-apis.ts';
import { TX_SENTINEL_NETWORKS_MAP } from '../tx-sentinel-networks-map.ts';
/**
* Mock for Polymarket API returning 500 error
* This simulates the Polymarket API being down
*/
// Global variable to track current USDC balance
let currentUSDCBalance = MOCK_RPC_RESPONSES.USDC_BALANCE_RESULT;
// Global variable to track current block number (to invalidate NetworkController block cache)
let currentBlockNumber = 0x1000000; // Start at block 16777216
// Global Set to track when Celtics vs Nets orders have been submitted
const celticsOrderSubmitted = new Set<string>();
/**
* Resets all mutable global state to defaults.
* Must be called at the start of each test's mock setup (via POLYMARKET_COMPLETE_MOCKS)
* because all spec files in a Detox run share the same Jest worker process.
*/
function resetGlobalMockState() {
currentUSDCBalance = MOCK_RPC_RESPONSES.USDC_BALANCE_RESULT;
currentBlockNumber = 0x1000000;
celticsOrderSubmitted.clear();
}
/**
* Mock Priority System
* Higher numbers = checked first (higher priority)
*
* 999 - Base mocks (catch-all for all RPC calls, set up once in POLYMARKET_COMPLETE_MOCKS)
* 1000 - API overrides (position removal, CLOB API)
* 1005 - Balance refresh mocks for /proxy calls (claim, cash-out, withdraw)
* 1006 - Balance refresh mocks for withdraw flow (separate to avoid conflicts)
* 1007 - Balance refresh mocks for direct polygon-rpc.com calls (claim, cash-out)
*/
const PRIORITY = {
BASE: 999,
API_OVERRIDE: 1000,
HOMEPAGE_POSITIONS_OVERRIDE: 1010,
CLAIMABLE_POSITIONS_OVERRIDE: 1020,
BALANCE_REFRESH_PROXY: 1005,
BALANCE_REFRESH_WITHDRAW: 1006,
BALANCE_REFRESH_DIRECT: 1007,
} as const;
/**
* Parses the `redeemable` query parameter from a proxied Polymarket URL.
* Returns `true`, `false`, or `undefined` (when the param is absent).
* The app omits `redeemable` when fetching ALL positions at once.
*/
function parseRedeemableParam(requestUrl: string): boolean | undefined {
const proxiedUrl = new URL(requestUrl).searchParams.get('url');
if (!proxiedUrl) return undefined;
const url = new URL(proxiedUrl);
const value = url.searchParams.get('redeemable');
if (value === null) return undefined;
return value === 'true';
}
export const POLYMARKET_API_DOWN = async (mockServer: Mockttp) => {
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: /^https:\/\/gamma-api\.polymarket\.com\/events\/pagination/,
responseCode: 500,
response: {
error: 'Internal Server Error',
message: 'Service temporarily unavailable',
statusCode: 500,
},
});
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: /^https:\/\/gamma-api\.polymarket\.com\/events\/\d+/,
responseCode: 500,
response: {
error: 'Internal Server Error',
message: 'Service temporarily unavailable',
statusCode: 500,
},
});
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: /^https:\/\/clob\.polymarket\.com\/prices-history/,
responseCode: 500,
response: {
error: 'Internal Server Error',
message: 'Service temporarily unavailable',
statusCode: 500,
},
});
// Mock broader patterns last (less specific patterns)
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: /^https:\/\/gamma-api\.polymarket\.com/,
responseCode: 500,
response: {
error: 'Internal Server Error',
message: 'Service temporarily unavailable',
statusCode: 500,
},
});
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: /^https:\/\/clob\.polymarket\.com/,
responseCode: 500,
response: {
error: 'Internal Server Error',
message: 'Service temporarily unavailable',
statusCode: 500,
},
});
};
/**
* Mock for Polymarket geoblock endpoint
* This simulates the user being in a geo-restricted region
* Uses a country from GEO_BLOCKED_COUNTRIES for consistency with app logic
*/
export const POLYMARKET_GEO_BLOCKED_MOCKS = async (mockServer: Mockttp) => {
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: 'https://polymarket.com/api/geoblock',
responseCode: 200,
response: { blocked: true, country: GEO_BLOCKED_COUNTRIES[0].country },
});
};
/**
* Mock for Polymarket geoblock endpoint returning eligible region.
* Reuses POLYMARKET_GEOBLOCK_ELIGIBLE from defaults so there is a single source of truth.
*/
export const POLYMARKET_GEO_ELIGIBLE_MOCKS = async (mockServer: Mockttp) => {
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: POLYMARKET_GEOBLOCK_ELIGIBLE.urlEndpoint,
responseCode: POLYMARKET_GEOBLOCK_ELIGIBLE.responseCode,
response: POLYMARKET_GEOBLOCK_ELIGIBLE.response,
});
};
/**
* Mock for Polymarket event details API
* Returns event details based on the requested event ID
*/
export const POLYMARKET_EVENT_DETAILS_MOCKS = async (mockServer: Mockttp) => {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(url?.includes('gamma-api.polymarket.com/events/'));
})
.asPriority(PRIORITY.BASE)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const eventIdMatch = url?.match(/\/events\/([0-9]+)$/);
const eventId = eventIdMatch ? eventIdMatch[1] : '60362';
if (eventId === '62553') {
// Return Spurs vs Pelicans event details from mock response file
return {
statusCode: 200,
json: POLYMARKET_EVENT_DETAILS_SPURS_PELICANS_RESPONSE,
};
}
if (eventId === '79682') {
// Return Celtics vs Nets event details from mock response file
return {
statusCode: 200,
json: POLYMARKET_EVENT_DETAILS_CELTICS_NETS_RESPONSE,
};
}
if (eventId === '58319') {
// Return Celtics vs Nets event details from mock response file
return {
statusCode: 200,
json: POLYMARKET_EVENT_DETAILS_COWBOYS_COMMANDERS_RESPONSE,
};
}
// Default to Blue Jays vs Mariners for other event IDs
return {
statusCode: 200,
json: POLYMARKET_EVENT_DETAILS_BLUE_JAYS_MARINERS_RESPONSE,
};
});
};
/**
* Mock for Polymarket positions API with test user positions
* Returns positions data for user 0x5f7c8f3c8bedf5e7db63a34ef2f39322ca77fe72
*/
export const POLYMARKET_CURRENT_POSITIONS_MOCKS = async (
mockServer: Mockttp,
) => {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(
url &&
url.includes('data-api.polymarket.com/positions') &&
url.includes('user=0x') &&
!url.includes('redeemable=true'),
);
})
.asPriority(PRIORITY.BASE)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const redeemable = parseRedeemableParam(request.url);
const userMatch = url?.match(/user=(0x[a-fA-F0-9]{40})/);
const userAddress = userMatch ? userMatch[1] : USER_WALLET_ADDRESS;
// Check if eventId parameter is present for filtering
const eventIdMatch = url?.match(/eventId=([0-9]+)/);
const eventId = eventIdMatch ? eventIdMatch[1] : null;
// Filter positions by eventId if provided
const allPositions =
redeemable === undefined
? [
...POLYMARKET_CURRENT_POSITIONS_RESPONSE,
...POLYMARKET_RESOLVED_LOST_POSITIONS_RESPONSE,
]
: POLYMARKET_CURRENT_POSITIONS_RESPONSE;
let filteredPositions = allPositions;
if (eventId) {
filteredPositions = allPositions.filter(
(position) => position.eventId === eventId,
);
}
// Update the mock response with the actual user address
const dynamicResponse = filteredPositions.map((position) => ({
...position,
proxyWallet: userAddress,
}));
return {
statusCode: 200,
json: dynamicResponse,
};
});
};
/**
* Mock for Polymarket positions API with controllable winning positions
* Returns positions data for user with optional winning positions
* This mock will trigger the CLAIM button
* Winning positions (redeemable=true) should be in resolved markets, not current positions
*/
export const POLYMARKET_POSITIONS_WITH_WINNINGS_MOCKS = async (
mockServer: Mockttp,
includeWinnings: boolean = false,
options: { showWinningsAsActive?: boolean } = {},
) => {
const { showWinningsAsActive = false } = options;
const priority = showWinningsAsActive
? PRIORITY.HOMEPAGE_POSITIONS_OVERRIDE
: PRIORITY.API_OVERRIDE;
// Mock for positions (no redeemable or redeemable=false) - overrides POLYMARKET_CURRENT_POSITIONS_MOCKS
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(
url &&
url.includes('data-api.polymarket.com/positions') &&
url.includes('user=0x') &&
!url.includes('redeemable=true'),
);
})
.asPriority(priority)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const redeemable = parseRedeemableParam(request.url);
const userMatch = url?.match(/user=(0x[a-fA-F0-9]{40})/);
const userAddress = userMatch ? userMatch[1] : USER_WALLET_ADDRESS;
const eventIdMatch = url?.match(/eventId=([0-9]+)/);
const eventId = eventIdMatch ? eventIdMatch[1] : null;
let winnings = includeWinnings
? POLYMARKET_WINNING_POSITIONS_RESPONSE
: [];
if (showWinningsAsActive && winnings.length > 0) {
winnings = winnings.map((position) => ({
...position,
redeemable: false,
mergeable: false,
}));
}
const allPositions =
redeemable === undefined
? [
...POLYMARKET_CURRENT_POSITIONS_RESPONSE,
...POLYMARKET_RESOLVED_LOST_POSITIONS_RESPONSE,
...winnings,
]
: showWinningsAsActive
? [...POLYMARKET_CURRENT_POSITIONS_RESPONSE, ...winnings]
: POLYMARKET_CURRENT_POSITIONS_RESPONSE;
let filteredPositions = allPositions;
if (eventId) {
filteredPositions = allPositions.filter(
(position) => position.eventId === eventId,
);
}
const dynamicResponse = filteredPositions.map((position) => ({
...position,
proxyWallet: userAddress,
}));
return {
statusCode: 200,
json: dynamicResponse,
};
});
// Mock for resolved markets (redeemable=true) - overrides POLYMARKET_RESOLVED_MARKETS_POSITIONS_MOCKS
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(
url &&
url.includes('data-api.polymarket.com/positions') &&
url.includes('user=0x') &&
url.includes('redeemable=true'),
);
})
.asPriority(PRIORITY.API_OVERRIDE)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const userMatch = url?.match(/user=(0x[a-fA-F0-9]{40})/);
const userAddress = userMatch ? userMatch[1] : USER_WALLET_ADDRESS;
const eventIdMatch = url?.match(/eventId=([0-9]+)/);
const eventId = eventIdMatch ? eventIdMatch[1] : null;
let resolvedMarkets = POLYMARKET_RESOLVED_LOST_POSITIONS_RESPONSE;
let winningPositions = includeWinnings
? POLYMARKET_WINNING_POSITIONS_RESPONSE
: [];
if (eventId) {
resolvedMarkets = resolvedMarkets.filter(
(position) => position.eventId === eventId,
);
winningPositions = winningPositions.filter(
(position) => position.eventId === eventId,
);
}
const resolvedPositions = [
...resolvedMarkets.map((position) => ({
...position,
proxyWallet: userAddress,
})),
...winningPositions.map((position) => ({
...position,
proxyWallet: userAddress,
})),
];
return {
statusCode: 200,
json: resolvedPositions,
};
});
};
/**
* Override positions so winning positions return redeemable: true.
* Register at priority 1020 to override showWinningsAsActive (priority 1010).
*
* Must be registered AFTER the homepage has loaded (where redeemable: false
* was needed for visibility). React Query's staleTime (5s) will have elapsed
* by then, so market details triggers a background refetch that hits this mock.
*/
export async function POLYMARKET_ENABLE_CLAIMABLE_POSITIONS_MOCK(
mockServer: Mockttp,
) {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(
url &&
url.includes('data-api.polymarket.com/positions') &&
url.includes('user=0x') &&
!url.includes('redeemable=true'),
);
})
.asPriority(PRIORITY.CLAIMABLE_POSITIONS_OVERRIDE)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const userMatch = url?.match(/user=(0x[a-fA-F0-9]{40})/);
const userAddress = userMatch ? userMatch[1] : undefined;
const eventIdMatch = url?.match(/eventId=([0-9]+)/);
const eventId = eventIdMatch ? eventIdMatch[1] : null;
const allPositions = [
...POLYMARKET_CURRENT_POSITIONS_RESPONSE,
...POLYMARKET_WINNING_POSITIONS_RESPONSE,
];
const filteredPositions = eventId
? allPositions.filter((position) => position.eventId === eventId)
: allPositions;
const response = userAddress
? filteredPositions.map((position) => ({
...position,
proxyWallet: userAddress,
}))
: filteredPositions;
return {
statusCode: 200,
json: response,
};
});
}
/**
* Mock for Polymarket CLOB API key endpoints.
*
* The real Polymarket server always returns 400 for POST /auth/api-key on the
* test wallet, which causes `createApiKey` to fall back to
* GET /auth/derive-api-key. Both paths are mocked here so the order-placement
* flow never makes real network calls — eliminating the Android CI failure
* caused by `clob.polymarket.com` being unreachable in that environment.
*
* The `secret` value is a valid base64 string; `getL2Headers` decodes it with
* `Buffer.from(secret, 'base64')` before computing the HMAC. The relayer mock
* does not validate HMAC headers, so the exact credential values don't matter.
*/
export const POLYMARKET_CLOB_AUTH_MOCKS = async (mockServer: Mockttp) => {
// POST /auth/api-key always returns 400 for the test wallet, triggering the
// derive-api-key fallback. Replicate that behaviour so createApiKey takes
// the correct code path without touching the real server.
await mockServer
.forPost('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(url?.includes('clob.polymarket.com/auth/api-key'));
})
.asPriority(PRIORITY.BASE)
.thenReply(400, JSON.stringify({ error: 'Could not create api key' }), {
'content-type': 'application/json',
});
// GET /auth/derive-api-key — the actual credential source used at runtime.
// The returned values are only used to compute HMAC headers; the relayer
// mock does not validate those headers, so any non-empty strings suffice.
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(url?.includes('clob.polymarket.com/auth/derive-api-key'));
})
.asPriority(PRIORITY.BASE)
.thenCallback(() => ({
statusCode: 200,
json: { apiKey: 'e2e-key', secret: 'e2e-secret', passphrase: 'e2e-pass' },
}));
};
/**
* Mock for Polymarket CLOB prices API
* Returns BUY (best ask) and SELL (best bid) prices for outcome tokens
* This is used to display current market prices in the UI
*/
export const POLYMARKET_PRICES_MOCKS = async (mockServer: Mockttp) => {
await mockServer
.forPost('/proxy')
.matching(async (request) => {
const urlParam = new URL(request.url).searchParams.get('url');
if (!urlParam?.includes('clob.polymarket.com/prices')) {
return false;
}
try {
const bodyText = await request.body.getText();
const body = bodyText ? JSON.parse(bodyText) : undefined;
// Check if it's an array of price queries
return Array.isArray(body) && body.length > 0;
} catch {
return false;
}
})
.asPriority(PRIORITY.BASE)
.thenCallback(async (request) => {
const bodyText = await safeGetBodyText(request);
if (bodyText === undefined) {
return { statusCode: 499, body: '' };
}
const body = bodyText ? JSON.parse(bodyText) : [];
// Extract unique token IDs from the request
const tokenIds = new Set<string>();
body.forEach((query: { token_id: string; side: string }) => {
if (query.token_id) {
tokenIds.add(query.token_id);
}
});
// Build response with prices for each token
const pricesResponse: Record<string, { BUY: string; SELL: string }> = {};
tokenIds.forEach((tokenId) => {
// Spurs token
if (
tokenId ===
'110743925263777693447488608878982152642205002490046349037358337248548507433643'
) {
// Best ask (BUY) = 0.62, Best bid (SELL) = 0.61
pricesResponse[tokenId] = {
BUY: '0.62', // Best ask - what you'd pay to buy
SELL: '0.61', // Best bid - what you'd receive to sell
};
}
// Pelicans token
else if (
tokenId ===
'38489710206351002266036612280230748165102516187175290608628298208123746725814'
) {
// Best ask (BUY) = 0.38, Best bid (SELL) = 0.37
pricesResponse[tokenId] = {
BUY: '0.38', // Best ask - what you'd pay to buy
SELL: '0.37', // Best bid - what you'd receive to sell
};
}
// Celtics token (Celtics vs Nets market)
else if (
tokenId ===
'51851880223290407825872150827934296608070009371891114025629582819868766043137'
) {
// Best ask (BUY) = 0.84, Best bid (SELL) = 0.83 (from HAR file)
pricesResponse[tokenId] = {
BUY: '0.84', // Best ask - what you'd pay to buy
SELL: '0.83', // Best bid - what you'd receive to sell
};
}
// Nets token (Celtics vs Nets market)
else if (
tokenId ===
'51090123154876409384652748958994213129207000557350215937559106819875795938227'
) {
// Best ask (BUY) = 0.17, Best bid (SELL) = 0.17
// The app displays the SELL price (entry.sell), so both should be 0.17 to show 17¢
pricesResponse[tokenId] = {
BUY: '0.17', // Best ask - what you'd pay to buy
SELL: '0.17', // Best bid - what you'd receive to sell (this is what's displayed)
};
}
// Default prices for other tokens (can be extended as needed)
else {
pricesResponse[tokenId] = {
BUY: '0.50',
SELL: '0.50',
};
}
});
return {
statusCode: 200,
json: pricesResponse,
};
});
};
export const POLYMARKET_FEE_RATE_MOCKS = async (mockServer: Mockttp) => {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(
url &&
url.includes('clob.polymarket.com/fee-rate') &&
url.includes('token_id='),
);
})
.asPriority(PRIORITY.BASE)
.thenReply(200, JSON.stringify({ base_fee: 0 }), {
'content-type': 'application/json',
});
};
/**
* Mock for Polymarket CLOB prices-history API
* Returns an empty history series — sufficient for predict happy-path specs
* that render the chart (consumer treats non-array history as empty).
*/
export const POLYMARKET_PRICES_HISTORY_MOCKS = async (mockServer: Mockttp) => {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(url?.includes('clob.polymarket.com/prices-history'));
})
.asPriority(PRIORITY.BASE)
.thenReply(200, JSON.stringify({ history: [] }), {
'content-type': 'application/json',
});
};
/**
* Mock for Polymarket CLOB order book API
* Returns order book data for specific token IDs with correct market mapping
*/
export const POLYMARKET_ORDER_BOOK_MOCKS = async (mockServer: Mockttp) => {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(
url &&
url.includes('clob.polymarket.com/book') &&
url.includes('token_id='),
);
})
.asPriority(PRIORITY.BASE)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const tokenIdMatch = url?.match(/token_id=(\d+)/);
const tokenId = tokenIdMatch ? tokenIdMatch[1] : '';
// Select the correct order book response based on token ID
let orderBookResponse;
if (
tokenId ===
'36588252805891405622192021663682911922795750993518578680902576500086169492917'
) {
// 76ers token
orderBookResponse = POLYMARKET_ORDER_BOOK_RESPONSE;
} else if (
tokenId ===
'33945469250963963541781051637999677727672635213493648594066577298999471399137'
) {
// Zohran Mamdani token
orderBookResponse = POLYMARKET_ZOHRAN_ORDER_BOOK_RESPONSE;
} else if (
tokenId ===
'11584273833068499329017832956188664326032555278943683999231427554688326830185'
) {
// Chiefs Super Bowl token
orderBookResponse = POLYMARKET_CHIEFS_ORDER_BOOK_RESPONSE;
} else if (
tokenId ===
'72685162394098505217895638060393901041260225434938300730127268362092284806692'
) {
// Andrew Cuomo token
orderBookResponse = POLYMARKET_CUOMO_ORDER_BOOK_RESPONSE;
} else if (
tokenId ===
'19740329944962592380580142050369523795065853055987745520766432334608119837023'
) {
// Bills Super Bowl token
orderBookResponse = POLYMARKET_BILLS_ORDER_BOOK_RESPONSE;
} else if (
tokenId ===
'110743925263777693447488608878982152642205002490046349037358337248548507433643'
) {
// Spurs token
orderBookResponse = POLYMARKET_SPURS_ORDER_BOOK_RESPONSE;
} else if (
tokenId ===
'38489710206351002266036612280230748165102516187175290608628298208123746725814'
) {
// Pelicans token
orderBookResponse = POLYMARKET_PELICANS_ORDER_BOOK_RESPONSE;
} else if (
tokenId ===
'51851880223290407825872150827934296608070009371891114025629582819868766043137'
) {
// Celtics token (Celtics vs Nets)
orderBookResponse = POLYMARKET_CELTICS_ORDER_BOOK_RESPONSE;
} else {
// Default to 76ers for unknown token IDs
orderBookResponse = POLYMARKET_ORDER_BOOK_RESPONSE;
}
return {
statusCode: 200,
json: orderBookResponse,
};
});
};
/**
* Mock for Polymarket redeemable positions API
* Returns redeemable positions data for user 0x5f7c8f3c8bedf5e7db63a34ef2f39322ca77fe72
*/
export const POLYMARKET_RESOLVED_MARKETS_POSITIONS_MOCKS = async (
mockServer: Mockttp,
) => {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
const matches = Boolean(
url &&
url.includes('data-api.polymarket.com/positions') &&
url.includes('redeemable=true'),
);
return matches;
})
.asPriority(PRIORITY.BASE)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const userMatch = url?.match(/user=(0x[a-fA-F0-9]{40})/);
const userAddress = userMatch ? userMatch[1] : USER_WALLET_ADDRESS;
// Check if eventId parameter is present for filtering
const eventIdMatch = url?.match(/eventId=([0-9]+)/);
const eventId = eventIdMatch ? eventIdMatch[1] : null;
// Filter positions by eventId if provided
let filteredPositions = POLYMARKET_RESOLVED_LOST_POSITIONS_RESPONSE;
if (eventId) {
filteredPositions = POLYMARKET_RESOLVED_LOST_POSITIONS_RESPONSE.filter(
(position) => position.eventId === eventId,
);
}
const dynamicResponse = filteredPositions.map((position) => ({
...position,
proxyWallet: userAddress,
}));
return {
statusCode: 200,
json: dynamicResponse,
};
});
};
/**
* Mock for Polymarket activity API with test user trading activity
* Returns trading activity data for user 0x5f7c8f3c8bedf5e7db63a34ef2f39322ca77fe72
*/
export const POLYMARKET_ACTIVITY_MOCKS = async (mockServer: Mockttp) => {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(
url &&
url.includes('data-api.polymarket.com/activity') &&
url.includes('user=0x'),
);
})
.asPriority(PRIORITY.BASE)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const userMatch = url?.match(/user=(0x[a-fA-F0-9]{40})/);
const userAddress = userMatch ? userMatch[1] : USER_WALLET_ADDRESS;
const dynamicResponse = POLYMARKET_ACTIVITY_RESPONSE.map((activity) => ({
...activity,
proxyWallet: userAddress,
}));
return {
statusCode: 200,
json: dynamicResponse,
};
});
};
/**
* Mock for Polymarket UpNL API with test user unrealized P&L data
* Returns unrealized P&L data for user 0x5f7c8f3c8bedf5e7db63a34ef2f39322ca77fe72
*/
export const POLYMARKET_UPNL_MOCKS = async (mockServer: Mockttp) => {
await mockServer
.forGet('/proxy')
.matching((request) => {
const url = new URL(request.url).searchParams.get('url');
return Boolean(
url &&
url.includes('data-api.polymarket.com/upnl') &&
url.includes('user=0x'),
);
})
.asPriority(PRIORITY.BASE)
.thenCallback((request) => {
const url = new URL(request.url).searchParams.get('url');
const userMatch = url?.match(/user=(0x[a-fA-F0-9]{40})/);
const userAddress = userMatch ? userMatch[1] : USER_WALLET_ADDRESS;
// Update the mock response with the actual user address
const dynamicResponse = POLYMARKET_UPNL_RESPONSE.map((upnl) => ({
...upnl,
user: userAddress,
}));
return {
statusCode: 200,
json: dynamicResponse,
};
});
};
/**
* Mock for USDC balance calls on Polygon
* Returns mock USDC balance for the test user
* @param mockServer - The mockttp server instance
* @param customBalance - Optional custom USDC balance in wei (hex string)
*/
export const POLYMARKET_USDC_BALANCE_MOCKS = async (
mockServer: Mockttp,
customBalance?: string,
) => {
// Update global balance if custom balance provided
if (customBalance) {
currentUSDCBalance = customBalance;
}
// Token API single-token metadata (Polygon bridged USDC). Activity and other flows
// call GET .../token/137?address=0x2791...&includeRwaData=true — must be mocked for
// live-request validation in E2E.
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: /^https:\/\/token\.api\.cx\.metamask\.io\/token\/137\?.*address=0x2791bca1f2de4661ed88a30c99a7a9449aa84174/i,
responseCode: 200,
response: {
address: USDC_CONTRACT_ADDRESS.toLowerCase(),
symbol: 'USDC',
decimals: 6,
name: 'USD Coin',
iconUrl:
'https://static.cx.metamask.io/api/v1/tokenIcons/137/0x2791bca1f2de4661ed88a30c99a7a9449aa84174.png',
},
});
// pUSD (Polymarket USD) on Polygon — predict / transaction-pay call
// GET .../token/137?address=0xC011...&includeRwaData=true
await setupMockRequest(mockServer, {
requestMethod: 'GET',
url: new RegExp(
`^https://token\\.api\\.cx\\.metamask\\.io/token/137\\?.*address=${POLYGON_PUSD_TOKEN_ADDRESS}`,
'i',
),
responseCode: 200,
response: {
address: POLYGON_PUSD_TOKEN_ADDRESS,
symbol: 'PUSD',
decimals: 6,
name: 'Polymarket USD',
iconUrl: `https://static.cx.metamask.io/api/v1/tokenIcons/137/${POLYGON_PUSD_TOKEN_ADDRESS}.png`,
},
});
// The app makes balance calls through the proxy, not direct Infura calls
// Our existing proxy mock below will handle these calls
// Add a catch-all mock for any eth_call to Polygon RPC (including polygon-rpc.com)
await mockServer
.forPost('/proxy')
.matching(async (request) => {
const urlParam = new URL(request.url).searchParams.get('url');
const isPolygonRPC = Boolean(urlParam?.includes('polygon'));
const isEthereumRPC = Boolean(
urlParam?.includes('mainnet') || urlParam?.includes('ethereum'),
);
const isInfuraRPC = Boolean(urlParam?.includes('infura'));
if (isPolygonRPC || isEthereumRPC || isInfuraRPC) {
try {
const bodyText = await request.body.getText();
const body = bodyText ? JSON.parse(bodyText) : undefined;
const isEthCall = body?.method === 'eth_call';
if (isEthCall) {
const toAddress = body?.params?.[0]?.to?.toLowerCase();
const isUSDCBalanceCall =
toAddress === USDC_CONTRACT_ADDRESS.toLowerCase();
const isProxyWalletCall =
toAddress === PROXY_WALLET_ADDRESS.toLowerCase() ||
toAddress === '0x254955be605cf7c4e683e92b157187550bd5e639';
// Match USDC balance calls, proxy wallet calls, and other contract calls
return isUSDCBalanceCall || isProxyWalletCall || Boolean(toAddress);
}
// Also match other RPC methods like eth_getCode, eth_getBalance, etc.
return Boolean(body?.method);
} catch (error) {
return false;
}
}
return false;
})
.asPriority(PRIORITY.BASE)
.thenCallback(async (request) => {
const bodyText = await safeGetBodyText(request);
if (bodyText === undefined) {
return { statusCode: 499, body: '' };
}
const body = bodyText ? JSON.parse(bodyText) : undefined;
// Return appropriate mock response based on the call
// Can be string (hex) or object (transaction receipt)
let result: string | object = '0x';
if (body?.method === 'eth_call') {
const toAddress = body?.params?.[0]?.to;
const callData = body?.params?.[0]?.data;
if (toAddress?.toLowerCase() === SAFE_FACTORY_ADDRESS.toLowerCase()) {
// Safe Factory call - return proxy wallet address
result = MOCK_RPC_RESPONSES.SAFE_FACTORY_RESULT;
} else if (
toAddress?.toLowerCase() === POLYGON_PUSD_TOKEN_ADDRESS.toLowerCase()
) {
// pUSD contract call (post-CLOB-v1 migration: Predict balance lives in pUSD).
// Return the current global balance for balanceOf so the displayed Predict
// balance comes from pUSD, matching production state for v2 users.
if (callData?.toLowerCase()?.startsWith('0x70a08231')) {
// balanceOf(address) selector - return current global balance
result = currentUSDCBalance;
} else if (callData?.toLowerCase()?.startsWith('0xdd62ed3e')) {
// allowance(address,address) selector - max allowance
result =
'0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';
} else {