-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathall_networks_shared.ts
More file actions
1407 lines (1290 loc) · 43.9 KB
/
all_networks_shared.ts
File metadata and controls
1407 lines (1290 loc) · 43.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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 { x402Facilitator } from "@x402/core/facilitator";
import {
EIP2612_GAS_SPONSORING,
createErc20ApprovalGasSponsoringExtension,
type Erc20ApprovalGasSponsoringSigner,
} from "@x402/extensions";
import { toFacilitatorEvmSigner, type FacilitatorEvmSigner } from "@x402/evm";
import { ExactEvmScheme } from "@x402/evm/exact/facilitator";
import { UptoEvmScheme } from "@x402/evm/upto/facilitator";
import { StandardMerkleTree } from "@openzeppelin/merkle-tree";
import { SuiClient, getFullnodeUrl } from "@mysten/sui/client";
import { WalrusClient } from "@mysten/walrus";
import { Redis, type RedisOptions } from "ioredis";
import {
createWalletClient,
defineChain,
encodeFunctionData,
http,
keccak256,
parseGwei,
parseTransaction,
publicActions,
recoverTransactionAddress,
toHex,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";
import {
debugLog,
summarizeDataSettlementJob,
summarizeError,
summarizePaymentPayload,
summarizePaymentRequirements,
summarizeSettleResponse,
summarizeVerifyResponse,
} from "./logging.js";
import { gaugeMetric, histogramMetric, incrementMetric } from "./metrics.js";
import {
BASE_MAINNET_NETWORK,
base64ToBytesCalldata,
DATA_INDIVIDUAL_SETTLEMENT_UPLOAD_ATTEMPTS,
DATA_INDIVIDUAL_SETTLEMENT_UPLOAD_RETRY_DELAY_MS,
DATA_SETTLEMENT_BATCH_BUFFER_SIZE,
DATA_SETTLEMENT_BATCH_IDLE_TIMEOUT_MS,
DATA_SETTLEMENT_BATCH_MAX_AGE_MS,
DATA_INDIVIDUAL_SETTLEMENT_NONCE_KEY,
DATA_INDIVIDUAL_WORKER_EVM_PRIVATE_KEY_ENV,
DATA_WORKER_EVM_PRIVATE_KEY_ENV,
DATA_WORKER_SETTLEMENT_CONTRACT_ENV,
HEARTBEAT_RELAY_EVM_PRIVATE_KEY_ENV,
HEARTBEAT_RELAY_REGISTRY_CONTRACT_ENV,
OG_EVM_NETWORK,
REDIS_URL,
toBytesCalldata,
toStrictBytes32,
type DataSettlementJobData,
type DataWorkerContext,
type HeartbeatRelayContext,
type IndividualDataSettlementJobData,
type SettlementBatchData,
type SettlementHandlerResult,
type SettlementIndividualData,
} from "./all_networks_types_helpers.js";
const ogEvm = defineChain({
id: 10740,
name: "OG EVM",
nativeCurrency: {
decimals: 18,
name: "OG",
symbol: "OG",
},
rpcUrls: {
default: { http: ["https://ogevmdevnet.opengradient.ai/"] },
},
blockExplorers: {
default: {
name: "OG EVM Explorer",
url: "https://explorer.og.artela.io",
},
},
contracts: {
multicall3: {
address: "0x4200000000000000000000000000000000000006",
blockCreated: 1,
},
},
});
const DATA_WORKER_SETTLEMENT_GAS_LIMIT = BigInt(
process.env.DATA_WORKER_SETTLEMENT_GAS_LIMIT || "9000000",
);
const DATA_WORKER_TX_RECEIPT_TIMEOUT_MS = Number(
process.env.DATA_WORKER_TX_RECEIPT_TIMEOUT_MS || 120_000,
);
const BASE_MAINNET_RPC_URL = process.env.BASE_MAINNET_RPC_URL;
const HEARTBEAT_RELAY_GAS_LIMIT = BigInt(process.env.HEARTBEAT_RELAY_GAS_LIMIT || "500000");
const HEARTBEAT_RELAY_TX_RECEIPT_TIMEOUT_MS = Number(
process.env.HEARTBEAT_RELAY_TX_RECEIPT_TIMEOUT_MS || 120_000,
);
type BatchFlushReason = "buffer-full" | "idle-timeout" | "max-age-timeout";
type BatchFlushResult = {
merkleRoot: string;
blobId: string;
itemCount: number;
reason: BatchFlushReason;
settlementTxHash: `0x${string}`;
};
type WalrusUploadResponse = {
newlyCreated?: {
blobObject: {
blobId: string;
};
};
alreadyCertified?: {
blobId: string;
};
};
type WalrusNetwork = "testnet" | "mainnet";
type IndividualSettlementPreparer = {
signerAddress: `0x${string}`;
close: () => Promise<void>;
prepare: (
data: SettlementIndividualData,
) => Promise<Omit<IndividualDataSettlementJobData, "settlementType" | "data">>;
};
const DEFAULT_SPONSORED_RAW_TX_GAS = 70_000n;
const DEFAULT_SPONSORED_RAW_TX_MAX_FEE_PER_GAS = 1_000_000_000n;
type SponsoredGasWalletClient = {
getBalance(args: { address: `0x${string}` }): Promise<bigint>;
sendTransaction(args: {
to: `0x${string}`;
data?: `0x${string}`;
gas?: bigint;
value?: bigint;
}): Promise<`0x${string}`>;
waitForTransactionReceipt(args: { hash: `0x${string}` }): Promise<{ status: string }>;
sendRawTransaction(args: { serializedTransaction: `0x${string}` }): Promise<`0x${string}`>;
};
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutHandle = setTimeout(() => {
reject(new Error(`${label} timed out after ${timeoutMs}ms`));
}, timeoutMs);
timeoutHandle.unref?.();
});
try {
return await Promise.race([promise, timeoutPromise]);
} finally {
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
}
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
function emitBatchOldestAgeMetric(): void {
const oldestAgeMs =
batchSettlementBuffer.length > 0 && batchSettlementFirstBufferedAtMs !== null
? Math.max(0, Date.now() - batchSettlementFirstBufferedAtMs)
: 0;
gaugeMetric("data.batch.oldest_age_ms", oldestAgeMs, ["worker:data"]);
}
function isAlreadyKnownRawTransactionError(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
return message.toLowerCase().includes("already known");
}
let batchSettlementBuffer: SettlementBatchData[] = [];
let batchSettlementFlushTimer: ReturnType<typeof setTimeout> | null = null;
let batchSettlementMaxAgeTimer: ReturnType<typeof setTimeout> | null = null;
let batchSettlementFirstBufferedAtMs: number | null = null;
let batchFlushInFlight: Promise<BatchFlushResult | null> | null = null;
let walrusClient: WalrusClient | null = null;
const settlementContractAbi = [
{
type: "function",
name: "batchSettle",
stateMutability: "nonpayable",
inputs: [
{
name: "_merkleRoot",
type: "bytes32",
},
{
name: "_batchSize",
type: "uint256",
},
{
name: "_walrusBlobId",
type: "bytes",
},
],
outputs: [],
},
{
type: "function",
name: "settleIndividual",
stateMutability: "nonpayable",
inputs: [
{
name: "_teeId",
type: "bytes32",
},
{
name: "_inputHash",
type: "bytes32",
},
{
name: "_outputHash",
type: "bytes32",
},
{
name: "_timestamp",
type: "uint256",
},
{
name: "_ethAddress",
type: "address",
},
{
name: "_walrusBlobId",
type: "bytes",
},
{
name: "_signature",
type: "bytes",
},
],
outputs: [],
},
] as const;
const teeRegistryHeartbeatAbi = [
{
type: "function",
name: "heartbeat",
stateMutability: "nonpayable",
inputs: [
{
name: "teeId",
type: "bytes32",
},
{
name: "timestamp",
type: "uint256",
},
{
name: "signature",
type: "bytes",
},
],
outputs: [],
},
] as const;
function scheduleBatchFlush(context: DataWorkerContext): void {
if (batchSettlementFlushTimer) {
clearTimeout(batchSettlementFlushTimer);
}
batchSettlementFlushTimer = setTimeout(() => {
void flushBatchSettlementBuffer(context, "idle-timeout").catch(error => {
console.error("[settlement] Batch idle-timeout flush failed:", error);
});
}, DATA_SETTLEMENT_BATCH_IDLE_TIMEOUT_MS);
batchSettlementFlushTimer.unref?.();
if (batchSettlementFirstBufferedAtMs !== null && !batchSettlementMaxAgeTimer) {
const elapsedMs = Date.now() - batchSettlementFirstBufferedAtMs;
const remainingMs = Math.max(0, DATA_SETTLEMENT_BATCH_MAX_AGE_MS - elapsedMs);
batchSettlementMaxAgeTimer = setTimeout(() => {
void flushBatchSettlementBuffer(context, "max-age-timeout").catch(error => {
console.error("[settlement] Batch max-age flush failed:", error);
});
}, remainingMs);
batchSettlementMaxAgeTimer.unref?.();
}
}
async function flushBatchSettlementBuffer(
context: DataWorkerContext,
reason: BatchFlushReason,
): Promise<BatchFlushResult | null> {
if (batchFlushInFlight) {
return batchFlushInFlight;
}
batchFlushInFlight = (async () => {
if (batchSettlementBuffer.length === 0) {
emitBatchOldestAgeMetric();
return null;
}
const flushStartedAtMs = Date.now();
const items = batchSettlementBuffer;
const flushedBatchFirstBufferedAtMs = batchSettlementFirstBufferedAtMs;
batchSettlementBuffer = [];
batchSettlementFirstBufferedAtMs = null;
if (batchSettlementFlushTimer) {
clearTimeout(batchSettlementFlushTimer);
batchSettlementFlushTimer = null;
}
if (batchSettlementMaxAgeTimer) {
clearTimeout(batchSettlementMaxAgeTimer);
batchSettlementMaxAgeTimer = null;
}
try {
const values = items.map(item => [
toStrictBytes32(item.teeId, "teeId"),
toStrictBytes32(item.inputHash, "inputHash"),
toStrictBytes32(item.outputHash, "outputHash"),
base64ToBytesCalldata(item.teeSignature),
item.timestamp,
]);
const tree = StandardMerkleTree.of(values, [
"bytes32",
"bytes32",
"bytes32",
"bytes",
"uint256",
]);
const merkleRoot = tree.root;
const treeData = JSON.stringify(tree.dump());
const blobId = await uploadToWalrus(treeData, "batch-tree");
const settlementTxHash = await context.submitBatchSettlement(
merkleRoot as `0x${string}`,
items.length,
blobId,
);
console.log("[settlement] Batch settlement flushed:", {
signerAddress: context.signerAddress,
chainId: context.chainId,
chainName: context.chainName,
merkleRoot,
walrusBlobId: blobId,
itemCount: items.length,
reason,
});
console.log("[settlement] Batch settlement transaction submitted:", {
settlementContractAddress: context.settlementContractAddress,
txHash: settlementTxHash,
merkleRoot,
batchSize: items.length,
walrusBlobId: blobId,
});
incrementMetric("data.batch.settled.count", ["worker:data"]);
histogramMetric("data.batch.size", items.length, ["worker:data"]);
histogramMetric("data.batch.flush.duration_ms", Date.now() - flushStartedAtMs, [
"worker:data",
`reason:${reason}`,
"outcome:success",
]);
emitBatchOldestAgeMetric();
return {
merkleRoot,
blobId,
itemCount: items.length,
reason,
settlementTxHash,
};
} catch (error) {
batchSettlementBuffer = [...items, ...batchSettlementBuffer];
batchSettlementFirstBufferedAtMs =
flushedBatchFirstBufferedAtMs ?? batchSettlementFirstBufferedAtMs ?? Date.now();
scheduleBatchFlush(context);
console.error("[settlement] Batch settlement flush failed; restored items to buffer:", {
signerAddress: context.signerAddress,
chainId: context.chainId,
chainName: context.chainName,
restoredItemCount: items.length,
bufferedItems: batchSettlementBuffer.length,
reason,
error,
});
histogramMetric("data.batch.flush.duration_ms", Date.now() - flushStartedAtMs, [
"worker:data",
`reason:${reason}`,
"outcome:failure",
]);
emitBatchOldestAgeMetric();
throw error;
}
})();
try {
return await batchFlushInFlight;
} finally {
batchFlushInFlight = null;
}
}
export async function processPrivateSettlement(): Promise<SettlementHandlerResult> {
console.warn(
"[settlement] Received x-settlement-type=private in facilitator request. Ignoring as sanity check.",
);
return {
acknowledged: true,
settlementType: "private",
processedAt: new Date().toISOString(),
notes: "Private settlement ignored by facilitator.",
};
}
export async function uploadToWalrus(
data: string,
uploadKind: "batch-tree" | "individual-payload" = "individual-payload",
): Promise<string> {
const publisherUrl = process.env.WALRUS_PUBLISHER_URL || "http://localhost:9002/v1/blobs";
const url = `${publisherUrl}?epochs=10`;
const walrusUploadTimeoutMs = Number(process.env.WALRUS_UPLOAD_TIMEOUT_MS || 30_0000);
console.log(`[settlement] Uploading ${uploadKind} to Walrus via ${publisherUrl}`);
const abortController = new AbortController();
const timeout = setTimeout(() => abortController.abort(), walrusUploadTimeoutMs);
timeout.unref?.();
let response: Response;
try {
response = await fetch(url, {
method: "PUT",
body: data,
headers: {
"Content-Type": "application/json",
},
signal: abortController.signal,
});
} catch (error) {
incrementMetric("data.walrus_upload.failure.count", ["worker:data", `kind:${uploadKind}`]);
throw error;
} finally {
clearTimeout(timeout);
}
if (!response.ok) {
incrementMetric("data.walrus_upload.failure.count", ["worker:data", `kind:${uploadKind}`]);
const errorText = await response.text();
throw new Error(`Walrus upload failed (${response.status}): ${errorText}`);
}
let result: WalrusUploadResponse;
try {
result = (await response.json()) as WalrusUploadResponse;
} catch (error) {
incrementMetric("data.walrus_upload.failure.count", ["worker:data", `kind:${uploadKind}`]);
throw error;
}
if (result.newlyCreated?.blobObject?.blobId) {
return result.newlyCreated.blobObject.blobId;
}
if (result.alreadyCertified?.blobId) {
console.log(`[settlement] ${uploadKind} already exists on Walrus (deduplicated).`);
return result.alreadyCertified.blobId;
}
incrementMetric("data.walrus_upload.failure.count", ["worker:data", `kind:${uploadKind}`]);
throw new Error("Unexpected response format from Walrus Publisher");
}
function getWalrusNetwork(): WalrusNetwork {
const network = process.env.WALRUS_NETWORK || "mainnet";
if (network !== "testnet" && network !== "mainnet") {
throw new Error("WALRUS_NETWORK must be either testnet or mainnet");
}
return network;
}
function getWalrusClient(): WalrusClient {
if (walrusClient) {
return walrusClient;
}
const network = getWalrusNetwork();
const suiClient = new SuiClient({
url: process.env.SUI_RPC_URL || getFullnodeUrl(network),
});
walrusClient = new WalrusClient({
network,
suiClient,
});
return walrusClient;
}
export function createIndividualWalrusPayload(data: SettlementIndividualData): string {
return JSON.stringify({
input: data.input,
output: data.output,
teeSignature: data.teeSignature,
teeId: data.teeId,
timestamp: data.timestamp,
ethAddress: data.ethAddress,
});
}
export async function computeWalrusBlobId(data: string): Promise<string> {
const bytes = new TextEncoder().encode(data);
const result = await getWalrusClient().encodeBlob(bytes);
return result.blobId;
}
export async function processBatchSettlement(
data: SettlementBatchData,
context: DataWorkerContext,
): Promise<SettlementHandlerResult> {
batchSettlementBuffer.push(data);
if (batchSettlementFirstBufferedAtMs === null) {
batchSettlementFirstBufferedAtMs = Date.now();
}
emitBatchOldestAgeMetric();
console.log("[settlement] Batch settlement item buffered:", {
signerAddress: context.signerAddress,
chainId: context.chainId,
chainName: context.chainName,
bufferedItems: batchSettlementBuffer.length,
...summarizeDataSettlementJob({ settlementType: "batch", data }),
});
debugLog("[settlement][debug] Raw batch settlement data", data);
scheduleBatchFlush(context);
const shouldFlushNow = batchSettlementBuffer.length >= DATA_SETTLEMENT_BATCH_BUFFER_SIZE;
const flushResult = shouldFlushNow
? await flushBatchSettlementBuffer(context, "buffer-full")
: null;
return {
acknowledged: true,
settlementType: "batch",
processedAt: new Date().toISOString(),
notes: flushResult
? `Batch settlement flushed (root=${flushResult.merkleRoot}, walrusBlobId=${flushResult.blobId}, count=${flushResult.itemCount}, txHash=${flushResult.settlementTxHash}).`
: `Batch settlement buffered (${batchSettlementBuffer.length}/${DATA_SETTLEMENT_BATCH_BUFFER_SIZE}).`,
};
}
export async function processIndividualSettlement(
data: SettlementIndividualData,
context: DataWorkerContext,
): Promise<SettlementHandlerResult> {
try {
const walrusPayload = {
input: data.input,
output: data.output,
teeSignature: data.teeSignature,
teeId: data.teeId,
timestamp: data.timestamp,
ethAddress: data.ethAddress,
};
const walrusData = JSON.stringify(walrusPayload);
const blobId = await uploadToWalrus(walrusData, "individual-payload");
const decodedSignatureHex = base64ToBytesCalldata(data.teeSignature);
const txHash = await context.submitIndividualSettlement({
teeId: data.teeId,
inputHash: toStrictBytes32(data.inputHash, "inputHash"),
outputHash: toStrictBytes32(data.outputHash, "outputHash"),
timestamp: data.timestamp,
ethAddress: data.ethAddress,
walrusBlobId: blobId,
signature: decodedSignatureHex,
});
console.log("[settlement] Processing individual settlement:", {
signerAddress: context.signerAddress,
chainId: context.chainId,
chainName: context.chainName,
walrusBlobId: blobId,
txHash,
...summarizeDataSettlementJob({ settlementType: "individual", data }),
});
debugLog("[settlement][debug] Raw individual settlement data", data);
debugLog("[settlement][debug] Walrus payload", walrusPayload);
console.log(
`[settlement] Individual settlement uploaded to Walrus with blob id: ${blobId}, txHash: ${txHash}`,
);
incrementMetric("data.individual_settled.count", ["worker:data"]);
return {
acknowledged: true,
settlementType: "individual",
processedAt: new Date().toISOString(),
notes: `Individual settlement processed (walrusBlobId=${blobId}, txHash=${txHash}).`,
};
} catch (error) {
console.error("[settlement] Individual settlement failed:", {
signerAddress: context.signerAddress,
chainId: context.chainId,
chainName: context.chainName,
settlementContractAddress: context.settlementContractAddress,
...summarizeDataSettlementJob({ settlementType: "individual", data }),
...summarizeError(error),
});
throw error;
}
}
async function uploadIndividualPayloadWithRetry(
jobData: IndividualDataSettlementJobData,
): Promise<void> {
const attempts = Math.max(1, DATA_INDIVIDUAL_SETTLEMENT_UPLOAD_ATTEMPTS);
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
const uploadedBlobId = await uploadToWalrus(jobData.walrusPayload, "individual-payload");
if (uploadedBlobId !== jobData.walrusBlobId) {
throw new Error(
`Walrus blob id mismatch: expected ${jobData.walrusBlobId}, got ${uploadedBlobId}`,
);
}
return;
} catch (error) {
const isFinalAttempt = attempt === attempts;
console.error(
isFinalAttempt
? "[settlement] Individual Walrus upload failed; no tx broadcast"
: "[settlement] Individual Walrus upload failed; retrying before broadcast",
{
attempt,
attempts,
queueNonce: jobData.queueNonce,
txHash: jobData.txHash,
walrusBlobId: jobData.walrusBlobId,
...summarizeError(error),
},
);
if (isFinalAttempt) {
throw error;
}
await sleep(DATA_INDIVIDUAL_SETTLEMENT_UPLOAD_RETRY_DELAY_MS);
}
}
}
export async function processPreSignedIndividualSettlement(
jobData: IndividualDataSettlementJobData,
context: DataWorkerContext,
): Promise<SettlementHandlerResult> {
const pendingNonce = await context.getPendingNonce();
if (jobData.queueNonce < pendingNonce) {
console.error("[settlement] Individual settlement nonce is already consumed; skipping tx", {
queueNonce: jobData.queueNonce,
pendingNonce,
txHash: jobData.txHash,
walrusBlobId: jobData.walrusBlobId,
});
return {
acknowledged: true,
settlementType: "individual",
processedAt: new Date().toISOString(),
walrusBlobId: jobData.walrusBlobId,
queueNonce: jobData.queueNonce,
signerAddress: jobData.signerAddress,
txHash: jobData.txHash,
notes: `Individual settlement skipped because nonce ${jobData.queueNonce} is already below pending nonce ${pendingNonce}; txHash=${jobData.txHash}.`,
};
}
if (jobData.queueNonce > pendingNonce) {
throw new Error(
`Individual settlement nonce ${jobData.queueNonce} is ahead of pending nonce ${pendingNonce}; waiting for earlier nonce before upload/broadcast`,
);
}
await uploadIndividualPayloadWithRetry(jobData);
let broadcastTxHash = jobData.txHash;
let broadcastWarning: string | undefined;
try {
broadcastTxHash = await context.sendSignedTransaction({
signedTransaction: jobData.signedTransaction,
txHash: jobData.txHash,
txType: "individual",
});
} catch (error) {
broadcastWarning = error instanceof Error ? error.message : String(error);
console.error("[settlement] Individual signed tx broadcast attempt failed; advancing queue", {
queueNonce: jobData.queueNonce,
txHash: jobData.txHash,
walrusBlobId: jobData.walrusBlobId,
...summarizeError(error),
});
}
console.log("[settlement] Pre-signed individual settlement broadcast:", {
signerAddress: jobData.signerAddress,
chainId: context.chainId,
chainName: context.chainName,
queueNonce: jobData.queueNonce,
walrusBlobId: jobData.walrusBlobId,
txHash: broadcastTxHash,
broadcastWarning,
...summarizeDataSettlementJob(jobData),
});
incrementMetric("data.individual_settled.count", ["worker:data-individual"]);
return {
acknowledged: true,
settlementType: "individual",
processedAt: new Date().toISOString(),
walrusBlobId: jobData.walrusBlobId,
queueNonce: jobData.queueNonce,
signerAddress: jobData.signerAddress,
txHash: broadcastTxHash,
notes: broadcastWarning
? `Individual settlement uploaded but broadcast had warning (${broadcastWarning}; nonce=${jobData.queueNonce}, walrusBlobId=${jobData.walrusBlobId}, txHash=${broadcastTxHash}).`
: `Individual settlement uploaded and broadcast (nonce=${jobData.queueNonce}, walrusBlobId=${jobData.walrusBlobId}, txHash=${broadcastTxHash}).`,
};
}
export async function processDataSettlementJob(
jobData: DataSettlementJobData,
context: DataWorkerContext,
): Promise<SettlementHandlerResult> {
if (jobData.settlementType === "batch") {
return processBatchSettlement(jobData.data, context);
}
return processPreSignedIndividualSettlement(jobData, context);
}
async function reserveIndividualSettlementNonce(args: {
redis: Redis;
walletClient: {
getTransactionCount(args: { address: `0x${string}`; blockTag: "pending" }): Promise<number>;
};
signerAddress: `0x${string}`;
}): Promise<number> {
const pendingNonce = await args.walletClient.getTransactionCount({
address: args.signerAddress,
blockTag: "pending",
});
const script = `
local key = KEYS[1]
local pending = tonumber(ARGV[1])
local baseline = pending - 1
local current = redis.call("GET", key)
if (not current) or (tonumber(current) < baseline) then
redis.call("SET", key, baseline)
end
return redis.call("INCR", key)
`;
const reserved = await args.redis.eval(
script,
1,
DATA_INDIVIDUAL_SETTLEMENT_NONCE_KEY,
pendingNonce,
);
const nonce = Number(reserved);
if (!Number.isSafeInteger(nonce) || nonce < 0) {
throw new Error(`Invalid reserved individual settlement nonce: ${String(reserved)}`);
}
if (nonce > pendingNonce) {
console.warn("[settlement] Reserved individual nonce is ahead of chain pending nonce", {
reservedNonce: nonce,
pendingNonce,
signerAddress: args.signerAddress,
});
}
return nonce;
}
export function createIndividualSettlementPreparer(): IndividualSettlementPreparer {
const privateKey = process.env[DATA_INDIVIDUAL_WORKER_EVM_PRIVATE_KEY_ENV] as
| `0x${string}`
| undefined;
if (!privateKey) {
throw new Error(`${DATA_INDIVIDUAL_WORKER_EVM_PRIVATE_KEY_ENV} is required`);
}
const settlementContractAddress = (process.env[DATA_WORKER_SETTLEMENT_CONTRACT_ENV] ||
process.env.X402_SETTLEMENT_CONTRACT) as `0x${string}` | undefined;
if (!settlementContractAddress) {
throw new Error(
`${DATA_WORKER_SETTLEMENT_CONTRACT_ENV} (or X402_SETTLEMENT_CONTRACT) is required for individual settlement signing`,
);
}
const account = privateKeyToAccount(privateKey);
const walletClient = createWalletClient({
account,
chain: ogEvm,
transport: http(),
}).extend(publicActions);
const redis = new Redis(createBullMqConnection());
return {
signerAddress: account.address,
close: async () => {
await redis.quit();
},
prepare: async (data: SettlementIndividualData) => {
const walrusPayload = createIndividualWalrusPayload(data);
const walrusBlobId = await computeWalrusBlobId(walrusPayload);
const queueNonce = await reserveIndividualSettlementNonce({
redis,
walletClient,
signerAddress: account.address,
});
const decodedSignatureHex = base64ToBytesCalldata(data.teeSignature);
const calldata = encodeFunctionData({
abi: settlementContractAbi,
functionName: "settleIndividual",
args: [
data.teeId,
toStrictBytes32(data.inputHash, "inputHash"),
toStrictBytes32(data.outputHash, "outputHash"),
BigInt(data.timestamp),
data.ethAddress,
toHex(walrusBlobId),
toBytesCalldata(decodedSignatureHex),
],
});
const signedTransaction = await account.signTransaction({
chainId: ogEvm.id,
to: settlementContractAddress,
data: calldata,
gas: DATA_WORKER_SETTLEMENT_GAS_LIMIT,
maxFeePerGas: parseGwei("0.002"),
maxPriorityFeePerGas: parseGwei("0.001"),
nonce: queueNonce,
type: "eip1559",
});
return {
walrusPayload,
walrusBlobId,
queueNonce,
signerAddress: account.address,
signedTransaction,
txHash: keccak256(signedTransaction),
};
},
};
}
export function createDataWorkerContext(
privateKeyEnvName = DATA_WORKER_EVM_PRIVATE_KEY_ENV,
): DataWorkerContext {
const privateKey = process.env[privateKeyEnvName] as `0x${string}` | undefined;
if (!privateKey) {
throw new Error(`${privateKeyEnvName} is required for data worker`);
}
const settlementContractAddress = (process.env[DATA_WORKER_SETTLEMENT_CONTRACT_ENV] ||
process.env.X402_SETTLEMENT_CONTRACT) as `0x${string}` | undefined;
if (!settlementContractAddress) {
throw new Error(
`${DATA_WORKER_SETTLEMENT_CONTRACT_ENV} (or X402_SETTLEMENT_CONTRACT) is required for data worker`,
);
}
const account = privateKeyToAccount(privateKey);
// OG EVM-only wallet context for data settlement worker.
const ogEvmWalletClient = createWalletClient({
account,
chain: ogEvm,
transport: http(),
}).extend(publicActions);
return {
signerAddress: account.address,
chainId: ogEvm.id,
chainName: ogEvm.name,
settlementContractAddress,
getPendingNonce: () =>
ogEvmWalletClient.getTransactionCount({
address: account.address,
blockTag: "pending",
}),
submitBatchSettlement: async (
merkleRoot: `0x${string}`,
batchSize: number,
walrusBlobId: string,
): Promise<`0x${string}`> => {
let stage: "broadcast" | "receipt" = "broadcast";
try {
const txHash = await ogEvmWalletClient.writeContract({
address: settlementContractAddress,
abi: settlementContractAbi,
functionName: "batchSettle",
args: [merkleRoot, BigInt(batchSize), toHex(walrusBlobId)],
gas: DATA_WORKER_SETTLEMENT_GAS_LIMIT,
maxFeePerGas: parseGwei("0.002"),
maxPriorityFeePerGas: parseGwei("0.001"),
});
stage = "receipt";
const receipt = await withTimeout(
ogEvmWalletClient.waitForTransactionReceipt({ hash: txHash }),
DATA_WORKER_TX_RECEIPT_TIMEOUT_MS,
"Batch settlement receipt wait",
);
if (receipt.status !== "success") {
throw new Error(`Batch settlement transaction reverted: ${txHash}`);
}
return txHash;
} catch (error) {
incrementMetric("data.tx.failure.count", [
"worker:data",
"tx_type:batch",
`stage:${stage}`,
]);
throw error;
}
},
submitIndividualSettlement: async ({
teeId,
inputHash,
outputHash,
timestamp,
ethAddress,
walrusBlobId,
signature,
}): Promise<`0x${string}`> => {
let stage: "broadcast" | "receipt" = "broadcast";
try {
const txHash = await ogEvmWalletClient.writeContract({
address: settlementContractAddress,
abi: settlementContractAbi,
functionName: "settleIndividual",
args: [
teeId,
inputHash,
outputHash,
BigInt(timestamp),
ethAddress,
toHex(walrusBlobId),
toBytesCalldata(signature),
],
gas: DATA_WORKER_SETTLEMENT_GAS_LIMIT,
maxFeePerGas: parseGwei("0.002"),
maxPriorityFeePerGas: parseGwei("0.001"),
});
stage = "receipt";
const receipt = await withTimeout(
ogEvmWalletClient.waitForTransactionReceipt({ hash: txHash }),
DATA_WORKER_TX_RECEIPT_TIMEOUT_MS,
"Individual settlement receipt wait",
);
if (receipt.status !== "success") {
throw new Error(`Individual settlement transaction reverted: ${txHash}`);
}
return txHash;
} catch (error) {
incrementMetric("data.tx.failure.count", [
"worker:data",
"tx_type:individual",
`stage:${stage}`,
]);
throw error;
}
},
sendSignedTransaction: async ({
signedTransaction,
txHash,
txType,
}): Promise<`0x${string}`> => {
let stage: "broadcast" | "receipt" = "broadcast";
try {
let broadcastTxHash = txHash;
try {
broadcastTxHash = await ogEvmWalletClient.sendRawTransaction({
serializedTransaction: signedTransaction,
});
} catch (error) {
if (!isAlreadyKnownRawTransactionError(error)) {
throw error;