@tangle-network/sandbox 1.0.264 → 1.0.266

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.
Files changed (73) hide show
  1. package/README.md +17 -7
  2. package/dist/abi-pcDt2Adp.js +136 -0
  3. package/dist/agent/index.d.ts +4 -4
  4. package/dist/agent/index.js +5 -5
  5. package/dist/agent/preview.d.ts +1 -1
  6. package/dist/agent/preview.js +2 -2
  7. package/dist/{agent-run-outcome-DLLvOkbe.d.ts → agent-run-outcome-DThM9ULE.d.ts} +2 -2
  8. package/dist/{api-request-SBaqnuZB.js → api-request-gkPDymqn.js} +2 -2
  9. package/dist/auth/index.d.ts +2 -2
  10. package/dist/auth/index.js +2 -2
  11. package/dist/{browser-interactive-control-controller-Bg7mWDLX.d.ts → browser-interactive-control-controller-ClykJB9N.d.ts} +1 -1
  12. package/dist/{browser-interactive-control-controller-PiCGGheb.js → browser-interactive-control-controller-S_Uo-Zy7.js} +1 -1
  13. package/dist/{chunked-upload-D2S7tOJO.js → chunked-upload-ChZB-dYE.js} +1 -1
  14. package/dist/{chunked-upload-file-CfuaCSja.js → chunked-upload-file-BGaOS3iK.js} +1 -1
  15. package/dist/cli-auth-bundle-DXKH215p.js +2 -0
  16. package/dist/{cli-auth-bundle-C6DtK7GX-D8681c7j.js → cli-auth-bundle-DcxhAW23-C22MMIvx.js} +36 -36
  17. package/dist/{client-CkpH8MsM.js → client-BWD7-uaL.js} +40 -57
  18. package/dist/{client-DaZwQeOS.d.ts → client-BYGLoEiU.d.ts} +153 -198
  19. package/dist/collaboration/index.d.ts +1 -1
  20. package/dist/collaboration/index.js +1 -1
  21. package/dist/{collaboration-Corlo5N0.js → collaboration-Bqk4jYQe.js} +2 -2
  22. package/dist/core.d.ts +6 -6
  23. package/dist/core.js +5 -5
  24. package/dist/{error-catalog-CWtp7Yg1.js → error-catalog-GS97N-Cm.js} +1 -1
  25. package/dist/{errors-C0S3TzhR.js → errors-D44qyFpy.js} +1 -1
  26. package/dist/{file-download-7lcgh1LR.js → file-download-BO-Hmn3x.js} +1 -1
  27. package/dist/gpu-lease/index.d.ts +192 -184
  28. package/dist/gpu-lease/index.js +390 -281
  29. package/dist/{index-dxhLhM8L.d.ts → index-DkB8WbjK.d.ts} +43 -99
  30. package/dist/index.d.ts +13 -13
  31. package/dist/index.js +178 -61
  32. package/dist/intelligence/index.d.ts +1 -1
  33. package/dist/intelligence/index.js +4 -4
  34. package/dist/interactive-control.d.ts +1 -1
  35. package/dist/interactive-control.js +1 -1
  36. package/dist/{interactive-controller-CRp4VQKD.d.ts → interactive-controller-DSYQTRwh.d.ts} +3 -3
  37. package/dist/{interactive-controller-CqJX-LcO.js → interactive-controller-llj6EdlZ.js} +4 -4
  38. package/dist/lib/prepared-evidence.js +1 -1
  39. package/dist/{lines-BTStaSM2.d.ts → lines-D7lE49lV.d.ts} +1 -1
  40. package/dist/{lines-NECw0OhS.js → lines-DwJ7AKx7.js} +1 -1
  41. package/dist/lines.d.ts +1 -1
  42. package/dist/lines.js +1 -1
  43. package/dist/{local-cli-auth-wyO74fdb.js → local-cli-auth-C2cETxK4.js} +1 -1
  44. package/dist/{mcp-local-CpQncJsf.js → mcp-local-DVzsBlqX.js} +3 -3
  45. package/dist/{preview-D6bMarHf.d.ts → preview-DsHoo8BC.d.ts} +3 -3
  46. package/dist/{public-templates-3diq9yKD.d.ts → public-templates-DRqOkshE.d.ts} +2 -2
  47. package/dist/public-templates.d.ts +1 -1
  48. package/dist/public-templates.js +1 -1
  49. package/dist/{raw-evidence-archive-B0oCpHY3.js → raw-evidence-archive-BJ1cA-sP.js} +3 -3
  50. package/dist/runtime.d.ts +5 -5
  51. package/dist/runtime.js +5 -5
  52. package/dist/{sandbox-BVN_aNT1.js → sandbox-C3PqmwfU.js} +136 -196
  53. package/dist/{secp256k1-ZiYFbGjz.js → secp256k1-DIwypP5B.js} +1 -1
  54. package/dist/{select-seat-Cu-9jRO-.js → select-seat-Dc7cQ8To.js} +3 -3
  55. package/dist/select-seat-command.d.ts +2 -2
  56. package/dist/select-seat-command.js +2 -2
  57. package/dist/session-gateway/index.js +1 -1
  58. package/dist/tangle/index.d.ts +1 -1
  59. package/dist/tangle/index.js +2 -1
  60. package/dist/{tangle-Bpv3pIjM.js → tangle-BP8F3ZN0.js} +58 -185
  61. package/dist/{terminal-stream-types-DLaXWiSA.d.ts → terminal-stream-types-Cdz3xrux.d.ts} +1 -1
  62. package/dist/{types-COnts0u7.d.ts → types-BikjtQi3.d.ts} +202 -224
  63. package/package.json +11 -11
  64. package/dist/cli-auth-bundle-D5ZBMpZ7.js +0 -2
  65. /package/dist/{cli-auth-bundle-eUl7Sa1x.d.ts → cli-auth-bundle-CQCt2mcZ.d.ts} +0 -0
  66. /package/dist/{direct-http2-zLxsvF44.js → direct-http2-CzeIT93P.js} +0 -0
  67. /package/dist/{index-ClusTWYM.d.ts → index-B6aMEMDR.d.ts} +0 -0
  68. /package/dist/{index-BTXyTVq4.d.ts → index-BsT3M4X-.d.ts} +0 -0
  69. /package/dist/{prepared-evidence-ibAysmX8.js → prepared-evidence-DIFfn4Ki.js} +0 -0
  70. /package/dist/{preview-operations-DWL78boI.js → preview-operations-BTHZR1w2.js} +0 -0
  71. /package/dist/{raw-evidence-export-C0ieFpi2.d.ts → raw-evidence-export-C-TDdAgC.d.ts} +0 -0
  72. /package/dist/{raw-evidence-export-C6Xdl3nC.js → raw-evidence-export-Dog7W5zP.js} +0 -0
  73. /package/dist/{utils-BT2q9nkO.js → utils-BvN0Mk3j.js} +0 -0
