-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathutils.ts
More file actions
2095 lines (1844 loc) · 55.7 KB
/
utils.ts
File metadata and controls
2095 lines (1844 loc) · 55.7 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
import { SignTypedDataVersion } from '@metamask/keyring-controller';
import { query } from '@metamask/controller-utils';
import EthQuery from '@metamask/eth-query';
import { Hex, numberToHex } from '@metamask/utils';
import { ethers } from 'ethers';
import { Interface } from 'ethers/lib/utils';
import Engine from '../../../../../core/Engine';
import DevLogger from '../../../../../core/SDKConnect/utils/DevLogger';
import Logger from '../../../../../util/Logger';
import {
OnchainTradeParams,
PredictMarketStatus,
PredictPositionStatus,
PredictSportsLeague,
Side,
type PredictCategory,
type PredictMarket,
type PredictPosition,
PredictActivity,
PredictOutcome,
PredictOutcomeGroup,
PredictOutcomeToken,
PredictMarketGame,
} from '../../types';
import { getRecurrence } from '../../utils/format';
import {
buildGameData,
getEventLeague,
mapApiTeamToPredictTeam,
type TeamLookup,
} from '../../utils/gameParser';
import {
isDrawCapableLeague,
isMoneylineLikeMarketType,
SUPPORTED_SPORTS_LEAGUES,
} from '../../constants/sports';
import type {
GetMarketsParams,
OrderPreview,
PredictFees,
PreviewOrderParams,
} from '../types';
import {
ClobAuthDomain,
DEFAULT_CLOB_BASE_URL,
DEFAULT_GROUP_KEY,
EIP712Domain,
GROUP_ORDER,
SPORTS_MARKET_TYPE_PRIORITIES,
HASH_ZERO_BYTES32,
MATIC_CONTRACTS_V2,
MSG_TO_SIGN,
POLYGON_MAINNET_CHAIN_ID,
POLYMARKET_PROVIDER_ID,
ROUNDING_CONFIG,
SLIPPAGE_BUY,
SLIPPAGE_SELL,
SPORTS_MARKET_TYPE_TO_GROUP,
} from './constants';
import {
ApiKeyCreds,
ClobFeeDetails,
ClobHeaders,
ClobMarketInfo,
COLLATERAL_TOKEN_DECIMALS,
ContractConfig,
L2HeaderArgs,
OrderSummary,
PolymarketApiEvent,
PolymarketApiActivity,
PolymarketApiMarket,
PolymarketApiTeam,
PolymarketPosition,
TickSize,
OrderBook,
} from './types';
import { PREDICT_CONSTANTS, PREDICT_ERROR_CODES } from '../../constants/errors';
import { PredictFeeCollection } from '../../types/flags';
import { roundToFiveDecimals } from '../../utils/orders';
import { getMinAmountReceivedWithSlippage } from './protocol/slippage';
export { SPORTS_MARKET_TYPE_TO_GROUP, GROUP_ORDER } from './constants';
/**
* Parse a fetch `Response` body as JSON, raising a contextual error when the
* body is not valid JSON. Without this wrapper the bare
* `await response.json()` call only surfaces "JSON Parse error: Unexpected
* character: <" with no clue which endpoint returned HTML, which masks the
* underlying problem (e.g. an upstream proxy/error page reaching the client).
*/
async function parseJsonOrThrow<T>(
response: Response,
url: string,
): Promise<T> {
const text = await response.text();
try {
return JSON.parse(text) as T;
} catch (parseError) {
const snippet = text.slice(0, 200).replace(/\s+/gu, ' ');
DevLogger.log('Polymarket: non-JSON response from endpoint', {
url,
status: response.status,
contentType: response.headers.get('content-type'),
bodySnippet: snippet,
});
throw new Error(
`Polymarket fetch returned non-JSON (status ${response.status}) from ${url}: ${snippet}`,
);
}
}
export const getPolymarketEndpoints = () => ({
GAMMA_API_ENDPOINT: 'https://gamma-api.polymarket.com',
CLOB_ENDPOINT: DEFAULT_CLOB_BASE_URL,
DATA_API_ENDPOINT: 'https://data-api.polymarket.com',
CRYPTO_PRICE_ENDPOINT: 'https://polymarket.com/api/crypto/crypto-price',
GEOBLOCK_API_ENDPOINT: 'https://polymarket.com/api/geoblock',
HOMEPAGE_CAROUSEL_ENDPOINT: 'https://polymarket.com/api/homepage/carousel',
CLOB_RELAYER:
process.env.METAMASK_ENVIRONMENT === 'dev'
? 'https://predict.dev-api.cx.metamask.io'
: 'https://predict.api.cx.metamask.io',
});
export const getL1Headers = async ({ address }: { address: string }) => {
const domain = {
name: 'ClobAuthDomain',
version: '1',
chainId: POLYGON_MAINNET_CHAIN_ID,
};
const types = {
EIP712Domain,
...ClobAuthDomain,
};
const message = {
address,
timestamp: `${Math.floor(Date.now() / 1000)}`,
nonce: 0,
message: MSG_TO_SIGN,
};
const signature = await Engine.context.KeyringController.signTypedMessage(
{
data: {
domain,
types,
message,
primaryType: 'ClobAuth',
},
from: address,
},
SignTypedDataVersion.V4,
);
const headers = {
POLY_ADDRESS: address,
POLY_SIGNATURE: signature,
POLY_TIMESTAMP: `${message.timestamp}`,
POLY_NONCE: `${message.nonce}`,
};
return headers;
};
/**
* Builds the canonical Polymarket CLOB HMAC signature
*
* @param secret
* @param timestamp
* @param method
* @param requestPath
* @param body
* @returns string
*/
export const buildPolyHmacSignature = async (
secret: string,
timestamp: number,
method: string,
requestPath: string,
body?: string,
): Promise<string> => {
let message = timestamp + method + requestPath;
if (body !== undefined) {
message += body;
}
const base64Secret = Buffer.from(secret, 'base64');
const hmac = global.crypto.createHmac('sha256', base64Secret);
const sig = hmac.update(message).digest('base64');
// NOTE: Must be url safe base64 encoding, but keep base64 "=" suffix
// Convert '+' to '-'
// Convert '/' to '_'
const sigUrlSafe = replaceAll(replaceAll(sig, '+', '-'), '/', '_');
return sigUrlSafe;
};
export const getL2Headers = async ({
l2HeaderArgs,
timestamp,
address,
apiKey,
}: {
l2HeaderArgs: L2HeaderArgs;
timestamp?: number;
address: string;
apiKey: ApiKeyCreds;
}) => {
let ts = Math.floor(Date.now() / 1000);
if (timestamp !== undefined) {
ts = timestamp;
}
const sig = await buildPolyHmacSignature(
apiKey?.secret || '',
ts,
l2HeaderArgs.method,
l2HeaderArgs.requestPath,
l2HeaderArgs.body,
);
const headers = {
POLY_ADDRESS: address ?? '',
POLY_SIGNATURE: sig,
POLY_TIMESTAMP: `${ts}`,
POLY_API_KEY: apiKey?.apiKey || '',
POLY_PASSPHRASE: apiKey?.passphrase || '',
};
return headers;
};
function getClobEndpoint(): string {
const { CLOB_ENDPOINT } = getPolymarketEndpoints();
return CLOB_ENDPOINT;
}
const clobMarketInfoCache = new Map<string, ClobMarketInfo>();
const reportedClobMarketInfoFailures = new Set<string>();
const isObjectRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
const isOptionalFiniteNumber = (value: unknown): boolean =>
value === undefined || (typeof value === 'number' && Number.isFinite(value));
const isOptionalNullableFiniteNumber = (value: unknown): boolean =>
value === undefined ||
value === null ||
(typeof value === 'number' && Number.isFinite(value));
const isOptionalNullableBoolean = (value: unknown): boolean =>
value === undefined || value === null || typeof value === 'boolean';
const isClobFeeDetails = (value: unknown): value is ClobFeeDetails =>
isObjectRecord(value) &&
isOptionalNullableFiniteNumber(value.r) &&
isOptionalNullableFiniteNumber(value.e) &&
isOptionalNullableBoolean(value.to);
const isClobMarketInfo = (value: unknown): value is ClobMarketInfo =>
isObjectRecord(value) &&
(value.fd === undefined || isClobFeeDetails(value.fd)) &&
isOptionalFiniteNumber(value.mts) &&
isOptionalFiniteNumber(value.mos);
const ensureClobMarketInfoError = (error: unknown): Error => {
if (error instanceof Error) {
return error;
}
return new Error(String(error));
};
const getClobMarketInfoFailureContext = (conditionId: string) => ({
tags: {
feature: PREDICT_CONSTANTS.FEATURE_NAME,
provider: POLYMARKET_PROVIDER_ID,
},
context: {
name: 'PolymarketUtils',
data: {
method: 'getClobMarketInfo',
conditionId,
},
},
});
export const clearClobMarketInfoSessionState = () => {
clobMarketInfoCache.clear();
reportedClobMarketInfoFailures.clear();
};
export const clearClobMarketInfoCache = () => {
clobMarketInfoCache.clear();
};
export const deriveApiKey = async ({ address }: { address: string }) => {
const headers = await getL1Headers({ address });
const url = `${getClobEndpoint()}/auth/derive-api-key`;
const response = await fetch(url, {
method: 'GET',
headers,
});
if (!response.ok) {
throw new Error('Failed to derive API key');
}
const apiKeyRaw = await parseJsonOrThrow<ApiKeyCreds>(response, url);
return apiKeyRaw;
};
export const createApiKey = async ({ address }: { address: string }) => {
const headers = await getL1Headers({ address });
const url = `${getClobEndpoint()}/auth/api-key`;
const response = await fetch(url, {
method: 'POST',
headers,
body: '',
});
if (response.status === 400) {
return await deriveApiKey({ address });
}
const apiKeyRaw = await parseJsonOrThrow<ApiKeyCreds>(response, url);
return apiKeyRaw;
};
export const priceValid = (price: number, tickSize: TickSize): boolean =>
price >= parseFloat(tickSize) && price <= 1 - parseFloat(tickSize);
export const getClobMarketInfo = async ({
conditionId,
}: {
conditionId: string;
}): Promise<ClobMarketInfo> => {
const cachedMarketInfo = clobMarketInfoCache.get(conditionId);
if (cachedMarketInfo) {
return cachedMarketInfo;
}
const response = await fetch(
`${getClobEndpoint()}/clob-markets/${conditionId}`,
{
method: 'GET',
},
);
if (!response.ok) {
throw new Error('Failed to get CLOB market info');
}
const marketInfo = await response.json();
if (!isClobMarketInfo(marketInfo)) {
throw new Error('Invalid CLOB market info response');
}
clobMarketInfoCache.set(conditionId, marketInfo);
reportedClobMarketInfoFailures.delete(conditionId);
return marketInfo;
};
export const getClobMarketInfoSafe = async ({
conditionId,
}: {
conditionId: string;
}): Promise<ClobMarketInfo | undefined> => {
try {
return await getClobMarketInfo({ conditionId });
} catch (error) {
if (!reportedClobMarketInfoFailures.has(conditionId)) {
Logger.error(
ensureClobMarketInfoError(error),
getClobMarketInfoFailureContext(conditionId),
);
reportedClobMarketInfoFailures.add(conditionId);
}
return undefined;
}
};
const isValidFeeMetadata = (
marketInfo?: ClobMarketInfo,
): marketInfo is ClobMarketInfo & {
fd: { r: number; e: number };
} => {
const rate = marketInfo?.fd?.r;
const exponent = marketInfo?.fd?.e;
return (
typeof rate === 'number' &&
Number.isFinite(rate) &&
rate >= 0 &&
typeof exponent === 'number' &&
Number.isFinite(exponent) &&
exponent >= 0
);
};
const calculateMarketFeeAtPrice = ({
amountUsd,
rate,
exponent,
price,
}: {
amountUsd: number;
rate: number;
exponent: number;
price: number;
}): number => {
if (
amountUsd <= 0 ||
rate <= 0 ||
price <= 0 ||
price >= 1 ||
!Number.isFinite(price)
) {
return 0;
}
const fee =
amountUsd * rate * price ** (exponent - 1) * (1 - price) ** exponent;
return Number.isFinite(fee) && fee > 0 ? fee : 0;
};
export const calculateConservativeBuyMarketFee = ({
preview,
marketInfo,
}: {
preview: OrderPreview;
marketInfo?: ClobMarketInfo;
}): number => {
if (preview.side !== Side.BUY || !isValidFeeMetadata(marketInfo)) {
return 0;
}
const amountUsd = preview.maxAmountSpent;
const minAmountReceivedWithSlippage =
getMinAmountReceivedWithSlippage(preview);
if (
amountUsd <= 0 ||
preview.minAmountReceived <= 0 ||
minAmountReceivedWithSlippage <= 0
) {
return 0;
}
const snapshotAvgPrice = amountUsd / preview.minAmountReceived;
const worstAllowedAvgPrice = amountUsd / minAmountReceivedWithSlippage;
const leftEndpoint = Math.min(snapshotAvgPrice, worstAllowedAvgPrice);
const rightEndpoint = Math.max(snapshotAvgPrice, worstAllowedAvgPrice);
if (
!Number.isFinite(leftEndpoint) ||
!Number.isFinite(rightEndpoint) ||
leftEndpoint <= 0 ||
rightEndpoint >= 1
) {
return 0;
}
const { r: rate, e: exponent } = marketInfo.fd;
/*
* Polymarket's CLOB fee model prices buy market fees as:
*
* fee(p) = amountUsd * rate * p^(exponent - 1) * (1 - p)^exponent
*
* The exact fill price can move within the user's allowed slippage range, so
* a "conservative" estimate means charging the highest fee possible over the
* interval between the preview snapshot average price and the worst allowed
* average price. A smooth single-variable curve reaches its maximum either at
* one of the interval endpoints or, when it falls inside the interval, at the
* critical point where the derivative is zero:
*
* p* = (exponent - 1) / (2 * exponent - 1)
*/
const candidates = [leftEndpoint, rightEndpoint];
const criticalPoint = (exponent - 1) / (2 * exponent - 1);
if (
Number.isFinite(criticalPoint) &&
criticalPoint > leftEndpoint &&
criticalPoint < rightEndpoint
) {
candidates.push(criticalPoint);
}
const conservativeMarketFee = Math.max(
...candidates.map((price) =>
calculateMarketFeeAtPrice({
amountUsd,
rate,
exponent,
price,
}),
),
);
return roundToFiveDecimals(conservativeMarketFee);
};
export const getOrderBook = async ({ tokenId }: { tokenId: string }) => {
const response = await fetch(
`${getClobEndpoint()}/book?token_id=${tokenId}`,
{
method: 'GET',
},
);
if (!response.ok) {
const responseData = (await response.json()) as { error: string };
if (
responseData.error === 'No orderbook exists for the requested token id'
) {
throw new Error(PREDICT_ERROR_CODES.PREVIEW_NO_ORDER_BOOK);
}
throw new Error(responseData.error);
}
const responseData = (await response.json()) as OrderBook;
return responseData;
};
export const generateSalt = (): Hex =>
`0x${BigInt(Math.floor(Math.random() * 1000000)).toString(16)}`;
export const getContractConfig = (chainID: number): ContractConfig => {
switch (chainID) {
case POLYGON_MAINNET_CHAIN_ID:
return MATIC_CONTRACTS_V2;
default:
throw new Error('MetaMask Predict is only supported on Polygon mainnet');
}
};
export const encodeApprove = ({
spender,
amount,
}: {
spender: string;
amount: bigint | string;
}): Hex =>
new Interface([
'function approve(address spender, uint256 amount)',
]).encodeFunctionData('approve', [spender, amount]) as Hex;
export const encodeErc1155Approve = ({
spender,
approved,
}: {
spender: string;
approved: boolean;
}): Hex =>
new Interface([
'function setApprovalForAll(address operator, bool approved)',
]).encodeFunctionData('setApprovalForAll', [spender, approved]) as Hex;
export const encodeErc20Transfer = ({
to,
value,
}: {
to: string;
value: bigint | string | number;
}): Hex =>
new Interface([
'function transfer(address to, uint256 value)',
]).encodeFunctionData('transfer', [to, value]) as Hex;
function replaceAll(s: string, search: string, replace: string) {
return s.split(search).join(replace);
}
const normalizeSportsMarketType = (type: string): string => {
const lower = type.toLowerCase();
if (lower.startsWith('first_half_')) {
return lower.slice('first_half_'.length);
}
return lower;
};
const getSportsMarketTypePriority = (type: string): number =>
SPORTS_MARKET_TYPE_PRIORITIES[type.toLowerCase()] ?? 3;
export function buildOutcomeGroups(
outcomes: PredictOutcome[],
): PredictOutcomeGroup[] {
if (outcomes.length === 0) {
return [];
}
const groupMap = new Map<string, PredictOutcome[]>();
for (const outcome of outcomes) {
const groupKey =
(outcome.sportsMarketType &&
SPORTS_MARKET_TYPE_TO_GROUP[outcome.sportsMarketType]) ||
DEFAULT_GROUP_KEY;
const bucket = groupMap.get(groupKey);
if (bucket) {
bucket.push(outcome);
} else {
groupMap.set(groupKey, [outcome]);
}
}
for (const [, groupOutcomes] of groupMap) {
groupOutcomes.sort((a, b) => {
const priorityDiff =
getSportsMarketTypePriority(
normalizeSportsMarketType(a.sportsMarketType ?? ''),
) -
getSportsMarketTypePriority(
normalizeSportsMarketType(b.sportsMarketType ?? ''),
);
if (priorityDiff !== 0) {
return priorityDiff;
}
const volumeDiff = b.volume - a.volume;
if (volumeDiff !== 0) return volumeDiff;
return (b.liquidity ?? 0) - (a.liquidity ?? 0);
});
}
const groupEntries = [...groupMap.entries()];
groupEntries.sort((a, b) => {
const aIndex = GROUP_ORDER.indexOf(a[0]);
const bIndex = GROUP_ORDER.indexOf(b[0]);
const aPriority = aIndex === -1 ? GROUP_ORDER.length : aIndex;
const bPriority = bIndex === -1 ? GROUP_ORDER.length : bIndex;
if (aPriority !== bPriority) {
return aPriority - bPriority;
}
return a[0].localeCompare(b[0]);
});
return groupEntries.map(([key, groupOutcomes]) => {
const typeMap = new Map<string, PredictOutcome[]>();
for (const outcome of groupOutcomes) {
const type = outcome.sportsMarketType ?? key;
const bucket = typeMap.get(type);
if (bucket) {
bucket.push(outcome);
} else {
typeMap.set(type, [outcome]);
}
}
if (typeMap.size < 2) {
return { key, outcomes: groupOutcomes };
}
const subgroupEntries = [...typeMap.entries()];
subgroupEntries.sort(
(a, b) =>
getSportsMarketTypePriority(normalizeSportsMarketType(a[0])) -
getSportsMarketTypePriority(normalizeSportsMarketType(b[0])),
);
return {
key,
outcomes: [],
subgroups: subgroupEntries.map(([subKey, subOutcomes]) => ({
key: subKey,
outcomes: subOutcomes,
})),
};
});
}
export const isSpreadMarket = (market: PolymarketApiMarket): boolean =>
market.sportsMarketType?.toLowerCase().includes('spread') ?? false;
const isMoneylineLikeMarket = (market: PolymarketApiMarket): boolean =>
isMoneylineLikeMarketType(market.sportsMarketType);
/**
* Sort markets within a sports market type group by liquidity + volume (descending)
*/
const sortByLiquidityAndVolume = (
markets: PolymarketApiMarket[],
): PolymarketApiMarket[] =>
[...markets].sort((a, b) => {
const aScore = (a.liquidity ?? 0) + (a.volumeNum ?? 0);
const bScore = (b.liquidity ?? 0) + (b.volumeNum ?? 0);
return bScore - aScore;
});
const formatMarketGroupItemTitle = (market: PolymarketApiMarket): string => {
if (isSpreadMarket(market)) {
// Remove the dash before the spread number (e.g., "FC-Dallas -3.5" → "FC-Dallas 3.5")
// Uses negative lookahead to target dash followed by digit, not dashes in team names
return market.groupItemTitle.replace(/-(?=\d)/, '');
}
if (isMoneylineLikeMarket(market)) {
return market.groupItemTitle || market.question;
}
return market.groupItemTitle;
};
const YES_NO_TO_OVER_UNDER: Record<string, string> = {
Yes: 'Over',
No: 'Under',
};
const isOverUnderMarket = (market: PolymarketApiMarket): boolean =>
market.groupItemTitle?.includes('O/U') ?? false;
const formatOutcomeTitles = (market: PolymarketApiMarket): string[] => {
const outcomes = market.outcomes ? JSON.parse(market.outcomes) : [];
if (isSpreadMarket(market)) {
const line = market.line ? Math.abs(market.line) : 0;
return outcomes.map((outcome: string, index: number) =>
line ? `${outcome} ${index > 0 ? `+${line}` : `-${line}`}` : outcome,
);
}
if (isOverUnderMarket(market)) {
return outcomes.map(
(outcome: string) => YES_NO_TO_OVER_UNDER[outcome] ?? outcome,
);
}
return outcomes;
};
const OVER_UNDER_SHORT: Record<string, string> = {
Over: 'O',
Under: 'U',
Yes: 'O',
No: 'U',
};
const buildNameToAbbreviation = (
game: PredictMarketGame,
): Record<string, string> => ({
[game.homeTeam.name]: game.homeTeam.abbreviation,
...(game.homeTeam.alias && {
[game.homeTeam.alias]: game.homeTeam.abbreviation,
}),
[game.awayTeam.name]: game.awayTeam.abbreviation,
...(game.awayTeam.alias && {
[game.awayTeam.alias]: game.awayTeam.abbreviation,
}),
});
const formatOutcomeShortTitles = (
market: PolymarketApiMarket,
game: PredictMarketGame,
): (string | undefined)[] => {
const outcomes: string[] = market.outcomes ? JSON.parse(market.outcomes) : [];
const nameToAbbr = buildNameToAbbreviation(game);
if (isSpreadMarket(market)) {
const line = market.line ? Math.abs(market.line) : 0;
return outcomes.map((outcome: string, index: number) => {
const abbr = nameToAbbr[outcome];
if (!abbr) return undefined;
return line ? `${abbr} ${index > 0 ? `+${line}` : `-${line}`}` : abbr;
});
}
return outcomes.map((outcome: string) => {
const shortOU = OVER_UNDER_SHORT[outcome];
if (shortOU && market.line != null) {
return `${shortOU} ${market.line}`;
}
const abbr = nameToAbbr[outcome];
return abbr ?? undefined;
});
};
const sortOutcomeTokens = (
outcomeTokens: PredictOutcomeToken[],
market: PolymarketApiMarket,
event: PolymarketApiEvent,
): PredictOutcomeToken[] => {
if (isSpreadMarket(market)) {
const teamA = event.title.split(' vs. ')[0];
return [...outcomeTokens].sort((a, b) => {
// teamA should come first
if (a.title.includes(teamA)) {
return -1;
}
if (b.title.includes(teamA)) {
return 1;
}
return 0;
});
}
return outcomeTokens;
};
const getNegRiskYesTokenTitle = (
market: PolymarketApiMarket,
): string | undefined => {
if (
!market.negRisk ||
!isMoneylineLikeMarket(market) ||
!market.groupItemTitle
) {
return undefined;
}
return market.groupItemTitle.toLowerCase().startsWith('draw')
? 'Draw'
: market.groupItemTitle;
};
const resolveNegRiskShortTitles = (
market: PolymarketApiMarket,
game: PredictMarketGame,
): { yesShort?: string; noShort?: string } => {
if (
!market.negRisk ||
!isMoneylineLikeMarket(market) ||
!market.groupItemTitle
) {
return {};
}
if (market.groupItemTitle.toLowerCase().startsWith('draw')) {
return {};
}
const nameToAbbr = buildNameToAbbreviation(game);
const yesAbbr = nameToAbbr[market.groupItemTitle];
if (!yesAbbr) return {};
const isHome = yesAbbr === game.homeTeam.abbreviation;
const noAbbr = isHome
? game.awayTeam.abbreviation
: game.homeTeam.abbreviation;
return { yesShort: yesAbbr, noShort: noAbbr };
};
const parsePolymarketMarketOutcomes = (
market: PolymarketApiMarket,
event: PolymarketApiEvent,
game?: PredictMarketGame,
): PredictOutcomeToken[] => {
const outcomeTokensIds = market.clobTokenIds
? JSON.parse(market.clobTokenIds)
: [];
const outcomes = formatOutcomeTitles(market);
const shortTitles = game ? formatOutcomeShortTitles(market, game) : [];
const outcomePrices = market.outcomePrices
? JSON.parse(market.outcomePrices)
: [];
const negRiskYesTitle = getNegRiskYesTokenTitle(market);
const negRiskShort = game ? resolveNegRiskShortTitles(market, game) : {};
const outcomeTokens = outcomeTokensIds.map(
(tokenId: string, index: number) => {
const isYes = outcomes[index] === 'Yes';
const isNo = outcomes[index] === 'No';
let title = outcomes[index];
if (negRiskYesTitle && isYes) {
title = negRiskYesTitle;
}
let shortTitle: string | undefined = shortTitles[index];
if (negRiskYesTitle && isYes && negRiskShort.yesShort) {
shortTitle = negRiskShort.yesShort;
} else if (negRiskYesTitle && isNo && negRiskShort.noShort) {
shortTitle = negRiskShort.noShort;
}
return {
id: tokenId,
title,
...(shortTitle && { shortTitle }),
price: parseFloat(outcomePrices[index]),
};
},
);
return sortOutcomeTokens(outcomeTokens, market, event);
};
/**
* Sort sport markets by:
* 1. Group by sportsMarketType
* 2. Order groups: moneyline first, spreads second, totals third, then alphabetically
* 3. Within each group, sort by liquidity + volume (descending)
* 4. Return flattened array of all groups in order
*/
export const sortGameMarkets = (
markets: PolymarketApiMarket[],
): PolymarketApiMarket[] => {
// Group markets by sportsMarketType
const groupedMarkets = markets.reduce<Record<string, PolymarketApiMarket[]>>(
(acc, market) => {
const type = market.sportsMarketType ?? 'other';
if (!acc[type]) {
acc[type] = [];
}
acc[type].push(market);
return acc;
},
{},
);
// Get all unique types and sort them by priority
const sortedTypes = Object.keys(groupedMarkets).sort((a, b) => {
const priorityA = getSportsMarketTypePriority(a);
const priorityB = getSportsMarketTypePriority(b);
// If same priority (both are "other" category), sort alphabetically
if (priorityA === priorityB && priorityA === 3) {
return a.toLowerCase().localeCompare(b.toLowerCase());
}
return priorityA - priorityB;
});
// Sort each group by liquidity + volume, then flatten
return sortedTypes.flatMap((type) =>
sortByLiquidityAndVolume(groupedMarkets[type]),
);
};
export const sortMarketsByField = (
markets: PolymarketApiMarket[],
sortBy: 'price' | 'ascending' | 'descending',
): PolymarketApiMarket[] => {
// If sortBy is not returned, do not sort
if (!sortBy) {
return markets;
}
return [...markets].sort((a, b) => {
switch (sortBy) {
case 'price': {
// Sort by descending percentage chance from market.outcomePrices[0]
const aPrice = a.outcomePrices ? JSON.parse(a.outcomePrices)[0] : '0';
const bPrice = b.outcomePrices ? JSON.parse(b.outcomePrices)[0] : '0';
return parseFloat(bPrice) - parseFloat(aPrice);
}
case 'ascending': {
// Sort by market.groupItemThreshold ascending
return (a.groupItemThreshold ?? 0) - (b.groupItemThreshold ?? 0);
}
case 'descending': {
// Sort by market.groupItemThreshold descending
return (b.groupItemThreshold ?? 0) - (a.groupItemThreshold ?? 0);
}
default:
return 0;
}
});
};
export const sortMarkets = ({
event,
sortBy,
isGameEvent,
}: {
event: PolymarketApiEvent;
sortBy?: 'price' | 'ascending' | 'descending';
isGameEvent?: boolean;
}): PolymarketApiMarket[] => {
const markets = Array.isArray(event.markets) ? event.markets : [];
const eventSortBy = event.sortBy;
if (isGameEvent) {
return sortGameMarkets(markets);
}
if (sortBy) {
return sortMarketsByField(markets, sortBy);
}
if (eventSortBy) {
return sortMarketsByField(markets, eventSortBy);
}
return markets;
};
export const parsePolymarketMarket = (
market: PolymarketApiMarket,
event: PolymarketApiEvent,
game?: PredictMarketGame,
): PredictOutcome => ({
id: market.conditionId,
providerId: POLYMARKET_PROVIDER_ID,
marketId: event.id,
title: market.question,
description: market.description,
image: market.icon ?? market.image,
groupItemTitle: formatMarketGroupItemTitle(market),
groupItemThreshold:
market.groupItemThreshold != null
? Number(market.groupItemThreshold)