@escro/sdk 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,15 +5,139 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
5
5
  // src/client.ts
6
6
  import { Connection as Connection2, PublicKey as PublicKey2 } from "@solana/web3.js";
7
7
 
8
- // src/api.ts
8
+ // ../shared/dist/index.js
9
+ import { createHash } from "crypto";
9
10
  import nacl from "tweetnacl";
10
11
  import bs58 from "bs58";
12
+ import nacl2 from "tweetnacl";
13
+ import bs582 from "bs58";
14
+ var EscrowState = /* @__PURE__ */ ((EscrowState2) => {
15
+ EscrowState2["CREATED"] = "CREATED";
16
+ EscrowState2["FUNDED"] = "FUNDED";
17
+ EscrowState2["IN_PROGRESS"] = "IN_PROGRESS";
18
+ EscrowState2["SUBMITTED"] = "SUBMITTED";
19
+ EscrowState2["COMPLETED"] = "COMPLETED";
20
+ EscrowState2["CANCELLED"] = "CANCELLED";
21
+ EscrowState2["DISPUTED"] = "DISPUTED";
22
+ EscrowState2["REFUNDED"] = "REFUNDED";
23
+ return EscrowState2;
24
+ })(EscrowState || {});
25
+ function canonicalize(value) {
26
+ if (value === null) return "null";
27
+ if (Array.isArray(value)) {
28
+ return "[" + value.map((v) => v === void 0 ? "null" : canonicalize(v)).join(",") + "]";
29
+ }
30
+ if (typeof value === "object") {
31
+ const obj = value;
32
+ const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
33
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalize(obj[k])).join(",") + "}";
34
+ }
35
+ return JSON.stringify(value);
36
+ }
37
+ var PROGRAM_ID_DEVNET = "EjLpJ3obUYk1f2KDensU7UdGBZTxSdxufm7CSnMA3H5C";
38
+ var PROGRAM_ID_MAINNET = "4CwLNRF4mFXutiBGjtMHQBxh8whW8T8EyvJXdRhY1rvr";
39
+ var ONCHAIN_REFUND_GRACE_SECONDS = 900;
40
+ var ONCHAIN_TIMEOUT_SECONDS = 86400;
41
+ var CLOCK_SKEW_SECONDS = 60;
42
+ var SCANNER_REFUND_GRACE_SECONDS = ONCHAIN_REFUND_GRACE_SECONDS + CLOCK_SKEW_SECONDS;
43
+ var SCANNER_TIMEOUT_SECONDS = ONCHAIN_TIMEOUT_SECONDS + CLOCK_SKEW_SECONDS;
44
+ var MAINNET_PROGRAM_ID_PLACEHOLDER = "11111111111111111111111111111111";
45
+ function getProgramId(cluster) {
46
+ return cluster === "mainnet" ? PROGRAM_ID_MAINNET : PROGRAM_ID_DEVNET;
47
+ }
48
+ function isPlaceholderProgramId(id) {
49
+ return id === MAINNET_PROGRAM_ID_PLACEHOLDER;
50
+ }
51
+ function assertProgramIdNotPlaceholder(id, cluster) {
52
+ if (cluster === "mainnet" && isPlaceholderProgramId(id)) {
53
+ throw new Error(
54
+ `PROGRAM_ID_MAINNET is still the System Program placeholder (${MAINNET_PROGRAM_ID_PLACEHOLDER}). Run scripts/deploy-mainnet.sh to bootstrap mainnet, then update the placeholder in packages/shared/src/config.ts, packages/program/programs/escro/src/lib.rs, packages/program/Anchor.toml, and infra/bin/escro.ts.`
55
+ );
56
+ }
57
+ }
58
+ function hashBody(rawBody) {
59
+ return createHash("sha256").update(rawBody, "utf8").digest("hex");
60
+ }
61
+ function buildSignedMessage(timestamp, method, fullPath, bodyHash) {
62
+ return `escro:${String(timestamp)}:${method}:${fullPath}:${bodyHash}`;
63
+ }
64
+ function signRequestRaw(secretKey, walletAddress, method, fullPath, rawBody) {
65
+ const timestamp = Date.now();
66
+ const bodyHash = hashBody(rawBody);
67
+ const message = buildSignedMessage(timestamp, method, fullPath, bodyHash);
68
+ const sigBytes = nacl.sign.detached(new TextEncoder().encode(message), secretKey);
69
+ return {
70
+ "x-wallet-address": walletAddress,
71
+ "x-signature": bs58.encode(sigBytes),
72
+ "x-timestamp": String(timestamp),
73
+ "x-content-sha256": bodyHash
74
+ };
75
+ }
76
+ function signRequest(wallet, method, fullPath, rawBody) {
77
+ return signRequestRaw(wallet.secretKey, wallet.publicKey.toBase58(), method, fullPath, rawBody);
78
+ }
79
+ function canonicalBotDescriptorMessage(descriptor) {
80
+ return canonicalize({
81
+ wallet: descriptor.wallet,
82
+ role: descriptor.role,
83
+ capabilities: descriptor.capabilities,
84
+ serviceRef: descriptor.serviceRef,
85
+ pricingHint: descriptor.pricingHint,
86
+ endpoint: descriptor.endpoint,
87
+ signedAt: descriptor.signedAt
88
+ });
89
+ }
90
+ function verifyBotDescriptorSignature(descriptor) {
91
+ try {
92
+ const { signature, ...unsigned } = descriptor;
93
+ const message = new TextEncoder().encode(canonicalBotDescriptorMessage(unsigned));
94
+ const signatureBytes = bs582.decode(signature);
95
+ if (signatureBytes.length !== 64) return false;
96
+ const pubkeyBytes = bs582.decode(descriptor.wallet);
97
+ if (pubkeyBytes.length !== 32) return false;
98
+ return nacl2.sign.detached.verify(message, signatureBytes, pubkeyBytes);
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
103
+ function spec(discriminator, escrowAccountIndex, cause) {
104
+ return {
105
+ discriminator: Uint8Array.from(discriminator),
106
+ escrowAccountIndex,
107
+ signerAccountIndex: 0,
108
+ cause
109
+ };
110
+ }
111
+ var ESCROW_INSTRUCTIONS = {
112
+ create_escrow: spec([253, 215, 165, 116, 36, 108, 68, 80], 4, null),
113
+ claim_task: spec([49, 222, 219, 238, 155, 68, 221, 136], 1, null),
114
+ submit_deliverable: spec([38, 137, 64, 44, 237, 11, 125, 101], 1, null),
115
+ raise_dispute: spec([41, 243, 1, 51, 150, 95, 246, 73], 1, null),
116
+ cancel_escrow: spec([156, 203, 54, 179, 38, 72, 33, 21], 3, "CANCELLED"),
117
+ release_payment: spec([24, 34, 191, 86, 145, 160, 183, 233], 3, "EXPLICIT_RELEASE"),
118
+ timeout_release: spec([98, 176, 26, 12, 83, 105, 154, 68], 3, "TIMEOUT_RELEASE"),
119
+ refund_buyer: spec([199, 139, 203, 146, 192, 150, 53, 218], 3, "DEADLINE_REFUND"),
120
+ arbitration_release: spec([118, 157, 141, 26, 104, 117, 94, 229], 4, "ARBITRATION_RELEASE"),
121
+ arbitration_refund: spec([255, 194, 84, 248, 185, 249, 120, 122], 4, "ARBITRATION_REFUND")
122
+ };
123
+
124
+ // src/payments.ts
125
+ var RAILS = ["escrow", "x402"];
126
+ var ENABLED_RAILS = ["escrow"];
127
+ var RAILS_DOCS_URL = "https://docs.escro.ai/rails";
128
+ var EscrowPaymentRouter = class {
129
+ selectRail(tx) {
130
+ const preferred = tx.mode === "sync" ? "x402" : "escrow";
131
+ return ENABLED_RAILS.includes(preferred) ? preferred : "escrow";
132
+ }
133
+ };
11
134
 
12
135
  // src/errors.ts
13
136
  var EscroError = class extends Error {
14
- constructor(message, code = "ESCRO_ERROR") {
137
+ constructor(message, code = "ESCRO_ERROR", retryAfterMs2) {
15
138
  super(message);
16
- this.code = code;
139
+ __publicField(this, "code", code);
140
+ __publicField(this, "retryAfterMs", retryAfterMs2);
17
141
  this.name = "EscroError";
18
142
  }
19
143
  };
@@ -23,6 +147,15 @@ var EscrowNotFoundError = class extends EscroError {
23
147
  this.name = "EscrowNotFoundError";
24
148
  }
25
149
  };
150
+ var ReputationUnavailableError = class extends EscroError {
151
+ constructor() {
152
+ super(
153
+ "Reputation endpoint is unavailable (HTTP 404): this deployment has no reputation source mounted.",
154
+ "REPUTATION_UNAVAILABLE"
155
+ );
156
+ this.name = "ReputationUnavailableError";
157
+ }
158
+ };
26
159
  var EscrowStateError = class extends EscroError {
27
160
  constructor(message) {
28
161
  super(message, "ESCROW_INVALID_STATE");
@@ -35,40 +168,58 @@ var EscrowTimeoutError = class extends EscroError {
35
168
  this.name = "EscrowTimeoutError";
36
169
  }
37
170
  };
171
+ var EscroConfirmError = class extends EscroError {
172
+ constructor(address, signature, code, message) {
173
+ super(`Confirm failed for escrow ${address} (signature ${signature}): ${message}`, code);
174
+ __publicField(this, "address", address);
175
+ __publicField(this, "signature", signature);
176
+ this.name = "EscroConfirmError";
177
+ }
178
+ };
38
179
  var UnauthorizedError = class extends EscroError {
39
180
  constructor(message = "Unauthorized") {
40
181
  super(message, "UNAUTHORIZED");
41
182
  this.name = "UnauthorizedError";
42
183
  }
43
184
  };
185
+ var EscroRailNotEnabledError = class extends EscroError {
186
+ constructor(rail) {
187
+ super(
188
+ `Payment rail "${rail}" is not enabled. Only the escrow rail is available today; the x402 rail is reserved and lands in Phase 9. See ${RAILS_DOCS_URL}`,
189
+ "ESCRO_RAIL_NOT_ENABLED"
190
+ );
191
+ __publicField(this, "rail", rail);
192
+ this.name = "EscroRailNotEnabledError";
193
+ }
194
+ };
44
195
 
45
196
  // src/api.ts
46
- function authHeaders(wallet, method, path) {
47
- const timestamp = Date.now();
48
- const message = `escro:${timestamp}:${method}:${path}`;
49
- const msgBytes = new TextEncoder().encode(message);
50
- const sigBytes = nacl.sign.detached(msgBytes, wallet.secretKey);
51
- return {
52
- "x-wallet-address": wallet.publicKey.toBase58(),
53
- "x-signature": bs58.encode(sigBytes),
54
- "x-timestamp": String(timestamp)
55
- };
197
+ function authHeaders(wallet, method, path, rawBody = "") {
198
+ return signRequest(wallet, method, path, rawBody);
56
199
  }
57
200
  function deserialize(raw) {
58
201
  return { ...raw, amount: BigInt(raw.amount) };
59
202
  }
60
203
  async function handleError(res, address) {
61
204
  const body = await res.json().catch(() => ({}));
62
- const msg = body.error ?? `HTTP ${res.status}`;
205
+ const msg = body.error ?? `HTTP ${String(res.status)}`;
63
206
  if (res.status === 404) throw new EscrowNotFoundError(address ?? msg);
64
207
  if (res.status === 409) throw new EscrowStateError(msg);
65
208
  if (res.status === 401 || res.status === 403) throw new UnauthorizedError(msg);
66
- throw new EscroError(msg, body.code ?? "UNKNOWN");
209
+ throw new EscroError(msg, body.code ?? "UNKNOWN", retryAfterMs(res.headers.get("retry-after")));
210
+ }
211
+ function retryAfterMs(header) {
212
+ return header !== null && /^\d+$/.test(header.trim()) ? Number(header.trim()) * 1e3 : void 0;
67
213
  }
68
214
  var ApiClient = class {
69
215
  constructor(baseUrl, wallet) {
70
- this.baseUrl = baseUrl;
71
- this.wallet = wallet;
216
+ __publicField(this, "baseUrl", baseUrl);
217
+ __publicField(this, "wallet", wallet);
218
+ const url = new URL(baseUrl);
219
+ const isLocalhost = url.hostname === "localhost" || url.hostname === "127.0.0.1";
220
+ if (url.protocol !== "https:" && !isLocalhost) {
221
+ throw new Error("apiUrl must use HTTPS in production");
222
+ }
72
223
  }
73
224
  url(path) {
74
225
  return `${this.baseUrl}${path}`;
@@ -80,10 +231,11 @@ var ApiClient = class {
80
231
  if (!res.ok) await handleError(res, address);
81
232
  return deserialize(await res.json());
82
233
  }
83
- /** GET /v1/escrows?assignedTo=...&state=... */
234
+ /** GET /v1/escrows?assignedTo=...&maker=...&state=... */
84
235
  async listEscrows(params) {
85
236
  const qs = new URLSearchParams();
86
237
  if (params.assignedTo) qs.set("assignedTo", params.assignedTo);
238
+ if (params.maker) qs.set("maker", params.maker);
87
239
  if (params.state) qs.set("state", params.state);
88
240
  if (params.limit != null) qs.set("limit", String(params.limit));
89
241
  if (params.offset != null) qs.set("offset", String(params.offset));
@@ -98,21 +250,77 @@ var ApiClient = class {
98
250
  offset: body.offset
99
251
  };
100
252
  }
253
+ /**
254
+ * GET /v1/bots?capability=...&role=...&limit=...&offset= : EscroBots registry
255
+ * read. Unauthenticated public read (no auth headers). Returns descriptors in
256
+ * registry order (newest first); descriptors are self-reported claims.
257
+ */
258
+ async listBots(params) {
259
+ const qs = new URLSearchParams();
260
+ if (params.capability != null) qs.set("capability", params.capability);
261
+ if (params.role != null) qs.set("role", params.role);
262
+ if (params.limit != null) qs.set("limit", String(params.limit));
263
+ if (params.offset != null) qs.set("offset", String(params.offset));
264
+ const path = `/v1/bots?${qs.toString()}`;
265
+ const res = await fetch(this.url(path));
266
+ if (!res.ok) await handleError(res);
267
+ const body = await res.json();
268
+ return { items: body.items, total: body.total, limit: body.limit, offset: body.offset };
269
+ }
270
+ /**
271
+ * GET /rep : EscroRep bulk export (ARCHITECTURE §9). Unauthenticated public
272
+ * read (no auth headers). Returns every indexed wallet's RAW components exactly
273
+ * once (no composite score). Ranking layers join against this ONE bulk fetch:
274
+ * the per-wallet endpoint shares a 10/min public-metrics budget, so a
275
+ * per-candidate fan-out would rate-limit itself. A 404 means the deployment
276
+ * mounted no reputation source (unknown wallets return zeroed rep, never 404),
277
+ * so it surfaces as {@link ReputationUnavailableError}, not EscrowNotFoundError.
278
+ */
279
+ async listReputations() {
280
+ const res = await fetch(this.url("/rep"));
281
+ if (!res.ok) {
282
+ if (res.status === 404) throw new ReputationUnavailableError();
283
+ await handleError(res);
284
+ }
285
+ const body = await res.json();
286
+ return body.wallets;
287
+ }
288
+ /**
289
+ * GET /rep/:wallet : one wallet's EscroRep RAW components (ARCHITECTURE §9).
290
+ * Unauthenticated public read (no auth headers). Unknown wallets return zeroed
291
+ * components, never 404; a 404 means the deployment mounted no reputation
292
+ * source and surfaces as {@link ReputationUnavailableError}. Shares the public
293
+ * per-wallet rate budget with every other caller, so fan-outs should use
294
+ * {@link listReputations} instead.
295
+ */
296
+ async getReputation(wallet) {
297
+ const res = await fetch(this.url(`/rep/${encodeURIComponent(wallet)}`));
298
+ if (!res.ok) {
299
+ if (res.status === 404) throw new ReputationUnavailableError();
300
+ await handleError(res);
301
+ }
302
+ return await res.json();
303
+ }
101
304
  /**
102
305
  * POST /v1/escrows — create escrow, returns unsigned tx + ids.
103
306
  * Requires auth.
104
307
  */
105
308
  async createEscrow(params) {
106
309
  const path = "/v1/escrows";
310
+ const bodyObj = {
311
+ taskSpec: params.taskSpec,
312
+ amountUsdc: params.amountUsdc,
313
+ deadlineUnix: params.deadlineUnix,
314
+ assignedWorker: params.assignedWorker
315
+ };
316
+ const rawBody = JSON.stringify(bodyObj);
107
317
  const res = await fetch(this.url(path), {
108
318
  method: "POST",
109
- headers: { ...authHeaders(this.wallet, "POST", path), "content-type": "application/json" },
110
- body: JSON.stringify({
111
- taskSpec: params.taskSpec,
112
- amountUsdc: params.amountUsdc,
113
- deadlineSeconds: params.deadlineSeconds,
114
- assignedWorker: params.assignedWorker
115
- })
319
+ headers: {
320
+ ...authHeaders(this.wallet, "POST", path, rawBody),
321
+ "content-type": "application/json"
322
+ },
323
+ body: rawBody
116
324
  });
117
325
  if (!res.ok) await handleError(res);
118
326
  return res.json();
@@ -136,13 +344,17 @@ var ApiClient = class {
136
344
  */
137
345
  async submitDeliverable(address, params) {
138
346
  const path = `/v1/escrows/${address}/submit`;
347
+ const rawBody = JSON.stringify({
348
+ contentHash: params.contentHash,
349
+ proofUri: params.proofUri
350
+ });
139
351
  const res = await fetch(this.url(path), {
140
352
  method: "POST",
141
- headers: { ...authHeaders(this.wallet, "POST", path), "content-type": "application/json" },
142
- body: JSON.stringify({
143
- contentHash: params.contentHash,
144
- proofUri: params.proofUri
145
- })
353
+ headers: {
354
+ ...authHeaders(this.wallet, "POST", path, rawBody),
355
+ "content-type": "application/json"
356
+ },
357
+ body: rawBody
146
358
  });
147
359
  if (!res.ok) await handleError(res, address);
148
360
  return res.json();
@@ -178,14 +390,58 @@ var ApiClient = class {
178
390
  */
179
391
  async raiseDispute(address, params) {
180
392
  const path = `/v1/escrows/${address}/dispute`;
393
+ const rawBody = JSON.stringify({ reason: params.reason });
181
394
  const res = await fetch(this.url(path), {
182
395
  method: "POST",
183
- headers: { ...authHeaders(this.wallet, "POST", path), "content-type": "application/json" },
184
- body: JSON.stringify({ reason: params.reason, evidence: params.evidence })
396
+ headers: {
397
+ ...authHeaders(this.wallet, "POST", path, rawBody),
398
+ "content-type": "application/json"
399
+ },
400
+ body: rawBody
185
401
  });
186
402
  if (!res.ok) await handleError(res, address);
187
403
  return res.json();
188
404
  }
405
+ /**
406
+ * POST /v1/escrows/:address/confirm: the API records the create, claim, submit,
407
+ * cancel or dispute the landed `signature` carries, after verifying it on chain.
408
+ * A non-2xx answer throws an {@link EscroError} with the server's code, or
409
+ * `HTTP_<status>` when the answer carries none; a network failure rejects with
410
+ * fetch's own error. {@link Escro.confirm} decides which to retry.
411
+ */
412
+ async confirm(address, signature, evidence) {
413
+ const path = `/v1/escrows/${address}/confirm`;
414
+ const rawBody = JSON.stringify({ signature, evidence });
415
+ const res = await fetch(this.url(path), {
416
+ method: "POST",
417
+ headers: {
418
+ ...authHeaders(this.wallet, "POST", path, rawBody),
419
+ "content-type": "application/json"
420
+ },
421
+ body: rawBody
422
+ });
423
+ if (!res.ok) {
424
+ const body2 = await res.json().catch(() => ({}));
425
+ throw new EscroError(
426
+ body2.error ?? `HTTP ${String(res.status)}`,
427
+ body2.code ?? `HTTP_${String(res.status)}`,
428
+ retryAfterMs(res.headers.get("retry-after"))
429
+ );
430
+ }
431
+ const body = await res.json();
432
+ return deserialize(body.escrow);
433
+ }
434
+ /**
435
+ * GET /v1/stats — public protocol-wide stats.
436
+ * No auth required. Upstream typing in {@link Escro.getStats} narrows the
437
+ * return shape.
438
+ */
439
+ async getStats() {
440
+ const path = "/v1/stats";
441
+ const res = await fetch(this.url(path));
442
+ if (!res.ok) await handleError(res);
443
+ return res.json();
444
+ }
189
445
  };
190
446
 
191
447
  // src/poll.ts
@@ -202,7 +458,7 @@ function sleep(ms) {
202
458
  }
203
459
  async function pollUntil(address, fetcher, predicate, timeoutMs = MS_24_H) {
204
460
  const deadline = Date.now() + timeoutMs;
205
- while (true) {
461
+ for (; ; ) {
206
462
  const result = await fetcher();
207
463
  if (predicate(result)) return result;
208
464
  const elapsed = Date.now() - (deadline - timeoutMs);
@@ -219,8 +475,9 @@ async function pollUntil(address, fetcher, predicate, timeoutMs = MS_24_H) {
219
475
  }
220
476
 
221
477
  // src/solana.ts
222
- import { createHash } from "crypto";
478
+ import { createHash as createHash2 } from "crypto";
223
479
  import {
480
+ ComputeBudgetProgram,
224
481
  PublicKey,
225
482
  Transaction,
226
483
  TransactionInstruction
@@ -229,41 +486,111 @@ import {
229
486
  TOKEN_PROGRAM_ID,
230
487
  ASSOCIATED_TOKEN_PROGRAM_ID,
231
488
  getAssociatedTokenAddressSync,
232
- createAssociatedTokenAccountInstruction
489
+ createAssociatedTokenAccountIdempotentInstruction
233
490
  } from "@solana/spl-token";
234
491
  function disc(name) {
235
- return Buffer.from(
236
- createHash("sha256").update(`global:${name}`).digest()
237
- ).subarray(0, 8);
492
+ return Buffer.from(createHash2("sha256").update(`global:${name}`).digest()).subarray(0, 8);
238
493
  }
239
494
  var DISC_RELEASE_PAYMENT = disc("release_payment");
240
- var PROGRAM_ID = new PublicKey("EjLpJ3obUYk1f2KDensU7UdGBZTxSdxufm7CSnMA3H5C");
241
- async function fetchPlatformConfig(connection) {
242
- const [pda] = PublicKey.findProgramAddressSync([Buffer.from("config")], PROGRAM_ID);
495
+ function resolveProgramId(cluster) {
496
+ const id = getProgramId(cluster);
497
+ assertProgramIdNotPlaceholder(id, cluster);
498
+ return new PublicKey(id);
499
+ }
500
+ function allowedProgramIds(programId) {
501
+ return /* @__PURE__ */ new Set([
502
+ programId.toBase58(),
503
+ TOKEN_PROGRAM_ID.toBase58(),
504
+ ASSOCIATED_TOKEN_PROGRAM_ID.toBase58(),
505
+ ComputeBudgetProgram.programId.toBase58()
506
+ ]);
507
+ }
508
+ var MAX_INSTRUCTIONS = 6;
509
+ var FORBIDDEN_TOKEN_IX_TAGS = /* @__PURE__ */ new Set([
510
+ 3,
511
+ // Transfer
512
+ 4,
513
+ // Approve
514
+ 6,
515
+ // SetAuthority
516
+ 7,
517
+ // MintTo
518
+ 8,
519
+ // Burn
520
+ 9,
521
+ // CloseAccount
522
+ 12,
523
+ // TransferChecked
524
+ 13,
525
+ // ApproveChecked
526
+ 14,
527
+ // MintToChecked
528
+ 15
529
+ // BurnChecked
530
+ ]);
531
+ var EXPECTED_PLATFORM_CONFIG_VERSION = 1;
532
+ var VERSION_OFFSET = 8;
533
+ var MINT_OFFSET = 43;
534
+ var TREASURY_OFFSET = 75;
535
+ async function fetchPlatformConfig(connection, cluster) {
536
+ const programId = resolveProgramId(cluster);
537
+ const [pda] = PublicKey.findProgramAddressSync([Buffer.from("config")], programId);
243
538
  const info = await connection.getAccountInfo(pda);
244
539
  if (!info) throw new Error("PlatformConfig account not found on-chain");
540
+ const version = info.data[VERSION_OFFSET];
541
+ if (version !== EXPECTED_PLATFORM_CONFIG_VERSION) {
542
+ throw new Error(
543
+ `PlatformConfig version mismatch: expected ${String(EXPECTED_PLATFORM_CONFIG_VERSION)}, got ${String(version)}`
544
+ );
545
+ }
245
546
  return {
246
- mint: new PublicKey(info.data.slice(42, 74)),
247
- treasury: new PublicKey(info.data.slice(74, 106))
547
+ mint: new PublicKey(info.data.subarray(MINT_OFFSET, MINT_OFFSET + 32)),
548
+ treasury: new PublicKey(info.data.subarray(TREASURY_OFFSET, TREASURY_OFFSET + 32))
248
549
  };
249
550
  }
250
- async function signAndSend(base64Tx, wallet, connection) {
551
+ function validateTransaction(tx, cluster) {
552
+ const programId = resolveProgramId(cluster);
553
+ const allowed = allowedProgramIds(programId);
554
+ const tokenProgram = TOKEN_PROGRAM_ID.toBase58();
555
+ for (const ix of tx.instructions) {
556
+ const id = ix.programId.toBase58();
557
+ if (!allowed.has(id)) {
558
+ throw new Error(
559
+ `Unexpected program in transaction: ${id}. Allowed: ${[...allowed].join(", ")}`
560
+ );
561
+ }
562
+ if (id === tokenProgram) {
563
+ const tag = ix.data.length > 0 ? ix.data[0] : void 0;
564
+ if (tag !== void 0 && FORBIDDEN_TOKEN_IX_TAGS.has(tag)) {
565
+ throw new Error(
566
+ `Refusing to sign a fund-moving SPL Token instruction (tag ${String(tag)}) in a server-built transaction. Escro never requires the wallet to directly sign a token transfer/approve/burn/close; all token movement is a CPI inside the escro program.`
567
+ );
568
+ }
569
+ }
570
+ }
571
+ if (tx.instructions.length > MAX_INSTRUCTIONS) {
572
+ throw new Error(
573
+ `Too many instructions (${String(tx.instructions.length)}). Max allowed: ${String(MAX_INSTRUCTIONS)}`
574
+ );
575
+ }
576
+ }
577
+ async function signAndSend(base64Tx, wallet, connection, cluster) {
251
578
  const buf = Buffer.from(base64Tx, "base64");
252
579
  const tx = Transaction.from(buf);
580
+ validateTransaction(tx, cluster);
253
581
  tx.partialSign(wallet);
254
582
  const raw = tx.serialize();
583
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash("confirmed");
255
584
  const signature = await connection.sendRawTransaction(raw, {
256
585
  skipPreflight: false
257
586
  });
258
- await connection.confirmTransaction(signature, "confirmed");
587
+ await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, "confirmed");
259
588
  return signature;
260
589
  }
261
590
  async function buildReleasePaymentTx(params) {
262
- const { buyer, escrowPda, worker, mint, treasury, connection } = params;
263
- const [platformConfig] = PublicKey.findProgramAddressSync(
264
- [Buffer.from("config")],
265
- PROGRAM_ID
266
- );
591
+ const { buyer, escrowPda, worker, mint, treasury, connection, cluster } = params;
592
+ const programId = resolveProgramId(cluster);
593
+ const [platformConfig] = PublicKey.findProgramAddressSync([Buffer.from("config")], programId);
267
594
  const vault = getAssociatedTokenAddressSync(
268
595
  mint,
269
596
  escrowPda,
@@ -281,16 +608,12 @@ async function buildReleasePaymentTx(params) {
281
608
  const treasuryAta = getAssociatedTokenAddressSync(
282
609
  mint,
283
610
  treasury,
284
- false,
611
+ true,
285
612
  TOKEN_PROGRAM_ID,
286
613
  ASSOCIATED_TOKEN_PROGRAM_ID
287
614
  );
288
- const [workerAtaInfo, treasuryAtaInfo] = await connection.getMultipleAccountsInfo([
289
- workerAta,
290
- treasuryAta
291
- ]);
292
615
  const ix = new TransactionInstruction({
293
- programId: PROGRAM_ID,
616
+ programId,
294
617
  keys: [
295
618
  { pubkey: buyer, isSigner: true, isWritable: true },
296
619
  { pubkey: platformConfig, isSigner: false, isWritable: false },
@@ -310,45 +633,67 @@ async function buildReleasePaymentTx(params) {
310
633
  const tx = new Transaction();
311
634
  tx.recentBlockhash = blockhash;
312
635
  tx.feePayer = buyer;
313
- if (!workerAtaInfo) {
314
- tx.add(
315
- createAssociatedTokenAccountInstruction(buyer, workerAta, worker, mint)
316
- );
317
- }
318
- if (!treasuryAtaInfo) {
319
- tx.add(
320
- createAssociatedTokenAccountInstruction(buyer, treasuryAta, treasury, mint)
321
- );
322
- }
636
+ tx.add(createAssociatedTokenAccountIdempotentInstruction(buyer, workerAta, worker, mint));
637
+ tx.add(createAssociatedTokenAccountIdempotentInstruction(buyer, treasuryAta, treasury, mint));
323
638
  tx.add(ix);
324
639
  return tx.serialize({ requireAllSignatures: false }).toString("base64");
325
640
  }
326
641
 
327
642
  // src/client.ts
643
+ var CONFIRM_WINDOW_MS = 3e4;
644
+ var CONFIRM_FIRST_DELAY_MS = 500;
645
+ var CONFIRM_MAX_DELAY_MS = 4e3;
646
+ var RETRYABLE_CONFIRM_CODES = [
647
+ "TX_NOT_FOUND",
648
+ "RPC_UNAVAILABLE",
649
+ "HTTP_502",
650
+ "HTTP_503",
651
+ "HTTP_504",
652
+ "RATE_LIMITED",
653
+ "HTTP_429"
654
+ ];
655
+ function isRetryableConfirmCode(code) {
656
+ return RETRYABLE_CONFIRM_CODES.includes(code);
657
+ }
658
+ function isUrl(value) {
659
+ try {
660
+ new URL(value);
661
+ return true;
662
+ } catch {
663
+ return false;
664
+ }
665
+ }
666
+ var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
328
667
  var Escro = class {
329
668
  constructor(options) {
330
669
  __publicField(this, "connection");
331
670
  __publicField(this, "api");
332
671
  __publicField(this, "options");
672
+ __publicField(this, "cluster");
673
+ __publicField(this, "router", new EscrowPaymentRouter());
333
674
  this.options = options;
675
+ this.cluster = options.cluster;
334
676
  this.connection = new Connection2(options.rpcUrl, "confirmed");
335
677
  this.api = new ApiClient(options.apiUrl, options.wallet);
336
678
  }
337
679
  // ── Buyer Bot ────────────────────────────────────────────────────────────────
338
680
  /**
339
681
  * Create a new escrow: registers with the API, signs and submits the
340
- * on-chain `create_escrow` transaction.
682
+ * on-chain `create_escrow` transaction, then confirms it with the API.
341
683
  *
342
684
  * @returns `{ escrowId, escrowPda, signature }` — use `escrowPda` for all subsequent calls.
343
685
  */
344
686
  async createEscrow(params) {
345
687
  const { escrowId, escrowPda, unsignedTx } = await this.api.createEscrow(params);
346
- const signature = await signAndSend(unsignedTx, this.options.wallet, this.connection);
688
+ const signature = await this.send(unsignedTx);
689
+ await this.confirm(escrowPda, signature);
347
690
  return { escrowId, escrowPda, signature };
348
691
  }
349
692
  /**
350
693
  * Release payment to the worker. Buyer must be the wallet in the constructor.
351
- * Updates API DB state, then builds and submits the `release_payment` on-chain tx.
694
+ * Builds and submits the `release_payment` on-chain tx FIRST (the chain is the
695
+ * source of truth), then confirms DB state. The DB confirmation is best-effort:
696
+ * the oracle sweep reconciles it if it fails.
352
697
  *
353
698
  * @returns Solana transaction signature.
354
699
  */
@@ -357,59 +702,96 @@ var Escro = class {
357
702
  if (!escrow.taker) {
358
703
  throw new EscrowNotFoundError(`Escrow ${address} has no assigned worker`);
359
704
  }
360
- const { treasury, mint } = await fetchPlatformConfig(this.connection);
361
- await this.api.releasePaymentDb(address);
705
+ const { treasury, mint } = await fetchPlatformConfig(this.connection, this.cluster);
362
706
  const unsignedTx = await buildReleasePaymentTx({
363
707
  buyer: this.options.wallet.publicKey,
364
708
  escrowPda: new PublicKey2(address),
365
709
  worker: new PublicKey2(escrow.taker),
366
710
  mint,
367
711
  treasury,
368
- connection: this.connection
712
+ connection: this.connection,
713
+ cluster: this.cluster
369
714
  });
370
- return signAndSend(unsignedTx, this.options.wallet, this.connection);
715
+ const signature = await signAndSend(
716
+ unsignedTx,
717
+ this.options.wallet,
718
+ this.connection,
719
+ this.cluster
720
+ );
721
+ try {
722
+ await this.api.releasePaymentDb(address);
723
+ } catch {
724
+ }
725
+ return signature;
371
726
  }
372
727
  /**
373
728
  * Raise a dispute for an escrow. Either the buyer or the assigned worker
374
- * may call this. Signs and submits the `raise_dispute` on-chain tx.
729
+ * may call this. Signs and submits the `raise_dispute` on-chain tx, then confirms it with the API.
375
730
  *
376
731
  * @returns Solana transaction signature.
377
732
  */
378
733
  async raiseDispute(address, params) {
379
- const { unsignedTx } = await this.api.raiseDispute(address, params);
380
- return signAndSend(unsignedTx, this.options.wallet, this.connection);
734
+ if (params.evidence !== void 0 && !isUrl(params.evidence)) {
735
+ throw new EscroError(`evidence must be a URL: ${params.evidence}`, "VALIDATION_ERROR");
736
+ }
737
+ const { unsignedTx } = await this.api.raiseDispute(address, { reason: params.reason });
738
+ const signature = await this.send(unsignedTx);
739
+ await this.confirm(address, signature, {
740
+ ...params.evidence !== void 0 && { evidence: params.evidence }
741
+ });
742
+ return signature;
381
743
  }
382
744
  /**
383
745
  * Cancel a funded escrow before any worker has claimed it.
384
746
  * Buyer must be the wallet in the constructor. Only valid when state is `FUNDED`.
385
- * Signs and submits the `cancel_escrow` on-chain tx; full USDC refund to buyer.
747
+ * Signs and submits the `cancel_escrow` on-chain tx, then confirms it with the API; full USDC refund to buyer.
386
748
  *
387
749
  * @returns Solana transaction signature.
388
750
  */
389
751
  async cancelEscrow(address) {
390
752
  const { unsignedTx } = await this.api.cancelEscrow(address);
391
- return signAndSend(unsignedTx, this.options.wallet, this.connection);
753
+ return this.sendAndConfirm(address, unsignedTx);
754
+ }
755
+ // ── Payments (dual-path; x402 reserved) ───────────────────────────────────────
756
+ /**
757
+ * Reserved synchronous-payment entrypoint (ARCHITECTURE §7a). `pay()` settles
758
+ * over the x402 rail, which is not implemented until Phase 9; today it rejects
759
+ * with {@link EscroRailNotEnabledError}. The signature is FROZEN so enabling
760
+ * x402 later is not a breaking change for kit-generated bots. For asynchronous,
761
+ * verification-needed work use {@link createEscrow}, the core product.
762
+ *
763
+ * Not `async`: it returns a rejected promise (never awaits) so callers can
764
+ * `await`/`.catch()` it uniformly, and it exercises the same {@link PaymentRouter}
765
+ * routing seam Phase 9 will implement.
766
+ */
767
+ pay(params) {
768
+ const rail = this.router.selectRail({
769
+ to: params.to,
770
+ amountMicroUsdc: params.amountMicroUsdc,
771
+ mode: "sync"
772
+ });
773
+ return Promise.reject(new EscroRailNotEnabledError(rail === "escrow" ? "x402" : rail));
392
774
  }
393
775
  // ── Worker Bot ───────────────────────────────────────────────────────────────
394
776
  /**
395
777
  * Claim an assigned task. Worker must be the wallet in the constructor.
396
- * Signs and submits the `claim_task` on-chain tx.
778
+ * Signs and submits the `claim_task` on-chain tx, then confirms it with the API.
397
779
  *
398
780
  * @returns Solana transaction signature.
399
781
  */
400
782
  async claimTask(address) {
401
783
  const { unsignedTx } = await this.api.claimTask(address);
402
- return signAndSend(unsignedTx, this.options.wallet, this.connection);
784
+ return this.sendAndConfirm(address, unsignedTx);
403
785
  }
404
786
  /**
405
- * Submit a deliverable for oracle evaluation. Worker must be the wallet.
406
- * Signs and submits the `submit_deliverable` on-chain tx.
787
+ * Submit a deliverable for the buyer to review. Worker must be the wallet.
788
+ * Signs and submits the `submit_deliverable` on-chain tx, then confirms it with the API.
407
789
  *
408
790
  * @returns Solana transaction signature.
409
791
  */
410
792
  async submitDeliverable(address, params) {
411
793
  const { unsignedTx } = await this.api.submitDeliverable(address, params);
412
- return signAndSend(unsignedTx, this.options.wallet, this.connection);
794
+ return this.sendAndConfirm(address, unsignedTx);
413
795
  }
414
796
  /**
415
797
  * List tasks assigned to the wallet's public key.
@@ -440,7 +822,130 @@ var Escro = class {
440
822
  options.timeoutMs
441
823
  );
442
824
  }
825
+ /**
826
+ * List escrows CREATED by the wallet's public key (the maker / buyer), the
827
+ * mirror of {@link getMyTasks} for the buyer side. Optionally filter by state
828
+ * and paginate.
829
+ *
830
+ * A Buyer Bot uses this to sum its own outstanding (still-locked) escrows for
831
+ * the client-side spend cap: the program is the source of truth, so the total
832
+ * is read from chain state (via the API), never a local tally a crash could lose.
833
+ *
834
+ * @param state - Filter by one or more states (first state used as API filter).
835
+ * @param options - Polling, pagination (limit/offset).
836
+ */
837
+ async getMyEscrows(state, options) {
838
+ const maker = this.options.wallet.publicKey.toBase58();
839
+ const params = {
840
+ maker,
841
+ ...state?.[0] != null && { state: state[0] },
842
+ ...options?.limit != null && { limit: options.limit },
843
+ ...options?.offset != null && { offset: options.offset }
844
+ };
845
+ if (!options?.poll) {
846
+ return this.api.listEscrows(params);
847
+ }
848
+ const fetcher = () => this.api.listEscrows(params).then((result) => result.items.length > 0 ? result : null);
849
+ return pollUntil(
850
+ maker,
851
+ fetcher,
852
+ (r) => r !== null,
853
+ options.timeoutMs
854
+ );
855
+ }
856
+ // ── EscroBots discovery ──────────────────────────────────────────────────────
857
+ /**
858
+ * Find worker bots in the EscroBots registry, optionally filtered by
859
+ * capability. Queries `GET /v1/bots?role=worker` (the API includes `both`
860
+ * bots) and returns candidates in REGISTRY ORDER: this method does no
861
+ * ranking, scoring, or reordering (ARCHITECTURE §8: no curation; §13: not a
862
+ * marketplace). Escro-shipped code never ranks; the caller's own bot decides.
863
+ *
864
+ * Each candidate keeps the CLAIM (`descriptor`) separate from the AUTHORSHIP
865
+ * check (`signatureValid`, verified locally so a third party need not trust the
866
+ * API). Capabilities remain unverified claims; on-chain history (EscroRep,
867
+ * Phase 7) is their verification, deliberately not merged in here.
868
+ */
869
+ async findWorkers(params = {}) {
870
+ const { items } = await this.api.listBots({
871
+ role: "worker",
872
+ ...params.capability != null && { capability: params.capability },
873
+ ...params.limit != null && { limit: params.limit },
874
+ ...params.offset != null && { offset: params.offset }
875
+ });
876
+ return items.map((descriptor) => ({
877
+ descriptor,
878
+ signatureValid: verifyBotDescriptorSignature(descriptor)
879
+ }));
880
+ }
881
+ /**
882
+ * Fetch the EscroRep bulk export: every indexed wallet's RAW reputation
883
+ * components (ARCHITECTURE §9), each wallet exactly once, in one fetch. Returns
884
+ * the raw components verbatim - this method does NO ranking, scoring, or default
885
+ * weighting (Escro-shipped code never ranks; the caller's own bot weights and
886
+ * decides). Selection layers join these components to {@link findWorkers}
887
+ * candidates by wallet. Throws {@link ReputationUnavailableError} when the
888
+ * deployment mounts no reputation source (HTTP 404).
889
+ */
890
+ async listReputations() {
891
+ return this.api.listReputations();
892
+ }
893
+ // ── Stats ────────────────────────────────────────────────────────────────────
894
+ /**
895
+ * Fetch protocol-wide stats from the public `GET /v1/stats` endpoint.
896
+ *
897
+ * @returns protocol-wide {@link ProtocolStats}.
898
+ */
899
+ async getStats() {
900
+ const data = await this.api.getStats();
901
+ return data;
902
+ }
443
903
  // ── Shared ───────────────────────────────────────────────────────────────────
904
+ /**
905
+ * Ask the API to record the create, claim, submit, cancel or dispute that the
906
+ * landed `signature` carries; the API verifies it on chain first. Retries a
907
+ * not-yet-visible transaction, an RPC failure, a gateway error or a rate limit
908
+ * for about 30 s (waiting at least a sent Retry-After), never a rejection. Throws
909
+ * {@link EscroConfirmError}; calling again is safe (a replay of a recorded
910
+ * transition succeeds).
911
+ */
912
+ async confirm(address, signature, opts = {}) {
913
+ const deadline = Date.now() + CONFIRM_WINDOW_MS;
914
+ let delay = CONFIRM_FIRST_DELAY_MS;
915
+ for (; ; ) {
916
+ let code;
917
+ let message;
918
+ let wait = delay;
919
+ try {
920
+ return await this.api.confirm(address, signature, opts.evidence);
921
+ } catch (err) {
922
+ if (err instanceof EscroError) {
923
+ if (!isRetryableConfirmCode(err.code)) {
924
+ throw new EscroConfirmError(address, signature, err.code, err.message);
925
+ }
926
+ code = err.code;
927
+ message = err.message;
928
+ wait = Math.max(delay, err.retryAfterMs ?? 0);
929
+ } else {
930
+ code = "NETWORK_ERROR";
931
+ message = err instanceof Error ? err.message : String(err);
932
+ }
933
+ }
934
+ if (Date.now() + wait > deadline) {
935
+ throw new EscroConfirmError(address, signature, code, message);
936
+ }
937
+ await sleep2(wait);
938
+ delay = Math.min(delay * 2, CONFIRM_MAX_DELAY_MS);
939
+ }
940
+ }
941
+ send(unsignedTx) {
942
+ return signAndSend(unsignedTx, this.options.wallet, this.connection, this.cluster);
943
+ }
944
+ async sendAndConfirm(address, unsignedTx) {
945
+ const signature = await this.send(unsignedTx);
946
+ await this.confirm(address, signature);
947
+ return signature;
948
+ }
444
949
  /**
445
950
  * Fetch an escrow by its PDA address.
446
951
  * If `options.poll` is true, polls with exponential backoff until the escrow
@@ -452,18 +957,1356 @@ var Escro = class {
452
957
  }
453
958
  return pollUntil(
454
959
  address,
455
- () => this.api.getEscrow(address).catch((e) => e instanceof EscrowNotFoundError ? null : Promise.reject(e)),
960
+ () => this.api.getEscrow(address).catch((e) => {
961
+ if (e instanceof EscrowNotFoundError) return null;
962
+ throw e instanceof Error ? e : new Error(String(e));
963
+ }),
456
964
  (r) => r !== null,
457
965
  options.timeoutMs
458
966
  );
459
967
  }
460
968
  };
969
+
970
+ // src/adapter.ts
971
+ function serviceResultToSubmitParams(result) {
972
+ return {
973
+ contentHash: result.contentHash,
974
+ ...result.proofUri !== void 0 && { proofUri: result.proofUri }
975
+ };
976
+ }
977
+
978
+ // src/adapter-contract.ts
979
+ import { createHash as createHash3 } from "crypto";
980
+ var AdapterContractError = class extends EscroError {
981
+ constructor(adapterId, violations) {
982
+ super(
983
+ `ServiceAdapter "${adapterId}" violates the adapter contract:
984
+ - ${violations.join("\n- ")}`,
985
+ "ADAPTER_CONTRACT_VIOLATION"
986
+ );
987
+ __publicField(this, "violations", violations);
988
+ this.name = "AdapterContractError";
989
+ }
990
+ };
991
+ function errMessage(err) {
992
+ return err instanceof Error ? err.message : String(err);
993
+ }
994
+ function sha256Hex(content) {
995
+ return createHash3("sha256").update(content).digest("hex");
996
+ }
997
+ function validateServiceResult(result) {
998
+ if (typeof result !== "object" || result === null) {
999
+ return ["`execute()` must resolve to a ServiceResult object"];
1000
+ }
1001
+ const violations = [];
1002
+ const r = result;
1003
+ const contentIsValid = typeof r.content === "string" || Buffer.isBuffer(r.content);
1004
+ if (!contentIsValid) {
1005
+ violations.push("`content` must be a string or Buffer");
1006
+ }
1007
+ if (typeof r.contentHash !== "string" || r.contentHash.trim() === "") {
1008
+ violations.push("`contentHash` must be a non-empty string");
1009
+ } else if (contentIsValid && r.contentHash !== sha256Hex(r.content)) {
1010
+ violations.push("`contentHash` must equal the SHA-256 hex digest of `content`");
1011
+ }
1012
+ if (r.proofUri !== void 0 && typeof r.proofUri !== "string") {
1013
+ violations.push("`proofUri`, when present, must be a string");
1014
+ }
1015
+ if (typeof r.metadata !== "object" || r.metadata === null || Array.isArray(r.metadata)) {
1016
+ violations.push("`metadata` must be a plain object");
1017
+ }
1018
+ return violations;
1019
+ }
1020
+ async function assertServiceAdapterContract(adapter, options) {
1021
+ const a = adapter;
1022
+ const violations = [];
1023
+ const id = typeof a.id === "string" && a.id.trim() !== "" ? a.id : "(unknown)";
1024
+ if (typeof a.id !== "string" || a.id.trim() === "") {
1025
+ violations.push("`id` must be a non-empty string");
1026
+ }
1027
+ if (!Array.isArray(a.capabilities) || a.capabilities.length === 0 || a.capabilities.some((c) => typeof c !== "string" || c.trim() === "")) {
1028
+ violations.push("`capabilities` must be a non-empty array of non-empty strings");
1029
+ }
1030
+ if (typeof a.healthCheck !== "function") {
1031
+ violations.push("`healthCheck` must be a function");
1032
+ }
1033
+ if (typeof a.execute !== "function") {
1034
+ violations.push("`execute` must be a function");
1035
+ }
1036
+ if (typeof a.healthCheck === "function") {
1037
+ try {
1038
+ const healthy = await a.healthCheck();
1039
+ if (typeof healthy !== "boolean") {
1040
+ violations.push("`healthCheck()` must resolve to a boolean");
1041
+ }
1042
+ } catch (err) {
1043
+ violations.push(`\`healthCheck()\` threw: ${errMessage(err)}`);
1044
+ }
1045
+ }
1046
+ let result;
1047
+ if (typeof a.execute === "function") {
1048
+ try {
1049
+ result = await a.execute(options.sampleSpec);
1050
+ violations.push(...validateServiceResult(result));
1051
+ } catch (err) {
1052
+ violations.push(`\`execute()\` threw: ${errMessage(err)}`);
1053
+ result = void 0;
1054
+ }
1055
+ }
1056
+ if (violations.length > 0 || result === void 0) {
1057
+ throw new AdapterContractError(
1058
+ id,
1059
+ violations.length > 0 ? violations : ["`execute()` produced no result"]
1060
+ );
1061
+ }
1062
+ return result;
1063
+ }
1064
+
1065
+ // src/adapters/bittensor/index.ts
1066
+ import { createHash as createHash4 } from "crypto";
1067
+ function tao(amount) {
1068
+ return amount;
1069
+ }
1070
+ function sha256Hex2(content) {
1071
+ return createHash4("sha256").update(content).digest("hex");
1072
+ }
1073
+ var REFERENCE_MICRO_USDC_PER_TAO = 3e8;
1074
+ var defaultSwap = (microUsdc) => Promise.resolve(tao(microUsdc / REFERENCE_MICRO_USDC_PER_TAO));
1075
+ var defaultPin = (content) => Promise.resolve(`ipfs://placeholder-${sha256Hex2(content).slice(0, 16)}`);
1076
+ function createBittensorSubnetAdapter(config) {
1077
+ const id = `bittensor:${config.subnet}`;
1078
+ return {
1079
+ id,
1080
+ capabilities: config.capabilities,
1081
+ healthCheck: config.checkHealth,
1082
+ async execute(spec2) {
1083
+ const budgetTao = await config.swap(config.taskBudgetMicroUsdc);
1084
+ const content = await config.callSubnet(spec2, budgetTao);
1085
+ const contentHash = sha256Hex2(content);
1086
+ const proofUri = await config.pin(content);
1087
+ return {
1088
+ content,
1089
+ contentHash,
1090
+ proofUri,
1091
+ metadata: { adapter: id, subnet: config.subnet }
1092
+ };
1093
+ }
1094
+ };
1095
+ }
1096
+
1097
+ // src/adapters/gradients/index.ts
1098
+ var GRADIENTS_ADAPTER_ID = "bittensor:sn56";
1099
+ var GRADIENTS_CAPABILITIES = ["fine-tune"];
1100
+ var DEFAULT_SUBNET = "sn56";
1101
+ var DEFAULT_TASK_BUDGET_MICRO_USDC = 5e6;
1102
+ var GRADIENTS_DEMO_MARKER = "gradients-sn56-demo-v1";
1103
+ var GRADIENTS_DEMO_EVAL_FLOOR = 0.8;
1104
+ var DEMO_DATASET = [3, 7, 11, 15, 19];
1105
+ function demoExpectedOutputs() {
1106
+ return DEMO_DATASET.map((x) => 2 * x + 1);
1107
+ }
1108
+ var gradientsDemoJobSpec = {
1109
+ version: "1.0.0",
1110
+ // TaskType has no fine-tune category; "custom" is the canonical fallback.
1111
+ taskType: "custom",
1112
+ description: "Fine-tune the reference model on the canned SN56 demo dataset and return its predictions on the same inputs. The target map is y = 2x + 1. Acceptance is deterministic and recomputed by the buyer: prediction accuracy must be >= 0.8; the worker's self-reported eval score is not trusted.",
1113
+ acceptanceCriteria: [
1114
+ {
1115
+ id: "ac-eval-floor",
1116
+ description: "Prediction accuracy on the demo dataset is >= 0.8, recomputed by the buyer from the deliverable.",
1117
+ required: true
1118
+ }
1119
+ ],
1120
+ deliverableFormat: { type: "json" },
1121
+ metadata: {
1122
+ demo: GRADIENTS_DEMO_MARKER,
1123
+ dataset: [...DEMO_DATASET],
1124
+ target: "y = 2x + 1",
1125
+ evalFloor: GRADIENTS_DEMO_EVAL_FLOOR
1126
+ }
1127
+ };
1128
+ function solveGradientsDemo() {
1129
+ const predictions = demoExpectedOutputs();
1130
+ return canonicalize({
1131
+ checkpoint: "reference-sn56-demo-checkpoint",
1132
+ eval: { metric: "accuracy", score: 1 },
1133
+ predictions
1134
+ });
1135
+ }
1136
+ function parseDemoDeliverable(content) {
1137
+ const text = Buffer.isBuffer(content) ? content.toString("utf8") : content;
1138
+ let parsed;
1139
+ try {
1140
+ parsed = JSON.parse(text);
1141
+ } catch {
1142
+ return null;
1143
+ }
1144
+ if (typeof parsed !== "object" || parsed === null) {
1145
+ return null;
1146
+ }
1147
+ const predictions = parsed.predictions;
1148
+ if (!Array.isArray(predictions) || predictions.some((p) => typeof p !== "number")) {
1149
+ return null;
1150
+ }
1151
+ return { predictions };
1152
+ }
1153
+ function scoreGradientsDemoDeliverable(content) {
1154
+ const parsed = parseDemoDeliverable(content);
1155
+ if (parsed === null) {
1156
+ return 0;
1157
+ }
1158
+ const expected = demoExpectedOutputs();
1159
+ let matches = 0;
1160
+ for (let i = 0; i < expected.length; i++) {
1161
+ if (parsed.predictions[i] === expected[i]) {
1162
+ matches++;
1163
+ }
1164
+ }
1165
+ return matches / expected.length;
1166
+ }
1167
+ function referencePlaceholder(spec2) {
1168
+ return canonicalize({
1169
+ checkpoint: "reference-sn56-checkpoint",
1170
+ eval: { metric: "accuracy", score: 0 },
1171
+ note: "reference stub - replace the callSubnet port with a real SN56 miner call.",
1172
+ taskType: spec2.taskType
1173
+ });
1174
+ }
1175
+ var defaultCallSubnet = (spec2) => Promise.resolve(
1176
+ spec2.metadata.demo === GRADIENTS_DEMO_MARKER ? solveGradientsDemo() : referencePlaceholder(spec2)
1177
+ );
1178
+ function createGradientsAdapter(config = {}) {
1179
+ return createBittensorSubnetAdapter({
1180
+ subnet: config.subnet ?? DEFAULT_SUBNET,
1181
+ capabilities: config.capabilities ?? [...GRADIENTS_CAPABILITIES],
1182
+ taskBudgetMicroUsdc: config.taskBudgetMicroUsdc ?? DEFAULT_TASK_BUDGET_MICRO_USDC,
1183
+ swap: config.swap ?? defaultSwap,
1184
+ callSubnet: config.callSubnet ?? defaultCallSubnet,
1185
+ pin: config.pin ?? defaultPin,
1186
+ checkHealth: config.checkHealth ?? (() => Promise.resolve(true))
1187
+ });
1188
+ }
1189
+
1190
+ // src/adapters/ridges/index.ts
1191
+ import { createHash as createHash5 } from "crypto";
1192
+ var RIDGES_ADAPTER_ID = "ridges";
1193
+ var RIDGES_CAPABILITIES = ["code-generation"];
1194
+ var DEFAULT_SERVICE = "ridges";
1195
+ function sha256Hex3(content) {
1196
+ return createHash5("sha256").update(content).digest("hex");
1197
+ }
1198
+ var RIDGES_DEMO_MARKER = "ridges-demo-v1";
1199
+ var RIDGES_DEMO_COVERAGE_TARGET = 0.8;
1200
+ var DEMO_INPUTS = [1, 2, 3, 5, 15];
1201
+ function fizzbuzz(n) {
1202
+ if (n % 15 === 0) return "FizzBuzz";
1203
+ if (n % 3 === 0) return "Fizz";
1204
+ if (n % 5 === 0) return "Buzz";
1205
+ return String(n);
1206
+ }
1207
+ var ridgesDemoJobSpec = {
1208
+ version: "1.0.0",
1209
+ taskType: "code_generation",
1210
+ description: "Implement FizzBuzz for the fixed demo battery and return a test report: for each battery input, the output your implementation produced. Acceptance is deterministic and recomputed by the buyer: every delivered test must pass (exit 0) and coverage of the battery must be >= 0.8; the worker's self-reported pass/coverage is not trusted.",
1211
+ acceptanceCriteria: [
1212
+ {
1213
+ id: "ac-tests-pass",
1214
+ description: "Every delivered test passes (exit 0), recomputed by the buyer from the test report.",
1215
+ required: true
1216
+ },
1217
+ {
1218
+ id: "ac-coverage",
1219
+ description: "Coverage of the demo battery is >= 0.8, recomputed by the buyer.",
1220
+ required: true
1221
+ }
1222
+ ],
1223
+ deliverableFormat: { type: "json" },
1224
+ metadata: {
1225
+ demo: RIDGES_DEMO_MARKER,
1226
+ kata: "fizzbuzz",
1227
+ inputs: [...DEMO_INPUTS],
1228
+ coverageTarget: RIDGES_DEMO_COVERAGE_TARGET
1229
+ }
1230
+ };
1231
+ var REFERENCE_SOLUTION = 'export function fizzbuzz(n: number): string {\n if (n % 15 === 0) return "FizzBuzz";\n if (n % 3 === 0) return "Fizz";\n if (n % 5 === 0) return "Buzz";\n return String(n);\n}\n';
1232
+ function solveRidgesDemo() {
1233
+ const tests = DEMO_INPUTS.map((input) => ({ input, output: fizzbuzz(input) }));
1234
+ return canonicalize({
1235
+ language: "typescript",
1236
+ solution: REFERENCE_SOLUTION,
1237
+ coverage: 1,
1238
+ passed: true,
1239
+ tests
1240
+ });
1241
+ }
1242
+ function parseTestReport(content) {
1243
+ const text = Buffer.isBuffer(content) ? content.toString("utf8") : content;
1244
+ let parsed;
1245
+ try {
1246
+ parsed = JSON.parse(text);
1247
+ } catch {
1248
+ return null;
1249
+ }
1250
+ if (typeof parsed !== "object" || parsed === null) {
1251
+ return null;
1252
+ }
1253
+ const tests = parsed.tests;
1254
+ if (!Array.isArray(tests)) {
1255
+ return null;
1256
+ }
1257
+ const results = [];
1258
+ for (const t of tests) {
1259
+ if (typeof t !== "object" || t === null) {
1260
+ return null;
1261
+ }
1262
+ const { input, output } = t;
1263
+ if (typeof input !== "number" || typeof output !== "string") {
1264
+ return null;
1265
+ }
1266
+ results.push({ input, output });
1267
+ }
1268
+ return results;
1269
+ }
1270
+ function scoreRidgesDemoDeliverable(content) {
1271
+ const results = parseTestReport(content);
1272
+ if (results === null) {
1273
+ return 0;
1274
+ }
1275
+ const battery = new Set(DEMO_INPUTS);
1276
+ const coveredInputs = /* @__PURE__ */ new Set();
1277
+ for (const { input, output } of results) {
1278
+ if (!battery.has(input)) {
1279
+ continue;
1280
+ }
1281
+ if (output !== fizzbuzz(input)) {
1282
+ return 0;
1283
+ }
1284
+ coveredInputs.add(input);
1285
+ }
1286
+ return coveredInputs.size / DEMO_INPUTS.length;
1287
+ }
1288
+ function referencePlaceholder2(spec2) {
1289
+ return canonicalize({
1290
+ language: "typescript",
1291
+ solution: "// reference stub - replace the runAgent port with a real Ridges agent call.",
1292
+ passed: false,
1293
+ tests: [],
1294
+ taskType: spec2.taskType
1295
+ });
1296
+ }
1297
+ var defaultRunAgent = (spec2) => Promise.resolve(
1298
+ spec2.metadata.demo === RIDGES_DEMO_MARKER ? solveRidgesDemo() : referencePlaceholder2(spec2)
1299
+ );
1300
+ var defaultPin2 = (content) => Promise.resolve(`ipfs://placeholder-${sha256Hex3(content).slice(0, 16)}`);
1301
+ function createRidgesAdapter(config = {}) {
1302
+ const service = config.service ?? DEFAULT_SERVICE;
1303
+ const capabilities = config.capabilities ?? [...RIDGES_CAPABILITIES];
1304
+ const runAgent = config.runAgent ?? defaultRunAgent;
1305
+ const pin = config.pin ?? defaultPin2;
1306
+ const checkHealth = config.checkHealth ?? (() => Promise.resolve(true));
1307
+ return {
1308
+ id: service,
1309
+ capabilities,
1310
+ healthCheck: checkHealth,
1311
+ async execute(spec2) {
1312
+ const content = await runAgent(spec2);
1313
+ const contentHash = sha256Hex3(content);
1314
+ const proofUri = await pin(content);
1315
+ return {
1316
+ content,
1317
+ contentHash,
1318
+ proofUri,
1319
+ metadata: { adapter: service }
1320
+ };
1321
+ }
1322
+ };
1323
+ }
1324
+
1325
+ // src/adapters/404gen/index.ts
1326
+ var GEN404_ADAPTER_ID = "bittensor:sn17";
1327
+ var GEN404_CAPABILITIES = ["3d-generation"];
1328
+ var DEFAULT_SUBNET2 = "sn17";
1329
+ var DEFAULT_TASK_BUDGET_MICRO_USDC2 = 5e6;
1330
+ var GEN404_DEMO_MARKER = "404gen-sn17-demo-v1";
1331
+ var GEN404_DEMO_EVAL_FLOOR = 1;
1332
+ var DEMO_EXPECTATION = {
1333
+ requestedAssets: 1,
1334
+ allowedFormats: ["GLB", "PLY"],
1335
+ minPolygons: 1e3,
1336
+ maxPolygons: 1e6
1337
+ };
1338
+ var gen404DemoJobSpec = {
1339
+ version: "1.0.0",
1340
+ // TaskType has no 3D category; "custom" is the canonical fallback.
1341
+ taskType: "custom",
1342
+ description: "Generate the canned SN17 demo batch: one 3D asset in a GLB or PLY container with a polygon count between 1000 and 1000000. Acceptance is deterministic and recomputed by the buyer: every requested asset must be present, in an allowed format, and in polygon range; the worker's self-reported validity is not trusted.",
1343
+ acceptanceCriteria: [
1344
+ {
1345
+ id: "ac-format-valid",
1346
+ description: "Every asset is in an allowed container format (GLB or PLY), recomputed by the buyer.",
1347
+ required: true
1348
+ },
1349
+ {
1350
+ id: "ac-polygon-range",
1351
+ description: "Every asset's polygon count is within [1000, 1000000], recomputed by the buyer.",
1352
+ required: true
1353
+ },
1354
+ {
1355
+ id: "ac-batch-complete",
1356
+ description: "The batch contains all requested assets (completeness), recomputed by the buyer.",
1357
+ required: true
1358
+ }
1359
+ ],
1360
+ deliverableFormat: { type: "json" },
1361
+ metadata: {
1362
+ demo: GEN404_DEMO_MARKER,
1363
+ requestedAssets: DEMO_EXPECTATION.requestedAssets,
1364
+ allowedFormats: [...DEMO_EXPECTATION.allowedFormats],
1365
+ minPolygons: DEMO_EXPECTATION.minPolygons,
1366
+ maxPolygons: DEMO_EXPECTATION.maxPolygons
1367
+ }
1368
+ };
1369
+ function solveGen404Demo() {
1370
+ return canonicalize({
1371
+ assets: [{ format: "GLB", polygonCount: 5e3, uri: "ipfs://404gen-sn17-demo-asset-0" }],
1372
+ eval: { metric: "validity", score: 1 }
1373
+ });
1374
+ }
1375
+ function parseBatch(content) {
1376
+ const text = Buffer.isBuffer(content) ? content.toString("utf8") : content;
1377
+ let parsed;
1378
+ try {
1379
+ parsed = JSON.parse(text);
1380
+ } catch {
1381
+ return null;
1382
+ }
1383
+ if (typeof parsed !== "object" || parsed === null) {
1384
+ return null;
1385
+ }
1386
+ const assets = parsed.assets;
1387
+ if (!Array.isArray(assets)) {
1388
+ return null;
1389
+ }
1390
+ const cleaned = [];
1391
+ for (const asset of assets) {
1392
+ if (typeof asset !== "object" || asset === null) {
1393
+ return null;
1394
+ }
1395
+ const format = asset.format;
1396
+ const polygonCount = asset.polygonCount;
1397
+ if (typeof format !== "string" || typeof polygonCount !== "number") {
1398
+ return null;
1399
+ }
1400
+ cleaned.push({ format, polygonCount });
1401
+ }
1402
+ return { assets: cleaned };
1403
+ }
1404
+ function isAssetValid(asset) {
1405
+ const formatOk = DEMO_EXPECTATION.allowedFormats.some(
1406
+ (f) => f.toLowerCase() === asset.format.toLowerCase()
1407
+ );
1408
+ const rangeOk = asset.polygonCount >= DEMO_EXPECTATION.minPolygons && asset.polygonCount <= DEMO_EXPECTATION.maxPolygons;
1409
+ return formatOk && rangeOk;
1410
+ }
1411
+ function score404genDemoDeliverable(content) {
1412
+ const batch = parseBatch(content);
1413
+ if (batch === null) {
1414
+ return 0;
1415
+ }
1416
+ if (batch.assets.some((asset) => !isAssetValid(asset))) {
1417
+ return 0;
1418
+ }
1419
+ return Math.min(batch.assets.length / DEMO_EXPECTATION.requestedAssets, 1);
1420
+ }
1421
+ function referencePlaceholder3(spec2) {
1422
+ return canonicalize({
1423
+ assets: [{ format: "GLB", polygonCount: 0, uri: "ipfs://placeholder" }],
1424
+ note: "reference stub - replace the callSubnet port with a real SN17 miner call.",
1425
+ taskType: spec2.taskType
1426
+ });
1427
+ }
1428
+ var defaultCallSubnet2 = (spec2) => Promise.resolve(
1429
+ spec2.metadata.demo === GEN404_DEMO_MARKER ? solveGen404Demo() : referencePlaceholder3(spec2)
1430
+ );
1431
+ function create404genAdapter(config = {}) {
1432
+ return createBittensorSubnetAdapter({
1433
+ subnet: config.subnet ?? DEFAULT_SUBNET2,
1434
+ capabilities: config.capabilities ?? [...GEN404_CAPABILITIES],
1435
+ taskBudgetMicroUsdc: config.taskBudgetMicroUsdc ?? DEFAULT_TASK_BUDGET_MICRO_USDC2,
1436
+ swap: config.swap ?? defaultSwap,
1437
+ callSubnet: config.callSubnet ?? defaultCallSubnet2,
1438
+ pin: config.pin ?? defaultPin,
1439
+ checkHealth: config.checkHealth ?? (() => Promise.resolve(true))
1440
+ });
1441
+ }
1442
+
1443
+ // src/adapters/lium/index.ts
1444
+ var LIUM_ADAPTER_ID = "bittensor:sn51";
1445
+ var LIUM_CAPABILITIES = ["gpu-compute"];
1446
+ var DEFAULT_SUBNET3 = "sn51";
1447
+ var DEFAULT_TASK_BUDGET_MICRO_USDC3 = 2e7;
1448
+ var LIUM_DEMO_MARKER = "lium-sn51-demo-v1";
1449
+ var LIUM_DEMO_ACCEPT_FLOOR = 1;
1450
+ var DEMO_SEED = "lium-sn51-demo-seed";
1451
+ var DEMO_ROUNDS = 1e3;
1452
+ function computeLiumDemoArtifact() {
1453
+ let h = DEMO_SEED;
1454
+ for (let i = 0; i < DEMO_ROUNDS; i++) {
1455
+ h = sha256Hex2(h);
1456
+ }
1457
+ return h;
1458
+ }
1459
+ var liumDemoJobSpec = {
1460
+ version: "1.0.0",
1461
+ // TaskType has no GPU-compute category; "custom" is the canonical fallback.
1462
+ taskType: "custom",
1463
+ description: "Run the canned SN51 scripted GPU job (a fixed hash-chain compute over a known seed) and return its output artifact. Acceptance is deterministic and recomputed by the buyer: the job must complete, an output artifact must be present, and the artifact must match the buyer's independent recompute; the worker's self-reported artifact hash is not trusted.",
1464
+ acceptanceCriteria: [
1465
+ {
1466
+ id: "ac-completion",
1467
+ description: "The scripted job ran to completion (status=completed).",
1468
+ required: true
1469
+ },
1470
+ {
1471
+ id: "ac-artifact-present",
1472
+ description: "An output artifact is present in the deliverable.",
1473
+ required: true
1474
+ },
1475
+ {
1476
+ id: "ac-hash-match",
1477
+ description: "The output artifact matches the buyer's independent recompute of the scripted job.",
1478
+ required: true
1479
+ }
1480
+ ],
1481
+ deliverableFormat: { type: "json" },
1482
+ metadata: {
1483
+ demo: LIUM_DEMO_MARKER,
1484
+ seed: DEMO_SEED,
1485
+ rounds: DEMO_ROUNDS,
1486
+ acceptFloor: LIUM_DEMO_ACCEPT_FLOOR
1487
+ }
1488
+ };
1489
+ function solveLiumDemo() {
1490
+ const artifact = computeLiumDemoArtifact();
1491
+ return canonicalize({
1492
+ job: LIUM_DEMO_MARKER,
1493
+ status: "completed",
1494
+ rounds: DEMO_ROUNDS,
1495
+ artifact,
1496
+ // Self-reported and deliberately ignored by the buyer's recompute.
1497
+ artifactHash: sha256Hex2(artifact)
1498
+ });
1499
+ }
1500
+ function parseDemoDeliverable2(content) {
1501
+ const text = Buffer.isBuffer(content) ? content.toString("utf8") : content;
1502
+ let parsed;
1503
+ try {
1504
+ parsed = JSON.parse(text);
1505
+ } catch {
1506
+ return null;
1507
+ }
1508
+ if (typeof parsed !== "object" || parsed === null) {
1509
+ return null;
1510
+ }
1511
+ const obj = parsed;
1512
+ const status = typeof obj.status === "string" ? obj.status : "";
1513
+ const artifact = typeof obj.artifact === "string" ? obj.artifact : null;
1514
+ return { status, artifact };
1515
+ }
1516
+ function scoreLiumDemoDeliverable(content) {
1517
+ const parsed = parseDemoDeliverable2(content);
1518
+ if (parsed === null) {
1519
+ return 0;
1520
+ }
1521
+ if (parsed.status !== "completed") {
1522
+ return 0;
1523
+ }
1524
+ if (parsed.artifact === null) {
1525
+ return 0;
1526
+ }
1527
+ return parsed.artifact === computeLiumDemoArtifact() ? 1 : 0;
1528
+ }
1529
+ function referencePlaceholder4(spec2) {
1530
+ return canonicalize({
1531
+ job: "lium-sn51-generic",
1532
+ status: "completed",
1533
+ artifact: null,
1534
+ note: "reference stub - replace the runJob port with a real SN51 GPU-rental call.",
1535
+ taskType: spec2.taskType
1536
+ });
1537
+ }
1538
+ var defaultRunJob = (spec2) => Promise.resolve(
1539
+ spec2.metadata.demo === LIUM_DEMO_MARKER ? solveLiumDemo() : referencePlaceholder4(spec2)
1540
+ );
1541
+ function createLiumAdapter(config = {}) {
1542
+ return createBittensorSubnetAdapter({
1543
+ subnet: config.subnet ?? DEFAULT_SUBNET3,
1544
+ capabilities: config.capabilities ?? [...LIUM_CAPABILITIES],
1545
+ taskBudgetMicroUsdc: config.taskBudgetMicroUsdc ?? DEFAULT_TASK_BUDGET_MICRO_USDC3,
1546
+ swap: config.swap ?? defaultSwap,
1547
+ callSubnet: config.runJob ?? defaultRunJob,
1548
+ pin: config.pin ?? defaultPin,
1549
+ checkHealth: config.checkHealth ?? (() => Promise.resolve(true))
1550
+ });
1551
+ }
1552
+
1553
+ // src/adapters/akash/index.ts
1554
+ import { createHash as createHash6 } from "crypto";
1555
+ function akt(amount) {
1556
+ return amount;
1557
+ }
1558
+ function sha256Hex4(content) {
1559
+ return createHash6("sha256").update(content).digest("hex");
1560
+ }
1561
+ var AKASH_ADAPTER_ID = "akash";
1562
+ var AKASH_CAPABILITIES = ["cloud-compute"];
1563
+ var DEFAULT_TASK_BUDGET_MICRO_USDC4 = 1e7;
1564
+ var REFERENCE_MICRO_USDC_PER_AKT = 3e6;
1565
+ var defaultSwap2 = (microUsdc) => Promise.resolve(akt(microUsdc / REFERENCE_MICRO_USDC_PER_AKT));
1566
+ var defaultPin3 = (content) => Promise.resolve(`ipfs://placeholder-${sha256Hex4(content).slice(0, 16)}`);
1567
+ var AKASH_DEMO_MARKER = "akash-demo-v1";
1568
+ var AKASH_DEMO_ACCEPT_FLOOR = 1;
1569
+ var DEMO_SEED2 = "akash-demo-seed";
1570
+ var DEMO_ROUNDS2 = 1e3;
1571
+ function computeAkashDemoArtifact() {
1572
+ let h = DEMO_SEED2;
1573
+ for (let i = 0; i < DEMO_ROUNDS2; i++) {
1574
+ h = sha256Hex4(h);
1575
+ }
1576
+ return h;
1577
+ }
1578
+ var akashDemoJobSpec = {
1579
+ version: "1.0.0",
1580
+ // TaskType has no cloud-compute category; "custom" is the canonical fallback.
1581
+ taskType: "custom",
1582
+ description: "Run the canned Akash scripted batch job (a fixed hash-chain compute over a known seed) on a deployment and return its output artifact. Acceptance is deterministic and recomputed by the buyer: the job must complete, an output artifact must be present, and the artifact must match the buyer's independent recompute; the worker's self-reported artifact hash is not trusted.",
1583
+ acceptanceCriteria: [
1584
+ {
1585
+ id: "ac-completion",
1586
+ description: "The scripted job ran to completion (status=completed).",
1587
+ required: true
1588
+ },
1589
+ {
1590
+ id: "ac-artifact-present",
1591
+ description: "An output artifact is present in the deliverable.",
1592
+ required: true
1593
+ },
1594
+ {
1595
+ id: "ac-hash-match",
1596
+ description: "The output artifact matches the buyer's independent recompute of the scripted job.",
1597
+ required: true
1598
+ }
1599
+ ],
1600
+ deliverableFormat: { type: "json" },
1601
+ metadata: {
1602
+ demo: AKASH_DEMO_MARKER,
1603
+ seed: DEMO_SEED2,
1604
+ rounds: DEMO_ROUNDS2,
1605
+ acceptFloor: AKASH_DEMO_ACCEPT_FLOOR
1606
+ }
1607
+ };
1608
+ function solveAkashDemo() {
1609
+ const artifact = computeAkashDemoArtifact();
1610
+ return canonicalize({
1611
+ job: AKASH_DEMO_MARKER,
1612
+ status: "completed",
1613
+ rounds: DEMO_ROUNDS2,
1614
+ artifact,
1615
+ // Self-reported and deliberately ignored by the buyer's recompute.
1616
+ artifactHash: sha256Hex4(artifact)
1617
+ });
1618
+ }
1619
+ function parseDemoDeliverable3(content) {
1620
+ const text = Buffer.isBuffer(content) ? content.toString("utf8") : content;
1621
+ let parsed;
1622
+ try {
1623
+ parsed = JSON.parse(text);
1624
+ } catch {
1625
+ return null;
1626
+ }
1627
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1628
+ return null;
1629
+ }
1630
+ const obj = parsed;
1631
+ const status = typeof obj.status === "string" ? obj.status : "";
1632
+ const artifact = typeof obj.artifact === "string" ? obj.artifact : null;
1633
+ return { status, artifact };
1634
+ }
1635
+ function scoreAkashDemoDeliverable(content) {
1636
+ const parsed = parseDemoDeliverable3(content);
1637
+ if (parsed === null) {
1638
+ return 0;
1639
+ }
1640
+ if (parsed.status !== "completed") {
1641
+ return 0;
1642
+ }
1643
+ if (parsed.artifact === null) {
1644
+ return 0;
1645
+ }
1646
+ return parsed.artifact === computeAkashDemoArtifact() ? 1 : 0;
1647
+ }
1648
+ function referencePlaceholder5(spec2) {
1649
+ return canonicalize({
1650
+ job: "akash-generic",
1651
+ status: "completed",
1652
+ artifact: null,
1653
+ note: "reference stub - replace the runDeployment port with a real Akash deployment call.",
1654
+ taskType: spec2.taskType
1655
+ });
1656
+ }
1657
+ var defaultRunDeployment = (spec2) => Promise.resolve(
1658
+ spec2.metadata.demo === AKASH_DEMO_MARKER ? solveAkashDemo() : referencePlaceholder5(spec2)
1659
+ );
1660
+ function createAkashAdapter(config = {}) {
1661
+ const capabilities = config.capabilities ?? [...AKASH_CAPABILITIES];
1662
+ const taskBudgetMicroUsdc = config.taskBudgetMicroUsdc ?? DEFAULT_TASK_BUDGET_MICRO_USDC4;
1663
+ const swap = config.swap ?? defaultSwap2;
1664
+ const runDeployment = config.runDeployment ?? defaultRunDeployment;
1665
+ const pin = config.pin ?? defaultPin3;
1666
+ const checkHealth = config.checkHealth ?? (() => Promise.resolve(true));
1667
+ return {
1668
+ id: AKASH_ADAPTER_ID,
1669
+ capabilities,
1670
+ healthCheck: checkHealth,
1671
+ async execute(spec2) {
1672
+ const budgetAkt = await swap(taskBudgetMicroUsdc);
1673
+ const content = await runDeployment(spec2, budgetAkt);
1674
+ const contentHash = sha256Hex4(content);
1675
+ const proofUri = await pin(content);
1676
+ return {
1677
+ content,
1678
+ contentHash,
1679
+ proofUri,
1680
+ metadata: { adapter: AKASH_ADAPTER_ID }
1681
+ };
1682
+ }
1683
+ };
1684
+ }
1685
+
1686
+ // src/adapters/render/index.ts
1687
+ import { createHash as createHash7 } from "crypto";
1688
+ function renderAmount(amount) {
1689
+ return amount;
1690
+ }
1691
+ var RENDER_ADAPTER_ID = "render";
1692
+ var RENDER_CAPABILITIES = ["3d-rendering", "video-rendering", "gpu-inference"];
1693
+ var DEFAULT_SERVICE2 = "render";
1694
+ var DEFAULT_TASK_BUDGET_MICRO_USDC5 = 15e6;
1695
+ function sha256Hex5(content) {
1696
+ return createHash7("sha256").update(content).digest("hex");
1697
+ }
1698
+ var REFERENCE_MICRO_USDC_PER_RENDER = 2e6;
1699
+ var defaultSwap3 = (microUsdc) => Promise.resolve(renderAmount(microUsdc / REFERENCE_MICRO_USDC_PER_RENDER));
1700
+ var defaultPin4 = (content) => Promise.resolve(`ipfs://placeholder-${sha256Hex5(content).slice(0, 16)}`);
1701
+ var RENDER_DEMO_MARKER = "render-demo-v1";
1702
+ var RENDER_DEMO_ACCEPT_FLOOR = 1;
1703
+ var DEMO_SCENE = "render-demo-scene-v1";
1704
+ var DEMO_WIDTH = 16;
1705
+ var DEMO_HEIGHT = 16;
1706
+ function shade(x, y) {
1707
+ return x * 53 + y * 97 + (x ^ y) * 29 & 255;
1708
+ }
1709
+ function computeRenderDemoArtifact() {
1710
+ const raster = Buffer.alloc(DEMO_WIDTH * DEMO_HEIGHT);
1711
+ let i = 0;
1712
+ for (let y = 0; y < DEMO_HEIGHT; y++) {
1713
+ for (let x = 0; x < DEMO_WIDTH; x++) {
1714
+ raster[i++] = shade(x, y);
1715
+ }
1716
+ }
1717
+ return raster.toString("hex");
1718
+ }
1719
+ var renderDemoJobSpec = {
1720
+ version: "1.0.0",
1721
+ taskType: "image_generation",
1722
+ description: "Render the canned demo scene (a fixed procedural frame) and return the rendered frame. Acceptance is deterministic and recomputed by the buyer: the job must complete, a rendered frame must be present, and the frame must match the buyer's independent re-render; the worker's self-reported frame hash is not trusted.",
1723
+ acceptanceCriteria: [
1724
+ {
1725
+ id: "ac-completion",
1726
+ description: "The render job ran to completion (status=completed).",
1727
+ required: true
1728
+ },
1729
+ {
1730
+ id: "ac-frame-present",
1731
+ description: "A rendered frame is present in the deliverable.",
1732
+ required: true
1733
+ },
1734
+ {
1735
+ id: "ac-frame-match",
1736
+ description: "The rendered frame matches the buyer's independent re-render of the scene.",
1737
+ required: true
1738
+ }
1739
+ ],
1740
+ deliverableFormat: { type: "json" },
1741
+ metadata: {
1742
+ demo: RENDER_DEMO_MARKER,
1743
+ scene: DEMO_SCENE,
1744
+ width: DEMO_WIDTH,
1745
+ height: DEMO_HEIGHT,
1746
+ acceptFloor: RENDER_DEMO_ACCEPT_FLOOR
1747
+ }
1748
+ };
1749
+ function solveRenderDemo() {
1750
+ const frame = computeRenderDemoArtifact();
1751
+ return canonicalize({
1752
+ job: RENDER_DEMO_MARKER,
1753
+ status: "completed",
1754
+ width: DEMO_WIDTH,
1755
+ height: DEMO_HEIGHT,
1756
+ frame,
1757
+ // Self-reported and deliberately ignored by the buyer's recompute.
1758
+ frameHash: sha256Hex5(frame)
1759
+ });
1760
+ }
1761
+ function parseDemoDeliverable4(content) {
1762
+ const text = Buffer.isBuffer(content) ? content.toString("utf8") : content;
1763
+ let parsed;
1764
+ try {
1765
+ parsed = JSON.parse(text);
1766
+ } catch {
1767
+ return null;
1768
+ }
1769
+ if (typeof parsed !== "object" || parsed === null) {
1770
+ return null;
1771
+ }
1772
+ const obj = parsed;
1773
+ const status = typeof obj.status === "string" ? obj.status : "";
1774
+ const frame = typeof obj.frame === "string" ? obj.frame : null;
1775
+ return { status, frame };
1776
+ }
1777
+ function scoreRenderDemoDeliverable(content) {
1778
+ const parsed = parseDemoDeliverable4(content);
1779
+ if (parsed === null) {
1780
+ return 0;
1781
+ }
1782
+ if (parsed.status !== "completed") {
1783
+ return 0;
1784
+ }
1785
+ if (parsed.frame === null) {
1786
+ return 0;
1787
+ }
1788
+ return parsed.frame === computeRenderDemoArtifact() ? 1 : 0;
1789
+ }
1790
+ function referencePlaceholder6(spec2) {
1791
+ return canonicalize({
1792
+ job: "render-generic",
1793
+ status: "completed",
1794
+ frame: null,
1795
+ note: "reference stub - replace the runJob port with a real Render Network job submission.",
1796
+ taskType: spec2.taskType
1797
+ });
1798
+ }
1799
+ var defaultRunJob2 = (spec2) => Promise.resolve(
1800
+ spec2.metadata.demo === RENDER_DEMO_MARKER ? solveRenderDemo() : referencePlaceholder6(spec2)
1801
+ );
1802
+ function createRenderAdapter(config = {}) {
1803
+ const service = config.service ?? DEFAULT_SERVICE2;
1804
+ const capabilities = config.capabilities ?? [...RENDER_CAPABILITIES];
1805
+ const taskBudgetMicroUsdc = config.taskBudgetMicroUsdc ?? DEFAULT_TASK_BUDGET_MICRO_USDC5;
1806
+ const swap = config.swap ?? defaultSwap3;
1807
+ const runJob = config.runJob ?? defaultRunJob2;
1808
+ const pin = config.pin ?? defaultPin4;
1809
+ const checkHealth = config.checkHealth ?? (() => Promise.resolve(true));
1810
+ return {
1811
+ id: service,
1812
+ capabilities,
1813
+ healthCheck: checkHealth,
1814
+ async execute(spec2) {
1815
+ const budgetRender = await swap(taskBudgetMicroUsdc);
1816
+ const content = await runJob(spec2, budgetRender);
1817
+ const contentHash = sha256Hex5(content);
1818
+ const proofUri = await pin(content);
1819
+ return {
1820
+ content,
1821
+ contentHash,
1822
+ proofUri,
1823
+ metadata: { adapter: service, network: "render" }
1824
+ };
1825
+ }
1826
+ };
1827
+ }
1828
+
1829
+ // src/adapters/gensyn/index.ts
1830
+ import { createHash as createHash8 } from "crypto";
1831
+ var GENSYN_ADAPTER_ID = "gensyn";
1832
+ var GENSYN_CAPABILITIES = ["verifiable-compute"];
1833
+ var GENSYN_REE_SCHEME = "gensyn-ree-v1";
1834
+ var GENSYN_DEMO_MARKER = "gensyn-ree-demo-v1";
1835
+ var GENSYN_DEMO_SEED = 12345;
1836
+ var GENSYN_DEMO_STEPS = 16;
1837
+ function sha256Hex6(content) {
1838
+ return createHash8("sha256").update(content).digest("hex");
1839
+ }
1840
+ var LCG_MULT = 1103515245n;
1841
+ var LCG_INC = 12345n;
1842
+ var LCG_MOD = 1n << 31n;
1843
+ function readComputeParams(spec2) {
1844
+ const rawSeed = spec2.metadata.seed;
1845
+ const rawSteps = spec2.metadata.steps;
1846
+ const seed = typeof rawSeed === "number" && Number.isInteger(rawSeed) ? rawSeed : GENSYN_DEMO_SEED;
1847
+ const steps = typeof rawSteps === "number" && Number.isInteger(rawSteps) && rawSteps > 0 ? rawSteps : GENSYN_DEMO_STEPS;
1848
+ return { seed, steps };
1849
+ }
1850
+ var reproduceGensynCompute = (spec2) => {
1851
+ const { seed, steps } = readComputeParams(spec2);
1852
+ const states = [];
1853
+ let x = BigInt(seed) % LCG_MOD;
1854
+ if (x < 0n) {
1855
+ x += LCG_MOD;
1856
+ }
1857
+ for (let i = 0; i < steps; i++) {
1858
+ x = (LCG_MULT * x + LCG_INC) % LCG_MOD;
1859
+ states.push(Number(x));
1860
+ }
1861
+ return { seed, steps, states, result: states[states.length - 1] ?? seed };
1862
+ };
1863
+ function gensynDeliverable(exec) {
1864
+ return canonicalize({ result: exec.result, steps: exec.steps });
1865
+ }
1866
+ function commitmentOf(base) {
1867
+ return sha256Hex6(
1868
+ [base.scheme, base.specHash, base.outputHash, String(base.steps), base.transcriptHash].join(
1869
+ "\n"
1870
+ )
1871
+ );
1872
+ }
1873
+ function buildReeProof(spec2, exec, content) {
1874
+ const base = {
1875
+ scheme: GENSYN_REE_SCHEME,
1876
+ specHash: sha256Hex6(canonicalize(spec2)),
1877
+ outputHash: sha256Hex6(content),
1878
+ steps: exec.steps,
1879
+ transcriptHash: sha256Hex6(canonicalize(exec.states))
1880
+ };
1881
+ return { ...base, commitment: commitmentOf(base) };
1882
+ }
1883
+ var HEX_64 = /^[0-9a-f]{64}$/;
1884
+ function isHex64(v) {
1885
+ return typeof v === "string" && HEX_64.test(v);
1886
+ }
1887
+ function malformed(reason) {
1888
+ return { valid: false, reason: `malformed: ${reason}` };
1889
+ }
1890
+ function invalid(reason) {
1891
+ return { valid: false, reason: `invalid: ${reason}` };
1892
+ }
1893
+ function verifyReeProof(proof, ctx) {
1894
+ if (typeof proof !== "object" || proof === null) {
1895
+ return malformed("proof is not an object");
1896
+ }
1897
+ const p = proof;
1898
+ if (p.scheme !== GENSYN_REE_SCHEME) {
1899
+ return malformed(`scheme must be "${GENSYN_REE_SCHEME}"`);
1900
+ }
1901
+ if (!isHex64(p.specHash)) {
1902
+ return malformed("specHash must be a 64-char lowercase hex string");
1903
+ }
1904
+ if (!isHex64(p.outputHash)) {
1905
+ return malformed("outputHash must be a 64-char lowercase hex string");
1906
+ }
1907
+ if (!isHex64(p.transcriptHash)) {
1908
+ return malformed("transcriptHash must be a 64-char lowercase hex string");
1909
+ }
1910
+ if (!isHex64(p.commitment)) {
1911
+ return malformed("commitment must be a 64-char lowercase hex string");
1912
+ }
1913
+ if (typeof p.steps !== "number" || !Number.isInteger(p.steps) || p.steps <= 0) {
1914
+ return malformed("steps must be a positive integer");
1915
+ }
1916
+ const base = {
1917
+ scheme: GENSYN_REE_SCHEME,
1918
+ specHash: p.specHash,
1919
+ outputHash: p.outputHash,
1920
+ steps: p.steps,
1921
+ transcriptHash: p.transcriptHash
1922
+ };
1923
+ if (commitmentOf(base) !== p.commitment) {
1924
+ return invalid("commitment does not bind the proof fields (tampered)");
1925
+ }
1926
+ if (sha256Hex6(ctx.content) !== p.outputHash) {
1927
+ return invalid("outputHash does not match the delivered content");
1928
+ }
1929
+ if (sha256Hex6(canonicalize(ctx.spec)) !== p.specHash) {
1930
+ return invalid("specHash does not match the commissioned task spec");
1931
+ }
1932
+ const exec = (ctx.reproduce ?? reproduceGensynCompute)(ctx.spec);
1933
+ if (p.steps !== exec.steps) {
1934
+ return invalid("steps does not match the reproduced execution");
1935
+ }
1936
+ if (sha256Hex6(canonicalize(exec.states)) !== p.transcriptHash) {
1937
+ return invalid("transcriptHash is not reproducible from the task spec");
1938
+ }
1939
+ if (sha256Hex6(gensynDeliverable(exec)) !== p.outputHash) {
1940
+ return invalid("outputHash does not match the reproduced deliverable");
1941
+ }
1942
+ return {
1943
+ valid: true,
1944
+ reason: "REE proof verified: commitment, spec, transcript, and the reproduced deliverable all bind to the delivered content."
1945
+ };
1946
+ }
1947
+ function gensynAutoRelease(bundle, ctx) {
1948
+ const verdict = verifyReeProof(bundle.proof, {
1949
+ spec: ctx.spec,
1950
+ content: bundle.content,
1951
+ ...ctx.reproduce !== void 0 && { reproduce: ctx.reproduce }
1952
+ });
1953
+ return { release: verdict.valid, reason: verdict.reason };
1954
+ }
1955
+ var gensynDemoJobSpec = {
1956
+ version: "1.0.0",
1957
+ taskType: "custom",
1958
+ description: "Run the reference reproducible compute (a fixed LCG walk from the seed in metadata) and return its final result. Acceptance is a valid gensyn-ree-v1 REE proof: the buyer recomputes the transcript and confirms the proof binds the delivered content, this spec, and the reproducible execution. The worker's self-reported result is never trusted on its own.",
1959
+ acceptanceCriteria: [
1960
+ {
1961
+ id: "ac-ree-proof",
1962
+ description: "A valid gensyn-ree-v1 proof binding the delivered content, this spec, and a reproducible transcript.",
1963
+ required: true
1964
+ }
1965
+ ],
1966
+ deliverableFormat: { type: "json" },
1967
+ metadata: {
1968
+ demo: GENSYN_DEMO_MARKER,
1969
+ seed: GENSYN_DEMO_SEED,
1970
+ steps: GENSYN_DEMO_STEPS
1971
+ }
1972
+ };
1973
+ var defaultPin5 = (content) => Promise.resolve(`ipfs://gensyn-${sha256Hex6(content).slice(0, 16)}`);
1974
+ function createGensynAdapter(config = {}) {
1975
+ const runCompute = config.runCompute ?? reproduceGensynCompute;
1976
+ const pin = config.pin ?? defaultPin5;
1977
+ const checkHealth = config.checkHealth ?? (() => Promise.resolve(true));
1978
+ const capabilities = config.capabilities ?? [...GENSYN_CAPABILITIES];
1979
+ return {
1980
+ id: GENSYN_ADAPTER_ID,
1981
+ capabilities,
1982
+ healthCheck: checkHealth,
1983
+ async execute(spec2) {
1984
+ const exec = runCompute(spec2);
1985
+ const content = gensynDeliverable(exec);
1986
+ const contentHash = sha256Hex6(content);
1987
+ const proof = buildReeProof(spec2, exec, content);
1988
+ const proofUri = await pin(content);
1989
+ return {
1990
+ content,
1991
+ contentHash,
1992
+ proofUri,
1993
+ metadata: { adapter: GENSYN_ADAPTER_ID, reeProof: proof }
1994
+ };
1995
+ }
1996
+ };
1997
+ }
1998
+
1999
+ // src/adapters/zkml/index.ts
2000
+ import { createHash as createHash9 } from "crypto";
2001
+ var ZKML_ADAPTER_ID = "zkml";
2002
+ var ZKML_CAPABILITIES = ["zk-verified-inference"];
2003
+ var ZKML_DEMO_MARKER = "zkml-demo-v1";
2004
+ var ZKML_PROOF_SCHEME = "escro-zkml-ref-v1";
2005
+ var ZKML_PROOF_URI_PREFIX = "zkml-proof:";
2006
+ function sha256Hex7(content) {
2007
+ return createHash9("sha256").update(content).digest("hex");
2008
+ }
2009
+ function computeZkmlVerificationTag(publicInputs) {
2010
+ return sha256Hex7(
2011
+ canonicalize({
2012
+ scheme: publicInputs.scheme,
2013
+ modelCommitment: publicInputs.modelCommitment,
2014
+ inputCommitment: publicInputs.inputCommitment,
2015
+ outputHash: publicInputs.outputHash
2016
+ })
2017
+ );
2018
+ }
2019
+ function buildZkmlProof(args) {
2020
+ const publicInputs = {
2021
+ scheme: args.scheme ?? ZKML_PROOF_SCHEME,
2022
+ modelCommitment: args.modelCommitment,
2023
+ inputCommitment: args.inputCommitment,
2024
+ outputHash: args.outputHash
2025
+ };
2026
+ return { ...publicInputs, verificationTag: computeZkmlVerificationTag(publicInputs) };
2027
+ }
2028
+ function encodeZkmlProofUri(proof) {
2029
+ return ZKML_PROOF_URI_PREFIX + Buffer.from(canonicalize(proof), "utf8").toString("base64url");
2030
+ }
2031
+ function isProofShaped(value) {
2032
+ if (typeof value !== "object" || value === null) {
2033
+ return false;
2034
+ }
2035
+ const p = value;
2036
+ return typeof p.scheme === "string" && typeof p.modelCommitment === "string" && typeof p.inputCommitment === "string" && typeof p.outputHash === "string" && typeof p.verificationTag === "string";
2037
+ }
2038
+ function decodeZkmlProofUri(uri) {
2039
+ if (!uri.startsWith(ZKML_PROOF_URI_PREFIX)) {
2040
+ return null;
2041
+ }
2042
+ const encoded = uri.slice(ZKML_PROOF_URI_PREFIX.length);
2043
+ let parsed;
2044
+ try {
2045
+ parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
2046
+ } catch {
2047
+ return null;
2048
+ }
2049
+ return isProofShaped(parsed) ? parsed : null;
2050
+ }
2051
+ function verifyZkmlProof(proof, expected) {
2052
+ if (!isProofShaped(proof)) {
2053
+ return { valid: false, category: "malformed", reason: "proof is missing required fields" };
2054
+ }
2055
+ if (proof.scheme !== ZKML_PROOF_SCHEME) {
2056
+ return {
2057
+ valid: false,
2058
+ category: "malformed",
2059
+ reason: `unsupported proof scheme "${proof.scheme}"`
2060
+ };
2061
+ }
2062
+ if (proof.verificationTag !== computeZkmlVerificationTag(proof)) {
2063
+ return {
2064
+ valid: false,
2065
+ category: "invalid",
2066
+ reason: "verification tag does not recompute (public inputs altered after the tag was computed)"
2067
+ };
2068
+ }
2069
+ if (proof.outputHash !== expected.contentHash) {
2070
+ return {
2071
+ valid: false,
2072
+ category: "invalid",
2073
+ reason: "proof attests a different output than the submitted deliverable"
2074
+ };
2075
+ }
2076
+ if (expected.modelCommitment !== void 0 && proof.modelCommitment !== expected.modelCommitment) {
2077
+ return { valid: false, category: "invalid", reason: "proof attests a different model" };
2078
+ }
2079
+ return { valid: true };
2080
+ }
2081
+ function verifyZkmlProofUri(uri, expected) {
2082
+ if (typeof uri !== "string" || uri === "") {
2083
+ return { valid: false, category: "malformed", reason: "no proof URI attached" };
2084
+ }
2085
+ const proof = decodeZkmlProofUri(uri);
2086
+ if (proof === null) {
2087
+ return {
2088
+ valid: false,
2089
+ category: "malformed",
2090
+ reason: "proof URI is not a decodable inline zkml proof"
2091
+ };
2092
+ }
2093
+ return verifyZkmlProof(proof, expected);
2094
+ }
2095
+ async function resolveZkmlProof(uri, fetchProof) {
2096
+ if (typeof uri !== "string" || uri === "") {
2097
+ return null;
2098
+ }
2099
+ if (uri.startsWith(ZKML_PROOF_URI_PREFIX)) {
2100
+ return decodeZkmlProofUri(uri);
2101
+ }
2102
+ return fetchProof ? await fetchProof(uri) : null;
2103
+ }
2104
+ function zkmlProofAutoRelease(opts) {
2105
+ const verify = opts.verify ?? verifyZkmlProof;
2106
+ return {
2107
+ name: "zkml-proof-auto-release",
2108
+ async evaluate(d) {
2109
+ const recomputed = sha256Hex7(await opts.fetchContent(d));
2110
+ if (recomputed !== d.contentHash) {
2111
+ return {
2112
+ accept: false,
2113
+ dispute: true,
2114
+ reason: "delivered artifact does not hash to the submitted contentHash (tampered or wrong)"
2115
+ };
2116
+ }
2117
+ const proof = await resolveZkmlProof(d.proofUri, opts.fetchProof);
2118
+ if (proof === null) {
2119
+ return { accept: false, dispute: true, reason: "no decodable zkml proof attached" };
2120
+ }
2121
+ const verdict = verify(proof, {
2122
+ contentHash: recomputed,
2123
+ ...opts.modelCommitment !== void 0 && { modelCommitment: opts.modelCommitment }
2124
+ });
2125
+ if (verdict.valid) {
2126
+ return {
2127
+ accept: true,
2128
+ dispute: false,
2129
+ reason: "zkml proof verified against the re-hashed deliverable"
2130
+ };
2131
+ }
2132
+ return {
2133
+ accept: false,
2134
+ dispute: true,
2135
+ reason: `zkml proof ${verdict.category}: ${verdict.reason}`
2136
+ };
2137
+ }
2138
+ };
2139
+ }
2140
+ var zkmlDemoJobSpec = {
2141
+ version: "1.0.0",
2142
+ taskType: "custom",
2143
+ description: "Run the canned zk-verified inference demo: classify the fixed demo input and attach a proof that the output is the correct result of the committed model on the committed input. Acceptance is deterministic and recomputed by the buyer: the attached proof must verify against the submitted deliverable's contentHash.",
2144
+ acceptanceCriteria: [
2145
+ {
2146
+ id: "ac-proof-verifies",
2147
+ description: "The attached proof verifies against the submitted deliverable's contentHash, recomputed by the buyer.",
2148
+ required: true
2149
+ }
2150
+ ],
2151
+ deliverableFormat: { type: "json" },
2152
+ metadata: { demo: ZKML_DEMO_MARKER }
2153
+ };
2154
+ var DEMO_MODEL_COMMITMENT = sha256Hex7("zkml-demo-classifier-v1");
2155
+ var DEMO_INPUT_COMMITMENT = sha256Hex7("zkml-demo-input-v1");
2156
+ function solveZkmlDemo() {
2157
+ return canonicalize({
2158
+ model: "zkml-demo-classifier-v1",
2159
+ output: { label: "cat", confidence: 0.98 }
2160
+ });
2161
+ }
2162
+ function referencePlaceholderOutput(spec2) {
2163
+ return {
2164
+ content: canonicalize({
2165
+ note: "reference stub - replace the runInference port with a real zk-verified inference call.",
2166
+ taskType: spec2.taskType
2167
+ }),
2168
+ modelCommitment: sha256Hex7("zkml-reference-stub-model"),
2169
+ inputCommitment: sha256Hex7(canonicalize(spec2))
2170
+ };
2171
+ }
2172
+ var defaultRunInference = (spec2) => spec2.metadata.demo === ZKML_DEMO_MARKER ? {
2173
+ content: solveZkmlDemo(),
2174
+ modelCommitment: DEMO_MODEL_COMMITMENT,
2175
+ inputCommitment: DEMO_INPUT_COMMITMENT
2176
+ } : referencePlaceholderOutput(spec2);
2177
+ function createZkmlAdapter(config = {}) {
2178
+ const id = config.id ?? ZKML_ADAPTER_ID;
2179
+ const capabilities = config.capabilities ?? [...ZKML_CAPABILITIES];
2180
+ const runInference = config.runInference ?? defaultRunInference;
2181
+ const prove = config.prove ?? ((args) => buildZkmlProof({
2182
+ modelCommitment: args.output.modelCommitment,
2183
+ inputCommitment: args.output.inputCommitment,
2184
+ outputHash: args.outputHash
2185
+ }));
2186
+ const pin = config.pin ?? ((proof) => encodeZkmlProofUri(proof));
2187
+ const checkHealth = config.checkHealth ?? (() => Promise.resolve(true));
2188
+ return {
2189
+ id,
2190
+ capabilities,
2191
+ async execute(spec2) {
2192
+ const output = await runInference(spec2);
2193
+ const contentHash = sha256Hex7(output.content);
2194
+ const proof = await prove({ spec: spec2, output, outputHash: contentHash });
2195
+ const proofUri = await pin(proof);
2196
+ return {
2197
+ content: output.content,
2198
+ contentHash,
2199
+ proofUri,
2200
+ metadata: {
2201
+ adapterId: id,
2202
+ scheme: proof.scheme,
2203
+ modelCommitment: proof.modelCommitment
2204
+ }
2205
+ };
2206
+ },
2207
+ healthCheck() {
2208
+ return checkHealth();
2209
+ }
2210
+ };
2211
+ }
461
2212
  export {
2213
+ AKASH_ADAPTER_ID,
2214
+ AKASH_CAPABILITIES,
2215
+ AKASH_DEMO_ACCEPT_FLOOR,
2216
+ AKASH_DEMO_MARKER,
2217
+ AdapterContractError,
2218
+ ApiClient,
2219
+ ENABLED_RAILS,
462
2220
  Escro,
2221
+ EscroConfirmError,
463
2222
  EscroError,
2223
+ EscroRailNotEnabledError,
464
2224
  EscrowNotFoundError,
2225
+ EscrowPaymentRouter,
2226
+ EscrowState,
465
2227
  EscrowStateError,
466
2228
  EscrowTimeoutError,
467
- UnauthorizedError
2229
+ GEN404_ADAPTER_ID,
2230
+ GEN404_CAPABILITIES,
2231
+ GEN404_DEMO_EVAL_FLOOR,
2232
+ GEN404_DEMO_MARKER,
2233
+ GENSYN_ADAPTER_ID,
2234
+ GENSYN_CAPABILITIES,
2235
+ GENSYN_DEMO_MARKER,
2236
+ GENSYN_REE_SCHEME,
2237
+ GRADIENTS_ADAPTER_ID,
2238
+ GRADIENTS_CAPABILITIES,
2239
+ GRADIENTS_DEMO_EVAL_FLOOR,
2240
+ GRADIENTS_DEMO_MARKER,
2241
+ LIUM_ADAPTER_ID,
2242
+ LIUM_CAPABILITIES,
2243
+ LIUM_DEMO_ACCEPT_FLOOR,
2244
+ LIUM_DEMO_MARKER,
2245
+ RAILS,
2246
+ RAILS_DOCS_URL,
2247
+ REFERENCE_MICRO_USDC_PER_AKT,
2248
+ REFERENCE_MICRO_USDC_PER_RENDER,
2249
+ RENDER_ADAPTER_ID,
2250
+ RENDER_CAPABILITIES,
2251
+ RENDER_DEMO_ACCEPT_FLOOR,
2252
+ RENDER_DEMO_MARKER,
2253
+ RIDGES_ADAPTER_ID,
2254
+ RIDGES_CAPABILITIES,
2255
+ RIDGES_DEMO_COVERAGE_TARGET,
2256
+ RIDGES_DEMO_MARKER,
2257
+ ReputationUnavailableError,
2258
+ UnauthorizedError,
2259
+ ZKML_ADAPTER_ID,
2260
+ ZKML_CAPABILITIES,
2261
+ ZKML_DEMO_MARKER,
2262
+ ZKML_PROOF_SCHEME,
2263
+ ZKML_PROOF_URI_PREFIX,
2264
+ akashDemoJobSpec,
2265
+ akt,
2266
+ assertServiceAdapterContract,
2267
+ buildReeProof,
2268
+ buildZkmlProof,
2269
+ computeAkashDemoArtifact,
2270
+ computeLiumDemoArtifact,
2271
+ computeRenderDemoArtifact,
2272
+ create404genAdapter,
2273
+ createAkashAdapter,
2274
+ createGensynAdapter,
2275
+ createGradientsAdapter,
2276
+ createLiumAdapter,
2277
+ createRenderAdapter,
2278
+ createRidgesAdapter,
2279
+ createZkmlAdapter,
2280
+ decodeZkmlProofUri,
2281
+ encodeZkmlProofUri,
2282
+ gen404DemoJobSpec,
2283
+ gensynAutoRelease,
2284
+ gensynDemoJobSpec,
2285
+ gradientsDemoJobSpec,
2286
+ liumDemoJobSpec,
2287
+ renderAmount,
2288
+ renderDemoJobSpec,
2289
+ reproduceGensynCompute,
2290
+ ridgesDemoJobSpec,
2291
+ score404genDemoDeliverable,
2292
+ scoreAkashDemoDeliverable,
2293
+ scoreGradientsDemoDeliverable,
2294
+ scoreLiumDemoDeliverable,
2295
+ scoreRenderDemoDeliverable,
2296
+ scoreRidgesDemoDeliverable,
2297
+ serviceResultToSubmitParams,
2298
+ solveAkashDemo,
2299
+ solveGen404Demo,
2300
+ solveGradientsDemo,
2301
+ solveLiumDemo,
2302
+ solveRenderDemo,
2303
+ solveRidgesDemo,
2304
+ solveZkmlDemo,
2305
+ tao,
2306
+ verifyReeProof,
2307
+ verifyZkmlProof,
2308
+ verifyZkmlProofUri,
2309
+ zkmlDemoJobSpec,
2310
+ zkmlProofAutoRelease
468
2311
  };
469
2312
  //# sourceMappingURL=index.js.map