@@ -1,76 +1,208 @@
1
- import { decodeAbiParameters, encodeAbiParameters, keccak256, parseAbi, parseAbiParameters, recoverMessageAddress, stringToHex } from "viem";
1
+ import { i as fetchSandboxApi } from "../api-request-gkPDymqn.js";
2
+ import { t as ITangleJobsAbi } from "../abi-pcDt2Adp.js";
3
+ import { createPublicClient, createWalletClient, decodeAbiParameters, encodeAbiParameters, encodeFunctionData, hexToBytes, http, keccak256, parseAbi, parseAbiParameters, parseEventLogs, recoverMessageAddress, stringToHex } from "viem";
4
+ import { privateKeyToAccount } from "viem/accounts";
5
+ //#region src/gpu-lease/vault.ts
6
+ const GPU_LEASE_VAULT_ABI = parseAbi([
7
+ "function create(address operator, uint128 pricePerSecond, uint64 durationSeconds, uint16 deviceCount, bytes32 intentHash, uint8 confidentiality, bytes endpointInfo) external payable returns (bytes32 leaseId)",
8
+ "function extend(bytes32 leaseId, uint64 addSeconds) external payable",
9
+ "function release(bytes32 leaseId) external",
10
+ "function reap(bytes32 leaseId) external",
11
+ "function withdrawEarnings() external",
12
+ "function totalEscrowed() external view returns (uint256)",
13
+ "function operatorEarnings() external view returns (uint256)",
14
+ "function leases(bytes32) external view returns (address operator, address lessee, uint128 escrow, uint128 pricePerSecond, uint64 expiry, bytes32 intentHash, uint8 confidentiality, uint8 state, uint16 deviceCount)",
15
+ "event LeaseCreated(bytes32 indexed leaseId, address indexed operator, address indexed lessee, uint128 escrow, uint128 pricePerSecond, uint16 deviceCount, uint64 expiry, bytes32 intentHash, uint8 confidentiality, bytes endpointInfo, uint16 schemaVersion)",
16
+ "event LeaseReleased(bytes32 indexed leaseId, uint128 refund, uint128 operatorTake)",
17
+ "event LeaseReaped(bytes32 indexed leaseId, uint128 operatorTake, address caller)"
18
+ ]);
19
+ function projectRefundWei(lease, nowSeconds) {
20
+ const remaining = lease.expiry > nowSeconds ? lease.expiry - nowSeconds : 0n;
21
+ const refundWei = lease.pricePerSecondWei * BigInt(lease.deviceCount) * remaining;
22
+ return {
23
+ refundWei,
24
+ operatorTakeWei: lease.escrowWei - refundWei
25
+ };
26
+ }
27
+ //#endregion
28
+ //#region src/gpu-lease/chain-viem.ts
29
+ /** eth_getLogs window, and how far back an earlier release is searched (100k blocks). */
30
+ const LOG_WINDOW = 5000n;
31
+ const LOG_WINDOWS = 20;
32
+ const JOB_RESULT_EV = ITangleJobsAbi.find((entry) => entry.type === "event" && entry.name === "JobResultSubmitted");
33
+ function createViemGpuLeaseChain(config) {
34
+ const publicClient = createPublicClient({ transport: http(config.rpcUrl) });
35
+ const account = privateKeyToAccount(config.privateKey);
36
+ const wallet = createWalletClient({
37
+ account,
38
+ transport: http(config.rpcUrl)
39
+ });
40
+ const pollIntervalMs = config.pollIntervalMs ?? 200;
41
+ const resultTimeoutMs = config.resultTimeoutMs ?? 3e4;
42
+ async function sendTx(to, data, value) {
43
+ const chainId = await publicClient.getChainId();
44
+ const hash = await wallet.sendTransaction({
45
+ to,
46
+ data,
47
+ value,
48
+ chain: null,
49
+ ...chainId === 31337 ? { gasPrice: 0n } : {}
50
+ });
51
+ const receipt = await publicClient.waitForTransactionReceipt({ hash }).catch(() => publicClient.waitForTransactionReceipt({ hash }));
52
+ if (receipt.status !== "success") throw new Error(`transaction ${hash} reverted`);
53
+ return receipt;
54
+ }
55
+ const chain = {
56
+ publicClient,
57
+ account: account.address,
58
+ async sessionDomain() {
59
+ return {
60
+ chainId: await publicClient.getChainId(),
61
+ vaultAddress: config.vaultAddress,
62
+ blueprintAddress: config.blueprintAddress
63
+ };
64
+ },
65
+ signMessage(message) {
66
+ return account.signMessage({ message });
67
+ },
68
+ async createVaultLease(input) {
69
+ const data = encodeFunctionData({
70
+ abi: GPU_LEASE_VAULT_ABI,
71
+ functionName: "create",
72
+ args: [
73
+ input.operator,
74
+ input.pricePerSecondWei,
75
+ input.durationSeconds,
76
+ input.deviceCount,
77
+ input.intentHash,
78
+ input.confidentiality,
79
+ stringToHex(input.endpointInfo)
80
+ ]
81
+ });
82
+ const [created] = parseEventLogs({
83
+ abi: GPU_LEASE_VAULT_ABI,
84
+ eventName: "LeaseCreated",
85
+ logs: (await sendTx(config.vaultAddress, data, input.escrowWei)).logs.filter((log) => log.address.toLowerCase() === config.vaultAddress.toLowerCase())
86
+ });
87
+ if (!created) throw new Error("vault.create receipt missing LeaseCreated");
88
+ return created.args.leaseId;
89
+ },
90
+ async submitJob(jobIndex, encodedInput) {
91
+ const data = encodeFunctionData({
92
+ abi: ITangleJobsAbi,
93
+ functionName: "submitJob",
94
+ args: [
95
+ config.serviceId,
96
+ jobIndex,
97
+ encodedInput
98
+ ]
99
+ });
100
+ const receipt = await sendTx(config.tangleAddress, data, 0n);
101
+ const [submitted] = parseEventLogs({
102
+ abi: ITangleJobsAbi,
103
+ eventName: "JobSubmitted",
104
+ logs: receipt.logs.filter((log) => log.address.toLowerCase() === config.tangleAddress.toLowerCase())
105
+ });
106
+ if (!submitted) throw new Error("submitJob receipt missing JobSubmitted");
107
+ const callId = submitted.args.callId;
108
+ const deadline = Date.now() + resultTimeoutMs;
109
+ while (Date.now() < deadline) {
110
+ const found = (await publicClient.getLogs({
111
+ address: config.tangleAddress,
112
+ event: JOB_RESULT_EV,
113
+ args: {
114
+ serviceId: config.serviceId,
115
+ callId
116
+ },
117
+ fromBlock: receipt.blockNumber
118
+ })).find((log) => log.args?.result !== void 0);
119
+ if (found?.args?.result !== void 0) return found.args.result;
120
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
121
+ }
122
+ throw new Error(`job result timeout (serviceId=${config.serviceId} callId=${callId})`);
123
+ },
124
+ async readLease(leaseId) {
125
+ const view = await publicClient.readContract({
126
+ address: config.vaultAddress,
127
+ abi: GPU_LEASE_VAULT_ABI,
128
+ functionName: "leases",
129
+ args: [leaseId]
130
+ });
131
+ return {
132
+ operator: view[0],
133
+ lessee: view[1],
134
+ escrowWei: view[2],
135
+ pricePerSecondWei: view[3],
136
+ expiry: view[4],
137
+ intentHash: view[5],
138
+ confidentiality: Number(view[6]),
139
+ state: Number(view[7]),
140
+ deviceCount: Number(view[8])
141
+ };
142
+ },
143
+ async chainNow() {
144
+ return (await publicClient.getBlock({ blockTag: "latest" })).timestamp;
145
+ },
146
+ async releaseLease(leaseId) {
147
+ const { state } = await chain.readLease(leaseId);
148
+ if (state !== 0 && state !== 1) throw new Error("vault lease is not releasable");
149
+ const data = encodeFunctionData({
150
+ abi: GPU_LEASE_VAULT_ABI,
151
+ functionName: "release",
152
+ args: [leaseId]
153
+ });
154
+ const events = async (toBlock, fromBlock = toBlock < LOG_WINDOW ? 0n : toBlock - LOG_WINDOW + 1n) => (await publicClient.getContractEvents({
155
+ address: config.vaultAddress,
156
+ abi: GPU_LEASE_VAULT_ABI,
157
+ eventName: "LeaseReleased",
158
+ args: { leaseId },
159
+ fromBlock,
160
+ toBlock,
161
+ strict: true
162
+ })).at(-1);
163
+ const sent = state === 0 && await sendTx(config.vaultAddress, data, 0n);
164
+ let released = sent && await events(sent.blockNumber, sent.blockNumber);
165
+ let to = await publicClient.getBlockNumber();
166
+ for (let n = 0; !released && to >= 0n && n < LOG_WINDOWS; n++, to -= LOG_WINDOW) released = await events(to);
167
+ if (!released) throw new Error("vault.release missing LeaseReleased");
168
+ return {
169
+ refundWei: released.args.refund,
170
+ operatorTakeWei: released.args.operatorTake
171
+ };
172
+ }
173
+ };
174
+ return chain;
175
+ }
176
+ //#endregion
2
177
  //#region src/gpu-lease/intent.ts
