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