-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathcommon.ts
More file actions
1274 lines (1105 loc) · 40.1 KB
/
common.ts
File metadata and controls
1274 lines (1105 loc) · 40.1 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 { getRetryProvider, paginatedEventQuery as umaPaginatedEventQuery } from "@uma/common";
import { createHttpClient } from "@uma/toolkit";
import { AxiosError, AxiosInstance } from "axios";
export const paginatedEventQuery = umaPaginatedEventQuery;
import type { Provider } from "@ethersproject/abstract-provider";
import { BigNumber, Contract, Event, EventFilter, ethers } from "ethers";
import { getAddress, OptimisticOracleEthers, OptimisticOracleV2Ethers } from "@uma/contracts-node";
import {
DisputePriceEvent,
ProposePriceEvent,
} from "@uma/contracts-node/dist/packages/contracts-node/typechain/core/ethers/OptimisticOracleV2";
import { getContractInstanceWithProvider } from "../utils/contracts";
import { Logger } from "@uma/financial-templates-lib";
export { getContractInstanceWithProvider } from "../utils/contracts";
import umaSportsOracleAbi from "./abi/umaSportsOracle.json";
// Opt-in local mode skips Datastore so the monitor can run without GCP access.
const isLocalNoDatastoreMode = process.env.LOCAL_NO_DATASTORE === "true";
const createDatastoreClient = () => {
const { Datastore } = require("@google-cloud/datastore");
return new Datastore();
};
const datastore = isLocalNoDatastoreMode ? null : createDatastoreClient();
import * as s from "superstruct";
export { Logger };
export const ONE_SCALED = ethers.utils.parseUnits("1", 18);
export const POLYGON_BLOCKS_PER_HOUR = 1800;
// Get Polymarket initializer whitelist from env
const getPolymarketInitializerWhitelist = (): string[] => {
const envWhitelist = process.env.POLYMARKET_INITIALIZER_WHITELIST;
if (envWhitelist) {
const parsed = JSON.parse(envWhitelist);
if (Array.isArray(parsed)) {
return parsed.map((addr) => addr.toString().toLowerCase());
}
throw new Error("POLYMARKET_INITIALIZER_WHITELIST must be a JSON array");
}
console.log("POLYMARKET_INITIALIZER_WHITELIST not provided, using empty whitelist");
return [];
};
interface GraphQLResponse<T> {
data?: T;
errors?: { message: string }[];
}
export interface MonitoringParams {
ctfExchangeAddress: string;
ctfSportsOracleAddress: string;
additionalRequesters: string[];
maxBlockLookBack: number;
graphqlEndpoint: string;
polymarketApiKey: string;
apiEndpoint: string;
provider: Provider;
chainId: number;
pollingDelay: number;
unknownProposalNotificationInterval: number;
retryAttempts: number;
retryDelayMs: number;
checkBeforeExpirationSeconds: number;
fillEventsLookbackSeconds: number;
fillEventsProposalGapSeconds: number;
httpClient: ReturnType<typeof createHttpClient>;
orderBookBatchSize: number;
orderBookSubgraphEndpoint: string;
ooV2Addresses: string[];
ooV1Addresses: string[];
aiConfig?: AIConfig;
subgraphSyncTolerance: number;
}
interface PolymarketMarketGraphql {
question: string;
outcomes: string;
outcomePrices: string;
volumeNum: number;
clobTokenIds: string;
questionID: string;
}
export interface PolymarketMarketGraphqlProcessed {
volumeNum: number;
outcomes: [string, string];
outcomePrices: [string, string];
clobTokenIds: [string, string];
question: string;
questionID: string;
}
export interface PolymarketTradeInformation {
price: number;
type: "buy" | "sell";
amount: number;
timestamp: number;
}
export interface PolymarketOrderBook {
market: string;
asset_id: string;
bids: { price: string; size: string }[];
asks: { price: string; size: string }[];
hash: string;
}
export type Order = { price: number; size: number }[];
export interface MarketOrderbook {
bids: Order;
asks: Order;
}
export interface OptimisticPriceRequest {
requestHash: string;
requestTimestamp: BigNumber;
requestLogIndex: number;
requester: string;
proposer: string;
identifier: string;
ancillaryData: string;
proposalBlockNumber: number;
proposedPrice: BigNumber;
proposalTimestamp: BigNumber;
proposalHash: string;
proposalExpirationTimestamp: BigNumber;
proposalLogIndex: number;
}
interface StoredNotifiedProposal {
proposalHash: string;
}
export enum MarketType {
Winner,
Spreads,
Totals,
}
export enum Ordering {
HomeVsAway,
AwayVsHome,
}
export enum Underdog {
Home,
Away,
}
export type Market = {
marketType: MarketType;
ordering: Ordering;
underdog: Underdog;
line: ethers.BigNumber;
};
export const getPolymarketProposedPriceRequestsOO = async (
params: MonitoringParams,
version: "v1" | "v2",
requesterAddresses: string[],
ooAddress: string
): Promise<OptimisticPriceRequest[]> => {
const currentBlockNumber = await params.provider.getBlockNumber();
const oneDayInBlocks = POLYGON_BLOCKS_PER_HOUR * 24;
const startBlockNumber = currentBlockNumber - oneDayInBlocks;
const maxBlockLookBack = params.maxBlockLookBack;
const searchConfig = {
fromBlock: startBlockNumber,
toBlock: currentBlockNumber,
maxBlockLookBack,
};
const oo = await getContractInstanceWithProvider<OptimisticOracleEthers | OptimisticOracleV2Ethers>(
version == "v1" ? "OptimisticOracle" : "OptimisticOracleV2",
params.provider,
ooAddress
);
const proposeEvents = await paginatedEventQuery<ProposePriceEvent>(
oo,
oo.filters.ProposePrice(null, null, null, null, null, null, null, null),
searchConfig,
params.retryAttempts,
queryFilterSafe
);
const disputeEvents = await paginatedEventQuery<DisputePriceEvent>(
oo,
oo.filters.DisputePrice(null, null, null, null, null, null, null),
searchConfig,
params.retryAttempts,
queryFilterSafe
);
const disputedRequestIds = new Set(
disputeEvents.map((event) =>
ethers.utils.keccak256(
ethers.utils.solidityPack(
["address", "bytes32", "uint256", "bytes"],
[event.args.requester, event.args.identifier, event.args.timestamp, event.args.ancillaryData]
)
)
)
);
const currentTime = Math.floor(Date.now() / 1000);
const currentTimeBN = BigNumber.from(currentTime);
const threshold = BigNumber.from(params.checkBeforeExpirationSeconds);
return Promise.all(
proposeEvents
.filter((event) => requesterAddresses.map((r) => r.toLowerCase()).includes(event.args.requester.toLowerCase()))
.filter((event) => {
const expirationTime = event.args.expirationTimestamp;
const thresholdTime = expirationTime.sub(threshold);
// Only keep if current time is greater than (expiration - threshold) but less than expiration.
return currentTimeBN.gt(thresholdTime) && currentTimeBN.lt(expirationTime);
})
.filter((event) => {
const requestId = ethers.utils.keccak256(
ethers.utils.solidityPack(
["address", "bytes32", "uint256", "bytes"],
[event.args.requester, event.args.identifier, event.args.timestamp, event.args.ancillaryData]
)
);
return !disputedRequestIds.has(requestId);
})
.map(async (event) => {
const proposalTimestamp = BigNumber.from(
await params.provider.getBlock(event.blockNumber).then((block) => block.timestamp)
);
return {
requestHash: event.transactionHash,
requestLogIndex: event.logIndex,
requester: event.args.requester,
proposer: event.args.proposer,
identifier: event.args.identifier,
requestTimestamp: event.args.timestamp,
ancillaryData: event.args.ancillaryData,
proposalBlockNumber: event.blockNumber,
proposedPrice: event.args.proposedPrice,
proposalTimestamp,
proposalHash: event.transactionHash,
proposalExpirationTimestamp: event.args.expirationTimestamp,
proposalLogIndex: event.logIndex,
};
})
);
};
// Extract initializer address from ancillary data
export const extractInitializerFromAncillaryData = (ancillaryData: string): string | null => {
// Check if ancillary data ends with "initializer:..." pattern (there is no 0x prefix)
const initializerMatch = ancillaryData.match(/initializer:([0-9a-fA-F]{40})$/);
if (initializerMatch) {
return "0x" + initializerMatch[1];
}
// If no initializer key found, return null
return null;
};
// Get reward amount from contract's requests mapping via eth_call
export const getRewardForProposal = async (
params: MonitoringParams,
proposal: OptimisticPriceRequest,
version: "v1" | "v2"
): Promise<BigNumber> => {
const oo = await getContractInstanceWithProvider<OptimisticOracleEthers | OptimisticOracleV2Ethers>(
version == "v1" ? "OptimisticOracle" : "OptimisticOracleV2",
params.provider
);
// Calculate the request ID as done in the contract: keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData))
const requestId = ethers.utils.keccak256(
ethers.utils.solidityPack(
["address", "bytes32", "uint256", "bytes"],
[proposal.requester, proposal.identifier, proposal.requestTimestamp, proposal.ancillaryData]
)
);
// Use eth_call to read from the requests mapping directly - this is much more efficient than event queries
const request = await oo.requests(requestId);
return request.reward;
};
// Check if a proposal should be ignored based on 3rd party criteria
export const shouldIgnoreThirdPartyProposal = async (
params: MonitoringParams,
proposal: OptimisticPriceRequest,
version: "v1" | "v2"
): Promise<boolean> => {
let criteriaCount = 0;
// 1. Check if reward is 0
const reward = await getRewardForProposal(params, proposal, version);
if (reward.eq(0)) {
criteriaCount++;
}
// 2. Check if initializer is not on whitelist (only if whitelist is configured)
// Decode hex ancillary data to string first
const ancillaryDataString = ethers.utils.toUtf8String(proposal.ancillaryData);
const initializer = extractInitializerFromAncillaryData(ancillaryDataString);
const whitelist = getPolymarketInitializerWhitelist();
if (initializer && whitelist.length > 0 && !whitelist.includes(initializer.toLowerCase())) {
criteriaCount++;
}
// 3. Check if initializer matches proposer (already available in proposal data)
if (initializer && initializer.toLowerCase() === proposal.proposer.toLowerCase()) {
criteriaCount++;
}
// Return true if >= 2 criteria are met (should ignore)
return criteriaCount >= 2;
};
export const getPolymarketMarketInformation = async (
logger: typeof Logger,
params: MonitoringParams,
questionID: string
): Promise<PolymarketMarketGraphqlProcessed[]> => {
const query = `
{
markets(where: "LOWER(question_id) = LOWER('${questionID}') or LOWER(neg_risk_request_id) = LOWER('${questionID}') or LOWER(game_id) = LOWER('${questionID}')") {
clobTokenIds
volumeNum
outcomes
outcomePrices
question
questionID
}
}
`;
const { data } = await params.httpClient.post<GraphQLResponse<{ markets: PolymarketMarketGraphql[] }>>(
params.graphqlEndpoint,
{ query },
{
headers: { authorization: `Bearer ${params.polymarketApiKey}` },
}
);
if (data.errors?.length) {
throw new Error(data.errors.map((e) => e.message).join("; "));
}
if (!data.data?.markets) {
throw new Error("No markets found");
}
const { markets } = data.data;
if (!markets.length) {
throw new Error(`No market found for question ID: ${questionID}`);
}
return markets.map((market) => {
return {
...market,
outcomes: JSON.parse(market.outcomes),
outcomePrices: JSON.parse(market.outcomePrices),
clobTokenIds: JSON.parse(market.clobTokenIds),
};
});
};
interface OrderFilledEventSubgraph {
id: string;
transactionHash: string;
makerAssetId: string;
takerAssetId: string;
maker: string;
taker: string;
makerAmountFilled: string;
takerAmountFilled: string;
fee: string;
timestamp: string;
orderHash: string;
}
interface SubgraphOrderFilledResponse {
data?: {
orderFilledEvents: OrderFilledEventSubgraph[];
};
errors?: { message: string }[];
}
interface SubgraphMetaResponse {
data?: {
_meta: {
block: {
number: number;
};
};
};
errors?: { message: string }[];
}
const getTradeInfoFromOrderFilledEvent = async (
provider: Provider,
event: any
): Promise<PolymarketTradeInformation> => {
const blockTimestamp = (await provider.getBlock(event.blockNumber)).timestamp;
const isBuy = event.args.makerAssetId.toString() === "0";
const numerator = (isBuy ? event.args.makerAmountFilled : event.args.takerAmountFilled).mul(1000);
const denominator = isBuy ? event.args.takerAmountFilled : event.args.makerAmountFilled;
const price = numerator.div(denominator).toNumber() / 1000;
return {
price,
type: isBuy ? "buy" : "sell",
timestamp: blockTimestamp,
// Convert to decimal value with 2 decimals
amount: (isBuy ? event.args.takerAmountFilled : event.args.makerAmountFilled).div(10_000).toNumber() / 100,
};
};
const getTradeInfoFromSubgraphEvent = (event: OrderFilledEventSubgraph): PolymarketTradeInformation => {
const isBuy = event.makerAssetId === "0";
const makerAmountFilled = BigNumber.from(event.makerAmountFilled);
const takerAmountFilled = BigNumber.from(event.takerAmountFilled);
const numerator = (isBuy ? makerAmountFilled : takerAmountFilled).mul(1000);
const denominator = isBuy ? takerAmountFilled : makerAmountFilled;
const price = numerator.div(denominator).toNumber() / 1000;
return {
price,
type: isBuy ? "buy" : "sell",
timestamp: parseInt(event.timestamp),
// Convert to decimal value with 2 decimals
amount: (isBuy ? takerAmountFilled : makerAmountFilled).div(10_000).toNumber() / 100,
};
};
const querySubgraphOrderFilledEvents = async (
httpClient: AxiosInstance,
subgraphEndpoint: string,
whereField: "takerAssetId" | "makerAssetId",
assetId: string,
pageSize = 1000,
startTimestamp?: number
): Promise<OrderFilledEventSubgraph[]> => {
const allEvents: OrderFilledEventSubgraph[] = [];
let skip = 0;
let hasMore = true;
while (hasMore) {
// Build where clause with optional timestamp filter
const whereClause = startTimestamp
? `{timestamp_gt: ${startTimestamp}, ${whereField}: "${assetId}"}`
: `{${whereField}: "${assetId}"}`;
const query = `
{
orderFilledEvents(
where: ${whereClause},
first: ${pageSize},
skip: ${skip},
orderBy: timestamp,
orderDirection: asc
) {
id
transactionHash
makerAssetId
takerAssetId
maker
taker
makerAmountFilled
takerAmountFilled
fee
timestamp
orderHash
}
}
`;
const response = await httpClient.post<SubgraphOrderFilledResponse>(subgraphEndpoint, { query });
if (response.data.errors?.length) {
throw new Error(response.data.errors.map((e) => e.message).join("; "));
}
if (!response.data.data?.orderFilledEvents) {
throw new Error("Invalid response from subgraph");
}
const events = response.data.data.orderFilledEvents;
allEvents.push(...events);
// If we got fewer events than pageSize, we've reached the end
hasMore = events.length === pageSize;
skip += pageSize;
}
return allEvents;
};
const getOrderFilledEventsFromSubgraph = async (
params: MonitoringParams,
clobTokenIds: [string, string],
startTimestamp?: number
): Promise<[PolymarketTradeInformation[], PolymarketTradeInformation[]]> => {
// Query 4 combinations: takerAssetId for both tokens, makerAssetId for both tokens
const queries = [
{ whereField: "takerAssetId" as const, assetId: clobTokenIds[0], tokenIndex: 0 },
{ whereField: "takerAssetId" as const, assetId: clobTokenIds[1], tokenIndex: 1 },
{ whereField: "makerAssetId" as const, assetId: clobTokenIds[0], tokenIndex: 0 },
{ whereField: "makerAssetId" as const, assetId: clobTokenIds[1], tokenIndex: 1 },
];
// Execute all queries in parallel
const queryResults = await Promise.all(
queries.map((q) =>
querySubgraphOrderFilledEvents(
params.httpClient,
params.orderBookSubgraphEndpoint,
q.whereField,
q.assetId,
1000,
startTimestamp
)
)
);
// Group events by token index, deduplicating per token (same event can appear for both tokens)
const tokenOneEventIds = new Set<string>();
const tokenTwoEventIds = new Set<string>();
const tokenOneEvents: PolymarketTradeInformation[] = [];
const tokenTwoEvents: PolymarketTradeInformation[] = [];
// Process takerAssetId queries (index 0 and 1)
queryResults[0].forEach((event) => {
if (!tokenOneEventIds.has(event.id)) {
tokenOneEventIds.add(event.id);
tokenOneEvents.push(getTradeInfoFromSubgraphEvent(event));
}
});
queryResults[1].forEach((event) => {
if (!tokenTwoEventIds.has(event.id)) {
tokenTwoEventIds.add(event.id);
tokenTwoEvents.push(getTradeInfoFromSubgraphEvent(event));
}
});
// Process makerAssetId queries (index 2 and 3)
queryResults[2].forEach((event) => {
if (!tokenOneEventIds.has(event.id)) {
tokenOneEventIds.add(event.id);
tokenOneEvents.push(getTradeInfoFromSubgraphEvent(event));
}
});
queryResults[3].forEach((event) => {
if (!tokenTwoEventIds.has(event.id)) {
tokenTwoEventIds.add(event.id);
tokenTwoEvents.push(getTradeInfoFromSubgraphEvent(event));
}
});
// Sort by timestamp
const sortByTimestamp = (events: PolymarketTradeInformation[]): PolymarketTradeInformation[] => {
return events.sort((a, b) => a.timestamp - b.timestamp);
};
return [sortByTimestamp(tokenOneEvents), sortByTimestamp(tokenTwoEvents)];
};
const checkSubgraphSyncStatus = async (httpClient: AxiosInstance, subgraphEndpoint: string): Promise<number | null> => {
const query = `
{
_meta {
block {
number
}
}
}
`;
try {
const response = await httpClient.post<SubgraphMetaResponse>(subgraphEndpoint, { query });
if (response.data.errors?.length) {
throw new Error(response.data.errors.map((e) => e.message).join("; "));
}
if (!response.data.data?._meta?.block?.number) {
throw new Error("Invalid response from subgraph meta query");
}
return response.data.data._meta.block.number;
} catch (error) {
// Return null if we can't check sync status, caller should handle gracefully
return null;
}
};
const getOrderFilledEventsSlow = async (
params: MonitoringParams,
clobTokenIds: [string, string],
startBlockNumber: number
): Promise<[PolymarketTradeInformation[], PolymarketTradeInformation[]]> => {
const ctfExchange = new ethers.Contract(
params.ctfExchangeAddress,
require("./abi/ctfExchange.json"),
params.provider
);
const currentBlockNumber = await params.provider.getBlockNumber();
const maxBlockLookBack = params.maxBlockLookBack;
const searchConfig = {
fromBlock: startBlockNumber,
toBlock: currentBlockNumber,
maxBlockLookBack,
};
const events: Event[] = await paginatedEventQuery(
ctfExchange,
ctfExchange.filters.OrderFilled(null, null, null, null, null, null, null, null),
searchConfig,
params.retryAttempts,
queryFilterSafe
);
const outcomeTokenOne = await Promise.all(
events
.filter((event) => {
return [event?.args?.takerAssetId.toString(), event?.args?.makerAssetId.toString()].includes(clobTokenIds[0]);
})
.map((event) => getTradeInfoFromOrderFilledEvent(params.provider, event))
);
const outcomeTokenTwo = await Promise.all(
events
.filter((event) => {
return [event?.args?.takerAssetId.toString(), event?.args?.makerAssetId.toString()].includes(clobTokenIds[1]);
})
.map((event) => getTradeInfoFromOrderFilledEvent(params.provider, event))
);
return [outcomeTokenOne, outcomeTokenTwo];
};
export const getOrderFilledEvents = async (
params: MonitoringParams,
clobTokenIds: [string, string],
startBlockNumber: number
): Promise<[PolymarketTradeInformation[], PolymarketTradeInformation[]]> => {
try {
// Check subgraph sync status first
const subgraphBlockNumber = await checkSubgraphSyncStatus(params.httpClient, params.orderBookSubgraphEndpoint);
if (subgraphBlockNumber !== null) {
// Get current block from provider
const currentBlockNumber = await params.provider.getBlockNumber();
const blockDifference = currentBlockNumber - subgraphBlockNumber;
// If subgraph is behind by more than tolerance, use slow method
if (blockDifference >= params.subgraphSyncTolerance) {
return await getOrderFilledEventsSlow(params, clobTokenIds, startBlockNumber);
}
}
// Get the block timestamp from startBlockNumber
const startBlock = await params.provider.getBlock(startBlockNumber);
const startTimestamp = startBlock.timestamp;
// Try the fast subgraph version
return await getOrderFilledEventsFromSubgraph(params, clobTokenIds, startTimestamp);
} catch (error) {
// Fallback to the slow version if subgraph fails
return await getOrderFilledEventsSlow(params, clobTokenIds, startBlockNumber);
}
};
export const calculatePolymarketQuestionID = (ancillaryData: string): string => {
return ethers.utils.keccak256(ancillaryData);
};
export async function getOrFallback<T>(
client: AxiosInstance,
url: string,
fallback: T,
opts?: {
statusCode?: number;
errorMessage?: string;
}
): Promise<T> {
try {
const resp = await client.get<T>(url);
return resp.data;
} catch (err) {
const axiosErr = err as AxiosError<{ error?: string }>;
const statusMatches = opts?.statusCode ? axiosErr.response?.status === opts.statusCode : false;
const messageMatches = opts?.errorMessage != null ? axiosErr.response?.data?.error === opts.errorMessage : false;
if (statusMatches && (opts?.errorMessage == null || messageMatches)) {
return fallback;
}
throw err;
}
}
export const getPolymarketOrderBook = async (
params: MonitoringParams,
clobTokenIds: [string, string]
): Promise<[MarketOrderbook, MarketOrderbook]> => {
const [marketOne, marketTwo] = clobTokenIds;
const apiUrlOne = params.apiEndpoint + `/book?token_id=${marketOne}`;
const apiUrlTwo = params.apiEndpoint + `/book?token_id=${marketTwo}`;
// Default to [] if the API returns an a 404 error with the message "No orderbook exists for the requested token id"
const outcome1Data = await getOrFallback(
params.httpClient,
apiUrlOne,
{ bids: [], asks: [] },
{
statusCode: 404,
errorMessage: "No orderbook exists for the requested token id",
}
);
const outcome2Data = await getOrFallback(
params.httpClient,
apiUrlTwo,
{ bids: [], asks: [] },
{
statusCode: 404,
errorMessage: "No orderbook exists for the requested token id",
}
);
const stringToNumber = (
orders: {
price: string;
size: string;
}[]
) => {
return orders.map((order) => {
return {
price: Number(order.price),
size: Number(order.size),
};
});
};
return [
{
bids: stringToNumber(outcome1Data.bids),
asks: stringToNumber(outcome1Data.asks),
},
{
bids: stringToNumber(outcome2Data.bids),
asks: stringToNumber(outcome2Data.asks),
},
];
};
export interface BookParams {
token_id: string;
}
export async function getPolymarketOrderBooks(
params: MonitoringParams,
tokenIds: string[]
): Promise<Record<string, MarketOrderbook>> {
const batchSize = params.orderBookBatchSize;
const apiUrl = `${params.apiEndpoint}/books`;
type RawOrderBook = {
asset_id: string;
bids: { price: string; size: string }[];
asks: { price: string; size: string }[];
};
const toNumeric = (orders: { price: string; size: string }[]) =>
orders.map((o) => ({ price: Number(o.price), size: Number(o.size) }));
// Split the clob IDs into batches that respect the limit.
const chunks: string[][] = [];
for (let i = 0; i < tokenIds.length; i += batchSize) {
chunks.push(tokenIds.slice(i, i + batchSize));
}
// Fire off every API call in parallel.
const chunkResults = await Promise.all(
chunks.map((ids) => {
const payload: BookParams[] = ids.map((token_id) => ({ token_id }));
return params.httpClient.post<RawOrderBook[]>(apiUrl, payload).then((res) => res.data);
})
);
// Consolidate all partial order books into one look-up map.
const map: Record<string, MarketOrderbook> = {};
for (const rawBooks of chunkResults) {
for (const ob of rawBooks) {
map[ob.asset_id] = { bids: toNumeric(ob.bids), asks: toNumeric(ob.asks) };
}
}
// Guarantee every requested ID appears, even if the API returned none.
for (const id of tokenIds) {
if (!map[id]) map[id] = { bids: [], asks: [] };
}
return map;
}
export async function getSportsMarketData(params: MonitoringParams, questionID: string): Promise<Market> {
const umaSportsOracle = new ethers.Contract(params.ctfSportsOracleAddress, umaSportsOracleAbi, params.provider);
return umaSportsOracle.getMarket(questionID);
}
export function decodeMultipleQueryPriceAtIndex(encodedPrice: BigNumber, index: number): BigNumber {
if (index < 0 || index > 6) {
throw new Error("Index out of range");
}
// Shift the bits of encodedPrice to the right by (32 * index) positions.
// This moves the desired 32-bit segment to the least significant bits.
// Then, we use bitwise AND with 0xffffffff (as a BigNumber) to extract that segment.
return encodedPrice.shr(32 * index).and(BigNumber.from("0xffffffff"));
}
export function encodeMultipleQuery(values: string[]): BigNumber {
if (values.length > 7) {
throw new Error("Maximum of 7 values allowed");
}
let encodedPrice = BigNumber.from(0);
for (let i = 0; i < values.length; i++) {
if (!values[i]) {
throw new Error("All values must be defined");
}
const numValue = Number(values[i]);
if (!Number.isInteger(numValue)) {
throw new Error("All values must be integers");
}
if (numValue > 0xffffffff || numValue < 0) {
throw new Error("Values must be uint32 (0 <= value <= 2^32 - 1)");
}
// Shift the current value by 32 * i bits (placing the first value at the LSB)
// then OR it into the encodedPrice.
encodedPrice = encodedPrice.or(BigNumber.from(numValue).shl(32 * i));
}
return encodedPrice;
}
export function isUnresolvable(price: BigNumber | string): boolean {
const maxInt256 = ethers.constants.MaxInt256;
return typeof price === "string" ? price === maxInt256.toString() : price.eq(maxInt256);
}
export function decodeScores(
ordering: Ordering,
data: ethers.BigNumber
): { home: ethers.BigNumber; away: ethers.BigNumber } {
const home = decodeMultipleQueryPriceAtIndex(data, ordering === Ordering.HomeVsAway ? 0 : 1);
const away = decodeMultipleQueryPriceAtIndex(data, ordering === Ordering.HomeVsAway ? 1 : 0);
return { home, away };
}
export function getSportsPayouts(market: Market, proposedPrice: ethers.BigNumber): [number, number] {
const { home, away } = decodeScores(market.ordering, proposedPrice);
const line = market.line.div(ethers.utils.parseUnits("1", 6));
// Handle Spreads market
if (market.marketType === MarketType.Spreads) {
// Spreads are always: ["Favorite", "Underdog"]
// Determine which score is underdog's based on market.underdog
const [underdogScore, favoriteScore] = market.underdog === Underdog.Home ? [home, away] : [away, home];
// Underdog wins if their score is higher OR if the spread (difference) is within the line.
return underdogScore.gt(favoriteScore) || favoriteScore.sub(underdogScore).lte(line)
? [0, 1] // Underdog wins
: [1, 0]; // Favorite wins
}
// Handle Totals market
if (market.marketType === MarketType.Totals) {
// Totals are always: ["Under", "Over"]
const total = home.add(away);
return total.lte(line) ? [0, 1] : [1, 0];
}
// Handle Draw (applicable for Winner markets)
if (home.eq(away)) {
return [1, 1];
}
// Handle Winner market for Home vs Away ordering
if (market.ordering === Ordering.HomeVsAway) {
return home.gt(away) ? [1, 0] : [0, 1];
}
// Handle Winner market for Away vs Home ordering
return home.gt(away) ? [0, 1] : [1, 0];
}
const MultipleValuesQuery = s.object({
// The title of the request
title: s.string(),
// Description of the request
description: s.string(),
// Values will be encoded into the settled price in the same order as the provided labels. The oracle UI will display each Label along with an input field. 7 labels maximum.
labels: s.array(s.string()),
});
export type MultipleValuesQuery = s.Infer<typeof MultipleValuesQuery>;
const isMultipleValuesQueryFormat = (q: unknown) => s.is(q, MultipleValuesQuery);
export function decodeMultipleValuesQuery(decodedAncillaryData: string): MultipleValuesQuery {
const endOfObjectIndex = decodedAncillaryData.lastIndexOf("}");
const maybeJson = endOfObjectIndex > 0 ? decodedAncillaryData.slice(0, endOfObjectIndex + 1) : decodedAncillaryData;
const json = JSON.parse(maybeJson);
if (!isMultipleValuesQueryFormat(json)) throw new Error("Not a valid multiple values request");
return json;
}
export interface UMAAIRetry {
id: string;
question_id: string;
data: {
input: {
timing?: {
expiration_timestamp?: number;
};
};
};
}
export interface UMAAIRetriesLatestResponse {
elements: UMAAIRetry[];
next_cursor: string | null;
has_more: boolean;
total_count: number;
total_pages: number;
}
interface AIRetryLookupResult {
deeplink?: string;
}
export async function fetchLatestAIDeepLink(
proposal: OptimisticPriceRequest,
params: MonitoringParams,
logger: typeof Logger
): Promise<AIRetryLookupResult> {
if (!params.aiConfig) {
return { deeplink: undefined };
}
try {
const questionId = calculatePolymarketQuestionID(proposal.ancillaryData);
const response = await params.httpClient.get<UMAAIRetriesLatestResponse>(params.aiConfig.apiUrl, {
params: {
limit: 50,
search: proposal.proposalHash,
last_page: false,
project_id: params.aiConfig.projectId,
},
});
const result = response.data?.elements?.find(
(element) => element.data.input.timing?.expiration_timestamp === proposal.proposalExpirationTimestamp.toNumber()
);
if (!result) {
logger.debug({
at: "PolymarketMonitor",
message: "No AI deeplink found for proposal",
proposalHash: proposal.proposalHash,
expirationTimestamp: proposal.proposalExpirationTimestamp.toNumber(),
questionId: questionId,
response: {
data: response.data,
status: response.status,
statusText: response.statusText,
},
notificationPath: "otb-monitoring",
});
return { deeplink: undefined };
}
return {
deeplink: `${params.aiConfig.resultsBaseUrl}/${result.id}`,
};
} catch (error) {
logger.debug({
at: "PolymarketMonitor",
message: "Failed to fetch AI deeplink",
err: error instanceof Error ? error.message : String(error),
proposalHash: proposal.proposalHash,