3
- /**
4
- * Canonical GPU-lease intent + job ABI encoding — MUST match:
5
- * gpu-lease-blueprint/gpu-lease-blueprint-lib/src/jobs/mod.rs (intent_hash)
6
- * gpu-lease-blueprint/contracts/src/GpuLeaseBlueprint.sol (GpuLeaseRequest)
7
- * gpu-lease-blueprint/metadata/blueprint.json (encodeType, generated).
8
- */
9
- const INTENT_VERSION = 1;
10
- /** keccak256 of the canonical intent string. */
178
+ const INTENT_VERSION = 2;
11
179
  function gpuLeaseIntentHash(input) {
12
- return keccak256(stringToHex(`gpu-lease-intent|v${input.intentVersion}|${input.gpuClass}|${input.durationSeconds}|${input.confidentiality}|${input.region}`));
180
+ return keccak256(stringToHex(`gpu-lease-intent|v${input.intentVersion}|${input.gpuClass}|${input.durationSeconds}|${input.confidentiality}|${input.region}|${input.deviceCount}`));
13
181
  }
14
- /** ABI shape of GpuLeaseRequest — mirrors the blueprint's sol! type. */
15
- const GPU_LEASE_REQUEST_ABI = parseAbiParameters("(uint8 intentVersion, bytes32 intentHash, uint128 pricePerSecond, uint64 durationSeconds, uint8 confidentiality, string gpuClass, string region, address lessee, bytes32 leaseId)");
16
- /**
17
- * ABI-encoded GpuLeaseRequest — the LEASE job calldata payload.
18
- * Positional (ABI order) — order is pinned by the blueprint's generated
19
- * encodeType in metadata/blueprint.json.
20
- */
182
+ const GPU_LEASE_REQUEST_ABI = parseAbiParameters("(uint8 intentVersion, bytes32 intentHash, uint128 pricePerSecond, uint64 durationSeconds, uint8 confidentiality, string gpuClass, string region, address lessee, bytes32 leaseId, bytes32 sandboxId, uint8 sandboxTeeType, uint16 deviceCount)");
21
183
  function encodeGpuLeaseRequest(params) {
22
- return encodeAbiParameters(GPU_LEASE_REQUEST_ABI, [[
23
- params.intentVersion,
24
- params.intentHash,
25
- params.pricePerSecondWei,
26
- params.durationSeconds,
27
- params.confidentiality,
28
- params.gpuClass,
29
- params.region,
30
- params.lessee,
31
- params.leaseId
32
- ]]);
184
+ return encodeAbiParameters(GPU_LEASE_REQUEST_ABI, [{
185
+ ...params,
186
+ pricePerSecond: params.pricePerSecondWei
187
+ }]);
33
188
  }
34
189
  //#endregion
35
190
  //#region src/gpu-lease/types.ts
36
- /**
37
- * GPU lease client types — mirrors the gpu-lease-blueprint operator API
38
- * (gpu-lease-blueprint/gpu-lease-blueprint-lib/src/api.rs) and the on-chain
39
- * ABI (contracts/src/GpuLeaseBlueprint.sol sol! mirror).
40
- *
41
- * Every on-chain and off-chain surface is schemaVersioned; unknown versions
42
- * fail closed (SPEC §3 of the blueprint).
43
- */
44
- /** The only schema this client understands. */
45
191
  const GPU_LEASE_SCHEMA_VERSION = 1;
46
192
  //#endregion
47
193
  //#region src/gpu-lease/operators.ts
48
- function assertKnownSchema(actual, where) {
49
- if (actual !== 1) throw new Error(`${where}: unknown schemaVersion ${actual} (client understands ${GPU_LEASE_VERSION_TEXT}) — failing closed`);
50
- }
51
- const GPU_LEASE_VERSION_TEXT = String(1);
52
- async function getJson(endpoint, path) {
53
- const res = await (endpoint.fetch ?? fetch)(new URL(path, endpoint.baseUrl).toString(), { headers: { accept: "application/json" } });
54
- if (!res.ok) throw new Error(`GET ${path}: operator returned ${res.status}`);
55
- const body = await res.json();
56
- assertKnownSchema(body.schemaVersion, `GET ${path}`);
57
- return body;
58
- }
59
- async function postJson(endpoint, path, payload, requireSchema = false) {
60
- const res = await (endpoint.fetch ?? fetch)(new URL(path, endpoint.baseUrl).toString(), {
61
- method: "POST",
62
- headers: {
63
- "content-type": "application/json",
64
- accept: "application/json"
65
- },
66
- body: JSON.stringify(payload)
194
+ async function requestJson(endpoint, path, options = {}) {
195
+ const response = await fetchSandboxApi({
196
+ baseUrl: "",
197
+ fetchImpl: endpoint.fetch
198
+ }, new URL(path, endpoint.baseUrl).toString(), {
199
+ method: options.payload ? "POST" : "GET",
200
+ headers: options.token ? { authorization: `Bearer ${options.token}` } : void 0,
201
+ body: options.payload ? JSON.stringify(options.payload) : void 0
67
202
  });
68
- if (!res.ok) {
69
- const detail = await res.text().catch(() => "");
70
- throw new Error(`POST ${path}: operator returned ${res.status} ${detail.slice(0, 200)}`);
71
- }
72
- const body = await res.json();
73
- if (requireSchema) assertKnownSchema(body.schemaVersion, `POST ${path}`);
203
+ if (!response.ok) throw new Error(`operator ${path} refused: ${response.status}`);
204
+ const body = await response.json();
205
+ if (options.schema !== false && body.schemaVersion !== 1) throw new Error(`operator ${path}: unknown schemaVersion ${body.schemaVersion}`);
74
206
  return body;
75
207
  }
76
208
  var GpuLeaseOperatorClient = class {
@@ -78,45 +210,43 @@ var GpuLeaseOperatorClient = class {
78
210
  this.endpoint = endpoint;
79
211
  }
80
212
  capabilities() {
81
- return getJson(this.endpoint, "/api/capabilities");
213
+ return requestJson(this.endpoint, "/api/capabilities");
82
214
  }
83
- async quote(params) {
84
- const quote = await postJson(this.endpoint, "/api/quote", {
85
- gpuClass: params.gpuClass,
86
- durationSeconds: params.durationSeconds,
87
- confidentiality: params.confidentiality ?? 0,
88
- ...params.region !== void 0 ? { region: params.region } : {}
89
- }, true);
90
- return {
91
- ...quote,
92
- operatorAddress: quote.operatorAddress ?? this.endpoint.address
93
- };
215
+ quote(params) {
216
+ return requestJson(this.endpoint, "/api/quote", { payload: {
217
+ ...params,
218
+ deviceCount: params.deviceCount ?? 1,
219
+ confidentiality: params.confidentiality ?? 0
220
+ } });
94
221
  }
95
222
  leaseStatus(leaseId) {
96
- return getJson(this.endpoint, `/api/leases/${leaseId.replace(/^0x/, "")}`);
223
+ return requestJson(this.endpoint, `/api/leases/${leaseId.replace(/^0x/, "")}`);
97
224
  }
98
225
  sessionChallenge(leaseId, lessee) {
99
- return postJson(this.endpoint, "/api/session/challenge", {
100
- leaseId,
101
- lessee
226
+ return requestJson(this.endpoint, "/api/session/challenge", {
227
+ payload: {
228
+ leaseId,
229
+ lessee
230
+ },
231
+ schema: false
102
232
  });
103
233
  }
104
234
  sessionVerify(nonce, signature) {
105
- return postJson(this.endpoint, "/api/session/verify", {
106
- nonce,
107
- signature
235
+ return requestJson(this.endpoint, "/api/session/verify", {
236
+ payload: {
237
+ nonce,
238
+ signature
239
+ },
240
+ schema: false
108
241
  });
109
242
  }
243
+ access(leaseId, token) {
244
+ return requestJson(this.endpoint, `/api/leases/${leaseId.replace(/^0x/, "")}/access`, { token });
245
+ }
110
246
  };
111
247
  //#endregion
112
248
  //#region src/gpu-lease/output.ts
113
- /**
114
- * GpuLeaseOutput decoding — the LEASE job result payload. The operator API
115
- * does NOT carry this (it is a job RESULT); it arrives from the chain via
116
- * the injected job client.
117
- */
118
249
  const GPU_LEASE_OUTPUT_ABI = parseAbiParameters("(bytes32 leaseId, string endpoint, uint16 schemaVersion)");
119
- /** Decode + fail closed on unknown schemaVersion (blueprint SPEC §3). */
120
250
  function decodeGpuLeaseOutput(encoded) {
121
251
  const [decoded] = decodeAbiParameters(GPU_LEASE_OUTPUT_ABI, encoded);
122
252
  if (decoded.schemaVersion !== 1) throw new Error(`GpuLeaseOutput: unknown schemaVersion ${decoded.schemaVersion} — failing closed`);
@@ -124,59 +254,48 @@ function decodeGpuLeaseOutput(encoded) {
124
254
  }
125
255
  //#endregion
126
256
  //#region src/gpu-lease/quotes.ts
127
- /**
128
- * Multi-operator RFQ: collect quotes, validate each against fail-closed
129
- * rules, rank by price. Pure — no I/O. Mirrors the validated-quote flow
130
- * proven in blueprint #1568 and the operator policy's ceiling semantics.
131
- */
132
- /** The exact string the operator signs — mirrors the blueprint's
133
- * `canonical_quote_payload` (v2) byte-for-byte. Every priced field is bound,
134
- * the device count included. */
257
+ /** Mirrors the operator API's signed quote payload. */
135
258
  function canonicalQuotePayload(quote) {
136
259
  return `gpu-lease-quote|v2|${quote.gpuClass}|${quote.pricePerSecond}|${quote.durationSeconds}|${quote.confidentiality}|${quote.deviceCount}|${quote.escrowTotal}|${quote.intentHash}|${quote.validUntil}`;
137
260
  }
138
- /** Offline EIP-191 recovery over the canonical payload. */
139
261
  async function verifyOperatorQuote(quote) {
140
262
  return (await recoverMessageAddress({
141
263
  message: canonicalQuotePayload(quote),
142
264
  signature: quote.signature
143
265
  })).toLowerCase();
144
266
  }
145
- /**
146
- * Validate one quote. Fail-closed on every field the RFQ binds:
147
- * class, duration, device count, the escrow derived from them,
148
- * confidentiality, and expiry.
149
- */
150
267
  function validateOperatorQuote(quote, input) {
151
- const now = (input.now ?? Date.now)() / 1e3;
152
- if (quote.gpuClass !== input.requestedClass) return {
153
- kind: "class-mismatch",
154
- requested: input.requestedClass,
155
- quoted: quote.gpuClass
156
- };
157
- if (quote.durationSeconds !== input.requestedDurationSeconds) return {
158
- kind: "duration-mismatch",
159
- requested: input.requestedDurationSeconds,
160
- quoted: quote.durationSeconds
161
- };
162
- if (quote.deviceCount !== input.requestedDeviceCount) return {
163
- kind: "count-mismatch",
164
- requested: input.requestedDeviceCount,
165
- quoted: quote.deviceCount
166
- };
167
- if (quote.confidentiality !== input.requestedConfidentiality) return {
168
- kind: "confidentiality-mismatch",
169
- requested: input.requestedConfidentiality,
170
- quoted: quote.confidentiality
171
- };
268
+ for (const rejection of [
269
+ {
270
+ kind: "class-mismatch",
271
+ requested: input.requestedClass,
272
+ quoted: quote.gpuClass
273
+ },
274
+ {
275
+ kind: "duration-mismatch",
276
+ requested: input.requestedDurationSeconds,
277
+ quoted: quote.durationSeconds
278
+ },
279
+ {
280
+ kind: "count-mismatch",
281
+ requested: input.requestedDeviceCount,
282
+ quoted: quote.deviceCount
283
+ },
284
+ {
285
+ kind: "confidentiality-mismatch",
286
+ requested: input.requestedConfidentiality,
287
+ quoted: quote.confidentiality
288
+ }
289
+ ]) if (rejection.requested !== rejection.quoted) return rejection;
172
290
  const price = BigInt(quote.pricePerSecond);
173
- const expectedEscrow = price * BigInt(quote.durationSeconds) * BigInt(quote.deviceCount);
174
- const actualEscrow = BigInt(quote.escrowTotal);
175
- if (expectedEscrow !== actualEscrow) return {
291
+ const expected = price * BigInt(quote.durationSeconds) * BigInt(quote.deviceCount);
292
+ const actual = BigInt(quote.escrowTotal);
293
+ if (expected !== actual) return {
176
294
  kind: "escrow-inconsistent",
177
- expected: expectedEscrow,
178
- actual: actualEscrow
295
+ expected,
296
+ actual
179
297
  };
298
+ const now = (input.now ?? Date.now)() / 1e3;
180
299
  if (quote.validUntil <= now) return {
181
300
  kind: "stale",
182
301
  validUntil: quote.validUntil,
@@ -185,14 +304,9 @@ function validateOperatorQuote(quote, input) {
185
304
  return {
186
305
  quote,
187
306
  pricePerSecondWei: price,
188
- escrowTotalWei: actualEscrow
307
+ escrowTotalWei: actual
189
308
  };
190
309
  }
191
- /**
192
- * Collect validated quotes from N operators and rank cheapest-first.
193
- * Operators that fail validation (or whose fetch rejects) are reported,
194
- * never silently dropped — the buyer sees why an operator lost.
195
- */
196
310
  function selectQuotes(quotes, input) {
197
311
  const ranked = [];
198
312
  const rejected = [];
@@ -208,134 +322,95 @@ function selectQuotes(quotes, input) {
208
322
  });
209
323
  }
210
324
  ranked.sort((a, b) => {
211
- if (a.validated.pricePerSecondWei !== b.validated.pricePerSecondWei) return a.validated.pricePerSecondWei < b.validated.pricePerSecondWei ? -1 : 1;
212
- return a.validated.escrowTotalWei < b.validated.escrowTotalWei ? -1 : 1;
325
+ const difference = a.validated.pricePerSecondWei - b.validated.pricePerSecondWei || a.validated.escrowTotalWei - b.validated.escrowTotalWei;
326
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
213
327
  });
214
328
  return {
215
329
  ranked,
216
330
  rejected
217
331
  };
218
332
  }
219
- /**
220
- * Enforce the signed RFQ envelope when present:
221
- * - signature present => it MUST recover to the claimed operator address;
222
- * invalid signature => reject (config-trust is dead on this path).
223
- * - no signature => the endpoint-config address is used (interim fallback);
224
- * strict mode rejects unsigned quotes outright.
225
- * - `pinnedOperator` set => the quote must be signed AND recover to that
226
- * address. A valid signature from any other key is rejected, so an
227
- * endpoint cannot substitute its own signer for the one the caller trusts.
228
- */
229
333
  async function validateQuoteIdentity(quote, opts = {}) {
230
- const base = {
231
- quote,
232
- pricePerSecondWei: BigInt(quote.pricePerSecond),
233
- escrowTotalWei: BigInt(quote.escrowTotal)
234
- };
235
- if (quote.signature) {
236
- const recovered = await verifyOperatorQuote(quote).catch(() => null);
237
- const claimed = quote.operatorAddress.toLowerCase();
238
- if (recovered === null || recovered !== claimed) return {
239
- kind: "signature-mismatch",
240
- claimed,
241
- recovered: recovered ?? "unrecoverable"
242
- };
243
- if (opts.pinnedOperator !== void 0 && recovered !== opts.pinnedOperator.toLowerCase()) return {
244
- kind: "operator-not-pinned",
245
- pinned: opts.pinnedOperator.toLowerCase(),
246
- recovered
247
- };
248
- return base;
249
- }
250
- if (opts.strict || opts.pinnedOperator !== void 0) return {
334
+ if (!quote.signature) return {
251
335
  kind: "unsigned",
252
336
  operator: quote.operatorAddress
253
337
  };
254
- return base;
255
- }
256
- //#endregion
257
- //#region src/gpu-lease/vault.ts
258
- /**
259
- * Vault money semantics — the client mirror of GpuLeaseVault.sol
260
- * (gpu-lease-blueprint/contracts/src/GpuLeaseVault.sol), invariants I1–I5.
261
- * Exact integers everywhere; wei only, never floats.
262
- */
263
- const GPU_LEASE_VAULT_ABI = parseAbi([
264
- "function create(address operator, uint128 pricePerSecond, uint64 durationSeconds, bytes32 intentHash, uint8 confidentiality, bytes endpointInfo) external payable returns (bytes32 leaseId)",
265
- "function extend(bytes32 leaseId, uint64 addSeconds) external payable",
266
- "function release(bytes32 leaseId) external",
267
- "function reap(bytes32 leaseId) external",
268
- "function withdrawEarnings() external",
269
- "function totalEscrowed() external view returns (uint256)",
270
- "function operatorEarnings() external view returns (uint256)",
271
- "function leases(bytes32) external view returns (address operator, address lessee, uint128 escrow, uint128 pricePerSecond, uint64 expiry, bytes32 intentHash, uint8 confidentiality, uint8 state)",
272
- "event LeaseCreated(bytes32 indexed leaseId, address indexed operator, address indexed lessee, uint128 escrow, uint128 pricePerSecond, uint64 expiry, bytes32 intentHash, uint8 confidentiality, bytes endpointInfo, uint16 schemaVersion)",
273
- "event LeaseReleased(bytes32 indexed leaseId, uint128 refund, uint128 operatorTake)",
274
- "event LeaseReaped(bytes32 indexed leaseId, uint128 operatorTake, address caller)"
275
- ]);
276
- /**
277
- * Exact refund projection (I3): pricePerSecond × max(expiry − now, 0).
278
- * Exact by construction because escrow === price × paidSeconds in the vault.
279
- */
280
- function projectRefundWei(lease, nowSeconds) {
281
- const remaining = lease.expiry > nowSeconds ? lease.expiry - nowSeconds : 0n;
282
- const refundWei = lease.pricePerSecondWei * remaining;
338
+ const recovered = await verifyOperatorQuote(quote).catch(() => null);
339
+ const claimed = quote.operatorAddress.toLowerCase();
340
+ if (recovered === null || recovered !== claimed) return {
341
+ kind: "signature-mismatch",
342
+ claimed,
343
+ recovered: recovered ?? "unrecoverable"
344
+ };
345
+ if (opts.pinnedOperator !== void 0 && recovered !== opts.pinnedOperator.toLowerCase()) return {
346
+ kind: "operator-not-pinned",
347
+ pinned: opts.pinnedOperator.toLowerCase(),
348
+ recovered
349
+ };
283
350
  return {
284
- refundWei,
285
- operatorTakeWei: lease.escrowWei - refundWei
351
+ quote,
352
+ pricePerSecondWei: BigInt(quote.pricePerSecond),
353
+ escrowTotalWei: BigInt(quote.escrowTotal)
286
354
  };
287
355
  }
288
- /** I2 from the client side: unpayable time can never be requested. */
289
- function maxAffordableSeconds(escrowWei, pricePerSecondWei) {
290
- if (pricePerSecondWei <= 0n) throw new Error("pricePerSecond must be positive");
291
- return escrowWei / pricePerSecondWei;
292
- }
293
356
  //#endregion
294
357
  //#region src/gpu-lease/resolver.ts
295
- /**
296
- * `gpuLease()` — the SPEC §5 resolver: collect + validate quotes → escrow on
297
- * the vault → LEASE job through tnt-core → teardown with an exact refund
298
- * receipt. Chain and job submission are INJECTED (transport-agnostic: works
299
- * with viem wallets, the TangleDriver, or test doubles).
300
- */
301
- /** Job ids — MUST match the blueprint router (sequential, no gaps). */
302
358
  const GPU_LEASE_JOBS = {
303
359
  LEASE: 0,
304
360
  RELEASE: 1,
305
361
  EXTEND: 2,
306
362
  REAP: 3
307
363
  };
308
- /** Resolve a GPU lease end-to-end. Throws with the full picture on failure. */
364
+ /** A failure after escrow: `leaseId` settles it (`chain.releaseLease`) instead of escrowing again. */
365
+ var GpuLeaseEscrowError = class extends Error {
366
+ constructor(leaseId, cause, cleanupError) {
367
+ super(`gpuLease: lease ${leaseId} failed after escrow: ${String(cause)}${cleanupError ? `; release also failed: ${String(cleanupError)}` : "; escrow released"}`, { cause });
368
+ this.leaseId = leaseId;
369
+ this.cleanupError = cleanupError;
370
+ }
371
+ };
309
372
  async function gpuLease(options) {
310
373
  const { gpuClass, durationSeconds, region = "any" } = options;
311
374
  const confidentiality = options.confidentiality ?? 0;
312
- const collected = (await Promise.allSettled(options.operators.map(async (endpoint) => {
313
- const quote = await new GpuLeaseOperatorClient(endpoint).quote({
314
- gpuClass,
315
- durationSeconds,
316
- confidentiality,
317
- region
318
- });
319
- return {
320
- operator: endpoint.baseUrl,
321
- quote
322
- };
323
- }))).flatMap((s) => s.status === "fulfilled" ? [s.value] : []);
375
+ const deviceCount = options.deviceCount ?? 1;
376
+ const sandboxId = options.sandboxId ?? `0x${"00".repeat(32)}`;
377
+ const sandboxTeeType = options.sandboxTeeType ?? 0;
378
+ const int = (n, min, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(n) && n >= min && n <= max;
379
+ if (!/^0x[0-9a-fA-F]{64}$/.test(sandboxId) || !int(sandboxTeeType, 0, 255)) throw new Error("gpuLease: sandbox id must be bytes32, TEE type uint8");
380
+ if (!int(deviceCount, 1) || !int(durationSeconds, 1)) throw new Error("gpuLease: device count and duration must be positive");
381
+ const intent = {
382
+ gpuClass,
383
+ durationSeconds,
384
+ confidentiality,
385
+ region,
386
+ deviceCount
387
+ };
388
+ const intentHash = gpuLeaseIntentHash({
389
+ intentVersion: 2,
390
+ ...intent
391
+ });
392
+ const collected = (await Promise.allSettled(options.operators.map(async (endpoint) => ({
393
+ operator: endpoint.baseUrl,
394
+ quote: await new GpuLeaseOperatorClient(endpoint).quote({
395
+ ...intent,
396
+ lessee: options.chain.account
397
+ })
398
+ })))).flatMap((s) => s.status === "fulfilled" ? [s.value] : []);
324
399
  if (collected.length === 0) throw new Error("gpuLease: no operator returned a quote");
325
400
  const { ranked, rejected } = selectQuotes(collected, {
326
401
  requestedClass: gpuClass,
327
402
  requestedDurationSeconds: durationSeconds,
328
403
  requestedConfidentiality: confidentiality,
329
- requestedDeviceCount: 1,
404
+ requestedDeviceCount: deviceCount,
330
405
  now: options.now
331
406
  });
332
- if (ranked.length === 0) {
333
- const reasons = rejected.map((r) => `${r.operator}: ${r.reason.kind}`).join(", ");
334
- throw new Error(`gpuLease: every quote failed validation (${reasons})`);
335
- }
407
+ const reasons = () => rejected.map((r) => `${r.operator}: ${r.reason.kind}`).join(", ");
408
+ if (ranked.length === 0) throw new Error(`gpuLease: every quote failed validation (${reasons()})`);
336
409
  let best;
337
410
  for (const candidate of ranked) {
338
- const identity = await validateQuoteIdentity(candidate.validated.quote);
411
+ const endpoint = options.operators.find((entry) => entry.baseUrl === candidate.operator);
412
+ if (!endpoint) throw new Error("gpuLease: quote endpoint is unknown");
413
+ const identity = await validateQuoteIdentity(candidate.validated.quote, { pinnedOperator: endpoint.address });
339
414
  if ("kind" in identity) {
340
415
  rejected.push({
341
416
  operator: candidate.operator,
@@ -345,75 +420,109 @@ async function gpuLease(options) {
345
420
  }
346
421
  best = {
347
422
  ...candidate,
348
- validated: identity
423
+ validated: identity,
424
+ endpoint
349
425
  };
350
426
  break;
351
427
  }
352
- if (!best) {
353
- const reasons = rejected.map((r) => `${r.operator}: ${r.reason.kind}`).join(", ");
354
- throw new Error(`gpuLease: no quote passed identity verification (${reasons})`);
355
- }
356
- const operatorAddress = best.validated.quote.operatorAddress;
357
- const intentHash = gpuLeaseIntentHash({
358
- intentVersion: 1,
359
- gpuClass,
360
- durationSeconds,
361
- confidentiality,
362
- region
363
- });
364
- const leaseId = await options.chain.createVaultLease({
365
- operator: operatorAddress,
366
- pricePerSecondWei: best.validated.pricePerSecondWei,
367
- durationSeconds: BigInt(durationSeconds),
368
- intentHash,
369
- confidentiality,
370
- endpointInfo: "{}",
371
- escrowWei: best.validated.escrowTotalWei
372
- });
373
- const encoded = encodeGpuLeaseRequest({
374
- intentVersion: 1,
375
- intentHash,
376
- pricePerSecondWei: best.validated.pricePerSecondWei,
377
- durationSeconds: BigInt(durationSeconds),
378
- confidentiality,
379
- gpuClass,
380
- region,
381
- lessee: options.chain.account,
382
- leaseId
383
- });
384
- const output = decodeGpuLeaseOutput(await options.chain.submitJob(GPU_LEASE_JOBS.LEASE, encoded));
385
- if (output.leaseId !== leaseId) throw new Error(`gpuLease: job returned leaseId ${output.leaseId}, expected the vault leaseId ${leaseId} (one identity across money and routing)`);
386
- return {
387
- lease: {
428
+ if (!best) throw new Error(`gpuLease: no quote passed identity verification (${reasons()})`);
429
+ if (best.validated.quote.intentHash.toLowerCase() !== intentHash.toLowerCase()) throw new Error("gpuLease: quote does not bind the requested intent");
430
+ let leaseId;
431
+ let bound = false;
432
+ try {
433
+ leaseId = await options.chain.createVaultLease({
434
+ operator: best.validated.quote.operatorAddress,
435
+ pricePerSecondWei: best.validated.pricePerSecondWei,
436
+ durationSeconds: BigInt(durationSeconds),
437
+ intentHash,
438
+ confidentiality,
439
+ endpointInfo: "{}",
440
+ escrowWei: best.validated.escrowTotalWei,
441
+ deviceCount
442
+ });
443
+ await options.onEscrowed?.(leaseId);
444
+ const encoded = encodeGpuLeaseRequest({
445
+ ...intent,
446
+ intentVersion: 2,
447
+ intentHash,
448
+ pricePerSecondWei: best.validated.pricePerSecondWei,
449
+ durationSeconds: BigInt(durationSeconds),
450
+ lessee: options.chain.account,
388
451
  leaseId,
389
- endpoint: output.endpoint,
390
- schemaVersion: output.schemaVersion,
391
- quote: best.validated
452
+ sandboxId,
453
+ sandboxTeeType
454
+ });
455
+ const result = await options.chain.submitJob(GPU_LEASE_JOBS.LEASE, encoded);
456
+ bound = true;
457
+ const output = decodeGpuLeaseOutput(result);
458
+ if (output.leaseId !== leaseId) throw new Error("gpuLease: result does not match the escrowed lease");
459
+ const { credential, access } = await openGpuLeaseSession(best.endpoint, leaseId, options.chain);
460
+ return {
461
+ lease: {
462
+ ...output,
463
+ endpoint: access.endpoint,
464
+ quote: best.validated,
465
+ credential
466
+ },
467
+ rankedOperators: ranked.map((r) => r.operator)
468
+ };
469
+ } catch (error) {
470
+ if (!leaseId) throw error;
471
+ const cleanup = bound ? releaseGpuLease(leaseId, options.chain) : options.chain.releaseLease(leaseId);
472
+ throw new GpuLeaseEscrowError(leaseId, error, await cleanup.then(() => void 0, (cleanupError) => cleanupError ?? "release failed"));
473
+ }
474
+ }
475
+ /** Sign only the SDK owner message bound to client-owned chain, contracts, operator and lease. */
476
+ async function openGpuLeaseSession(endpoint, leaseId, chain) {
477
+ const client = new GpuLeaseOperatorClient(endpoint);
478
+ const { nonce, message, expiresAt } = await client.sessionChallenge(leaseId, chain.account);
479
+ const domain = await chain.sessionDomain();
480
+ const addressBytes = (address) => {
481
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address) || /^0x0{40}$/.test(address)) throw new Error("gpuLease: invalid client session domain address");
482
+ return Array.from(hexToBytes(address));
483
+ };
484
+ if (!Number.isSafeInteger(domain.chainId) || domain.chainId <= 0 || !/^0x[0-9a-fA-F]{64}$/.test(leaseId) || !Number.isSafeInteger(expiresAt)) throw new Error("gpuLease: invalid client session domain or expiry");
485
+ const expected = `Blueprint resource access\n${JSON.stringify([
486
+ {
487
+ audience: `gpu-lease:${domain.blueprintAddress.toLowerCase()}`,
488
+ chain_id: domain.chainId,
489
+ operator: addressBytes(endpoint.address),
490
+ contract: addressBytes(domain.vaultAddress)
392
491
  },
393
- rankedOperators: ranked.map((r) => r.operator)
492
+ {
493
+ service_id: [0, 0],
494
+ resource: leaseId.toLowerCase().slice(2)
495
+ },
496
+ chain.account.toLowerCase().slice(2),
497
+ nonce.slice(2),
498
+ expiresAt,
499
+ ["gpu:attach", "gpu:exec"]
500
+ ])}`;
501
+ addressBytes(domain.blueprintAddress);
502
+ addressBytes(chain.account);
503
+ const ttl = expiresAt - Date.now() / 1e3;
504
+ if (!/^0x[0-9a-f]{64}$/.test(nonce) || message !== expected || !(ttl > 0 && ttl <= 360)) throw new Error("gpuLease: operator challenge is not for this lease");
505
+ const credential = await client.sessionVerify(nonce, await chain.signMessage(message));
506
+ const access = await client.access(leaseId, credential.token);
507
+ if (credential.leaseId !== leaseId || access.leaseId !== leaseId || access.lessee.toLowerCase() !== chain.account.toLowerCase()) throw new Error("gpuLease: access identity does not match the escrowed lease");
508
+ return {
509
+ credential,
510
+ access
394
511
  };
395
512
  }
396
- /** Teardown: voluntary release with an exact-refund receipt (I3/I4). */
397
513
  async function releaseGpuLease(leaseId, chain) {
398
514
  const { refundWei, operatorTakeWei } = await chain.releaseLease(leaseId);
515
+ await chain.submitJob(GPU_LEASE_JOBS.RELEASE, encodeAbiParameters([{ type: "bytes32" }], [leaseId]));
399
516
  return {
400
517
  leaseId,
401
518
  refundWei,
402
519
  operatorTakeWei
403
520
  };
404
521
  }
405
- /**
406
- * Refund projection for UI meters. Uses the chain clock when the injected
407
- * chain provides `chainNow()`; otherwise requires an explicit timestamp.
408
- * Never Date.now() — the drift lesson from the blueprint's own E2E.
409
- */
410
522
  async function projectGpuLeaseRefund(leaseId, chain, explicitNowSeconds) {
411
523
  const lease = await chain.readLease(leaseId);
412
- let nowSeconds = explicitNowSeconds;
413
- if (nowSeconds === void 0) {
414
- if (!chain.chainNow) throw new Error("projectGpuLeaseRefund: chain has no chainNow() — pass explicitNowSeconds");
415
- nowSeconds = await chain.chainNow();
416
- }
524
+ const nowSeconds = explicitNowSeconds ?? await chain.chainNow?.();
525
+ if (nowSeconds === void 0) throw new Error("projectGpuLeaseRefund: pass explicitNowSeconds or a chain with chainNow()");
417
526
  const { refundWei, operatorTakeWei } = projectRefundWei(lease, nowSeconds);
418
527
  return {
419
528
  refundWei,
@@ -422,4 +531,4 @@ async function projectGpuLeaseRefund(leaseId, chain, explicitNowSeconds) {
422
531
  };
423
532
  }
424
533
  //#endregion
425
- export { GPU_LEASE_JOBS, GPU_LEASE_REQUEST_ABI, GPU_LEASE_SCHEMA_VERSION, GPU_LEASE_VAULT_ABI, GpuLeaseOperatorClient, INTENT_VERSION, canonicalQuotePayload, decodeGpuLeaseOutput, encodeGpuLeaseRequest, gpuLease, gpuLeaseIntentHash, maxAffordableSeconds, projectGpuLeaseRefund, projectRefundWei, releaseGpuLease, selectQuotes, validateOperatorQuote, validateQuoteIdentity, verifyOperatorQuote };
534
+ export { GPU_LEASE_JOBS, GPU_LEASE_REQUEST_ABI, GPU_LEASE_SCHEMA_VERSION, GPU_LEASE_VAULT_ABI, GpuLeaseEscrowError, GpuLeaseOperatorClient, INTENT_VERSION, canonicalQuotePayload, createViemGpuLeaseChain, decodeGpuLeaseOutput, encodeGpuLeaseRequest, gpuLease, gpuLeaseIntentHash, openGpuLeaseSession, projectGpuLeaseRefund, projectRefundWei, releaseGpuLease, selectQuotes, validateOperatorQuote, validateQuoteIdentity, verifyOperatorQuote };