stuntman 0.2.4 → 0.2.5

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.
@@ -0,0 +1,604 @@
1
+ // Practice API for Attesta, the GPU rental market for agents on Robinhood Chain.
2
+ //
3
+ // Point an agent's Attesta base URL at the practice API instead of
4
+ // https://api.attestagpu.xyz:
5
+ // local practice http://127.0.0.1:8545/attesta
6
+ // witnessed https://stuntmanhq.xyz/w/<key>/attesta
7
+ //
8
+ // Catalog reads and quotes come from the real Attesta API, so GPUs and prices
9
+ // are real. Everything that would spend is answered here and never reaches
10
+ // Attesta: sign-in gives a practice key, previews use Attesta's default spend
11
+ // policy, and a launch builds the real Bull stream transactions (from Bull's
12
+ // own API) for the agent to send through Stuntman, where they are played out
13
+ // with practice USDG. No GPU is held and no real job is created. The agent's
14
+ // real Attesta key is never asked for and never forwarded.
15
+ import { randomBytes } from 'node:crypto';
16
+ import { keccak256, toHex, verifyMessage } from 'viem';
17
+ import { checksum, lower } from './chain.js';
18
+ import { BULL_STREAMS, USDG, nameAddress, streamsCreated, usdg, usdgRaw } from './bull.js';
19
+ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
20
+ import { join } from 'node:path';
21
+ import { ensureHome } from './config.js';
22
+ import { fund } from './engine.js';
23
+ import { findTakeByHash, readTakes } from './store.js';
24
+ export const ATTESTA_URL = 'https://api.attestagpu.xyz';
25
+ export const BULL_URL = 'https://www.bull.family';
26
+ /** Stand-ins for Attesta's treasury and executor, whose live addresses aren't published. */
27
+ export const PRACTICE_TREASURY = '0x5354554e544d414e00000000000000000000a77e';
28
+ export const PRACTICE_EXECUTOR = '0x5354554e544d414e00000000000000000000e1ec';
29
+ nameAddress(PRACTICE_TREASURY, 'Attesta (practice fee stream)');
30
+ const DEFAULT_POLICY = {
31
+ hourly_cap_usdg: '100',
32
+ session_cap_usdg: '1000',
33
+ daily_cap_usdg: '1000',
34
+ max_hours_per_job: 24,
35
+ max_mutations_per_hour: 10,
36
+ allow_skus: ['H100', 'H200'],
37
+ allow_trust_classes: ['aggregated', 'bonded_attested', 'confidential'],
38
+ };
39
+ const MIN_JOB = usdgRaw('10');
40
+ const MAX_JOB = usdgRaw('1000');
41
+ const FUNDING_GRACE_MS = 15 * 60_000;
42
+ const PREVIEW_TTL_MS = 5 * 60_000;
43
+ const RESERVE_MS = 5 * 60_000;
44
+ const MAX_ENTRIES = 200;
45
+ export function emptyBook() {
46
+ return { challenges: {}, keys: {}, quotes: {}, previews: {}, reserves: {}, jobs: {}, usedStreams: {}, mutations: [], idem: {} };
47
+ }
48
+ const err = (status, code, message) => ({ status, body: { error: { code, message } } });
49
+ const iso = (ms) => new Date(ms).toISOString();
50
+ const id = (prefix) => `${prefix}_practice_${randomBytes(9).toString('hex')}`;
51
+ function trim(rec, at) {
52
+ const keys = Object.keys(rec);
53
+ if (keys.length <= MAX_ENTRIES)
54
+ return;
55
+ keys.sort((a, b) => at(rec[a]) - at(rec[b])).slice(0, keys.length - MAX_ENTRIES).forEach((k) => delete rec[k]);
56
+ }
57
+ /** Handles one request to the practice API. `path` starts at /v1. */
58
+ export async function handleAttesta(ctx, method, path, query, headers, rawBody) {
59
+ const now = (ctx.now ?? Date.now)();
60
+ const fetcher = ctx.fetcher ?? fetch;
61
+ const attesta = (ctx.attestaUrl ?? process.env.STUNTMAN_ATTESTA_URL ?? ATTESTA_URL).replace(/\/$/, '');
62
+ const head = (name) => {
63
+ const v = headers[name];
64
+ return Array.isArray(v) ? v[0] : v;
65
+ };
66
+ let body = {};
67
+ if (rawBody) {
68
+ try {
69
+ body = JSON.parse(rawBody) ?? {};
70
+ }
71
+ catch {
72
+ return err(400, 'bad_json', 'body is not JSON');
73
+ }
74
+ }
75
+ // Public reads go to the real Attesta API. Nothing identifying is forwarded.
76
+ const forward = async () => {
77
+ let res;
78
+ try {
79
+ res = await fetcher(`${attesta}${path}${query}`, {
80
+ method,
81
+ headers: { 'content-type': 'application/json', accept: 'application/json', 'user-agent': 'stuntman-practice' },
82
+ body: method === 'GET' ? undefined : rawBody,
83
+ signal: AbortSignal.timeout(20_000),
84
+ });
85
+ }
86
+ catch (e) {
87
+ return err(502, 'attesta_unreachable', `Could not reach Attesta at ${attesta}: ${e.message}`);
88
+ }
89
+ const text = await res.text();
90
+ let parsed = text;
91
+ try {
92
+ parsed = JSON.parse(text);
93
+ }
94
+ catch {
95
+ /* keep text */
96
+ }
97
+ return { status: res.status, body: parsed };
98
+ };
99
+ if (method === 'GET' && (path === '/v1/health' || path === '/v1/skus' || path === '/v1/offers' || /^\/v1\/providers\/[^/]+$/.test(path) || /^\/v1\/credits\/[^/]+$/.test(path))) {
100
+ const out = await forward();
101
+ if (path === '/v1/health' && out.status === 200 && out.body && typeof out.body === 'object') {
102
+ return { status: 200, body: { ...out.body, practice: true, note: 'Stuntman practice API: spending is practiced, never sent to Attesta.' } };
103
+ }
104
+ return out;
105
+ }
106
+ const book = await ctx.readBook();
107
+ const save = async () => {
108
+ trim(book.challenges, (v) => v.expiresAt);
109
+ trim(book.quotes, (v) => v.savedAt);
110
+ trim(book.previews, (v) => v.expiresAt);
111
+ trim(book.jobs, (v) => v.updatedAt);
112
+ trim(book.idem, (v) => v.at);
113
+ book.mutations = book.mutations.filter((t) => now - t < 3_600_000);
114
+ await ctx.writeBook(book);
115
+ };
116
+ if (method === 'POST' && path === '/v1/quotes') {
117
+ const out = await forward();
118
+ const q = out.body;
119
+ if (out.status < 300 && q && typeof q.quote_id === 'string') {
120
+ book.quotes[q.quote_id] = { view: q, savedAt: now };
121
+ await save();
122
+ }
123
+ return out;
124
+ }
125
+ // ---- sign-in: practice keys only
126
+ if (method === 'POST' && path === '/v1/auth/challenge') {
127
+ const wallet = String(body.wallet ?? '');
128
+ if (!/^0x[0-9a-fA-F]{40}$/.test(wallet))
129
+ return err(400, 'bad_wallet', 'wallet is required');
130
+ if (lower(wallet) !== lower(ctx.account))
131
+ return err(403, 'not_practice_wallet', `This practice API is for ${checksum(ctx.account)}, the wallet Stuntman practices as.`);
132
+ const role = body.role === 'provider' ? 'provider' : 'buyer';
133
+ if (role !== 'buyer')
134
+ return err(400, 'practice_unsupported', 'Practice covers renting GPUs (role buyer).');
135
+ const nonce = randomBytes(16).toString('hex');
136
+ const message = `Attesta sign-in (Stuntman practice)\nWallet: ${checksum(wallet)}\nRole: ${role}\nChain ID: ${ctx.chainId}\nNonce: ${nonce}\nIssued At: ${iso(now)}`;
137
+ book.challenges[nonce] = { wallet: checksum(wallet), role, message, expiresAt: now + 10 * 60_000 };
138
+ await save();
139
+ return { status: 200, body: { nonce, message } };
140
+ }
141
+ if (method === 'POST' && path === '/v1/auth/login') {
142
+ const ch = book.challenges[String(body.nonce ?? '')];
143
+ if (!ch || ch.expiresAt < now)
144
+ return err(400, 'challenge_expired', 'sign-in challenge missing or expired');
145
+ const signature = String(body.signature ?? '');
146
+ let ok = false;
147
+ try {
148
+ ok = /^0x[0-9a-fA-F]+$/.test(signature) && (await verifyMessage({ address: ch.wallet, message: ch.message, signature: signature }));
149
+ }
150
+ catch {
151
+ ok = false;
152
+ }
153
+ if (!ok)
154
+ return err(403, 'bad_signature', 'signature does not match wallet');
155
+ delete book.challenges[String(body.nonce)];
156
+ const key = `atk_practice_${randomBytes(24).toString('hex')}`;
157
+ book.keys[keccak256(toHex(key))] = { wallet: ch.wallet, role: ch.role, at: now };
158
+ await save();
159
+ return { status: 201, body: { api_key: key, wallet: ch.wallet, kind: ch.role, practice: true } };
160
+ }
161
+ // ---- everything below needs a practice key
162
+ const bearer = (head('authorization') ?? '').replace(/^Bearer\s+/i, '').trim();
163
+ const caller = bearer ? book.keys[keccak256(toHex(bearer))] : undefined;
164
+ const keyed = /^\/v1\/(spend|jobs|policy)/.test(path) || path === '/v1/receipts' || /^\/v1\/receipts\/job_practice_/.test(path);
165
+ if (method === 'GET' && /^\/v1\/receipts\/[^/]+$/.test(path) && !/job_practice_/.test(path))
166
+ return forward();
167
+ if (!keyed)
168
+ return err(404, 'not_found', `${method} ${path} is not part of the practice API.`);
169
+ if (!caller) {
170
+ return err(401, 'practice_key_required', bearer.startsWith('atk_') && !bearer.startsWith('atk_practice_')
171
+ ? 'That is a real Attesta key. The practice API never uses it: sign in here (POST /v1/auth/challenge, then /v1/auth/login) for a practice key.'
172
+ : 'Sign in first: POST /v1/auth/challenge with your wallet, sign the message, then POST /v1/auth/login.');
173
+ }
174
+ // Idempotency, like the real API: a repeated key replays the first answer.
175
+ const idemKey = head('idempotency-key');
176
+ if (method === 'POST') {
177
+ if (!idemKey || idemKey.length < 8)
178
+ return err(400, 'idempotency_key_required', 'send an Idempotency-Key header (8+ characters, new per action) on every signed-in POST');
179
+ const seen = book.idem[`${path}:${idemKey}`];
180
+ if (seen)
181
+ return { status: seen.status, body: seen.body };
182
+ }
183
+ const answer = async (status, out) => {
184
+ if (method === 'POST' && idemKey && status < 300)
185
+ book.idem[`${path}:${idemKey}`] = { at: now, status, body: out };
186
+ await save();
187
+ return { status, body: out };
188
+ };
189
+ const bull = (ctx.bullUrl ?? process.env.STUNTMAN_BULL_URL ?? BULL_URL).replace(/\/$/, '');
190
+ const prepareStream = async (key, kind, payee, amountUsdg, durationSeconds, intervalIndex) => {
191
+ const res = await fetcher(`${bull}/api/v1/streams`, {
192
+ method: 'POST',
193
+ headers: { 'content-type': 'application/json', 'user-agent': 'stuntman-practice' },
194
+ body: JSON.stringify({ chain: 'robinhood', payer: checksum(ctx.account), payee, arbiter: PRACTICE_EXECUTOR, amount: amountUsdg, token: 'usdg', durationSeconds }),
195
+ signal: AbortSignal.timeout(20_000),
196
+ });
197
+ const text = await res.text();
198
+ if (!res.ok)
199
+ throw Object.assign(new Error(`Bull could not prepare the stream (${res.status}): ${text.slice(0, 200)}`), { code: 'bull_error' });
200
+ const r = JSON.parse(text);
201
+ for (const s of r.steps ?? []) {
202
+ if (Number(s.transaction.chainId) !== ctx.chainId || lower(s.transaction.from) !== lower(ctx.account))
203
+ throw Object.assign(new Error(`Bull returned a ${s.name} step for another chain or wallet`), { code: 'bull_safe_send_failed' });
204
+ if (s.name === 'createStream' && lower(s.transaction.to) !== BULL_STREAMS)
205
+ throw Object.assign(new Error('Bull returned a createStream step for an unexpected contract'), { code: 'bull_safe_send_failed' });
206
+ if (s.name === 'approve' && lower(s.transaction.to) !== USDG)
207
+ throw Object.assign(new Error('Bull returned an approve step on an unexpected token'), { code: 'bull_safe_send_failed' });
208
+ }
209
+ if (!r.steps?.some((s) => s.name === 'createStream'))
210
+ throw Object.assign(new Error('Bull returned no createStream step'), { code: 'bull_safe_send_failed' });
211
+ return {
212
+ key,
213
+ kind,
214
+ ...(intervalIndex !== undefined ? { intervalIndex } : {}),
215
+ payee,
216
+ amountUsdg,
217
+ durationSeconds,
218
+ steps: r.steps,
219
+ bullFeeUsd: String(r.feeUsd ?? ''),
220
+ deadline: Math.min((Number(r.quoteExpiresAt) || Infinity) * 1000, now + FUNDING_GRACE_MS),
221
+ status: 'awaiting_funding',
222
+ };
223
+ };
224
+ const providerPayee = (job) => {
225
+ const who = String(job.quote.offer_id ?? 'provider').split(':')[0];
226
+ const addr = `0x5354554e544d414e${keccak256(toHex(who)).slice(-24)}`;
227
+ nameAddress(addr, `GPU provider ${who} (practice)`);
228
+ return addr;
229
+ };
230
+ const move = (job, to, reason) => {
231
+ job.history.push({ at: iso(now), from: job.state, to, reason });
232
+ job.state = to;
233
+ job.updatedAt = now;
234
+ };
235
+ // Bring a practice job up to date: next slices, finished streams, the end of the job.
236
+ const advance = async (job) => {
237
+ if (!['running', 'streaming'].includes(job.state))
238
+ return;
239
+ const slices = job.streams.filter((s) => s.kind === 'provider');
240
+ const last = slices.at(-1);
241
+ for (const s of job.streams)
242
+ if (s.status === 'active' && s.end !== undefined && s.end * 1000 <= now)
243
+ s.status = 'completed';
244
+ const lastIndex = last.intervalIndex ?? 0;
245
+ if (last.status === 'awaiting_funding') {
246
+ if (last.deadline < now)
247
+ move(job, 'paused', `interval ${lastIndex} was not funded in time`);
248
+ return;
249
+ }
250
+ const endsAt = (last.end ?? 0) * 1000;
251
+ if (lastIndex + 1 >= job.plannedIntervals) {
252
+ if (endsAt <= now)
253
+ move(job, 'settled', 'all intervals done');
254
+ return;
255
+ }
256
+ if (endsAt - now <= 5 * 60_000) {
257
+ job.streams.push(await prepareStream(`slice:${lastIndex + 1}`, 'provider', providerPayee(job), job.netPerIntervalUsdg, job.intervalSeconds, lastIndex + 1));
258
+ job.updatedAt = now;
259
+ }
260
+ };
261
+ const view = (job) => {
262
+ const slices = job.streams.filter((s) => s.kind === 'provider' && s.status !== 'awaiting_funding');
263
+ const cur = slices.at(-1);
264
+ return {
265
+ id: job.id,
266
+ state: job.state,
267
+ practice: true,
268
+ sku: job.quote.sku,
269
+ gpus: job.quote.gpus,
270
+ trust_class: job.quote.trust_class,
271
+ region: job.quote.region,
272
+ provider_id: String(job.quote.offer_id ?? '').split(':')[0] || null,
273
+ buyer: checksum(ctx.account),
274
+ interval_seconds: job.intervalSeconds,
275
+ planned_intervals: job.plannedIntervals,
276
+ verified_intervals: slices.filter((s) => s.status === 'completed').length,
277
+ current_interval: cur ? { index: cur.intervalIndex, state: cur.status === 'completed' ? 'verified' : 'running', start: cur.start ? iso(cur.start * 1000) : null, end: cur.end ? iso(cur.end * 1000) : null, net_usdg: cur.amountUsdg, metered: false } : null,
278
+ authorized_usdg: job.authorizedUsdg,
279
+ credits_usdg: job.creditsUsdg,
280
+ policy_hash: 'practice',
281
+ streams: job.streams.map((s) => ({ key: s.key, kind: s.kind, status: s.status, stream_id: s.streamId ?? null, amount_usdg: s.amountUsdg, payee: s.payee })),
282
+ next_actions: job.streams
283
+ .filter((s) => s.status === 'awaiting_funding')
284
+ .map((s) => ({ kind: 'fund', stream_key: s.key, amount_usdg: s.amountUsdg, bull_fee_usd: s.bullFeeUsd, deadline: iso(s.deadline), steps: s.steps, why: s.kind === 'fee' ? 'Attesta fee stream (practice)' : `provider stream for interval ${s.intervalIndex} (practice)` })),
285
+ access: null,
286
+ backend: null,
287
+ backend_error: null,
288
+ close_reason: job.closeReason ?? null,
289
+ receipt_url: `/v1/receipts/${job.id}`,
290
+ history: job.history,
291
+ created_at: iso(job.createdAt),
292
+ updated_at: iso(job.updatedAt),
293
+ note: 'Practice job: the Bull transactions are played out by Stuntman with practice USDG and never broadcast. No GPU is started.',
294
+ };
295
+ };
296
+ const jobOf = (jobId) => book.jobs[jobId];
297
+ try {
298
+ // ---- spend preview, with Attesta's default policy
299
+ if (method === 'POST' && path === '/v1/spend/preview') {
300
+ const action = String(body.action ?? '');
301
+ if (!['launch', 'reserve', 'extend', 'close'].includes(action))
302
+ return err(400, 'bad_action', 'action must be launch, reserve, extend or close');
303
+ const denials = [];
304
+ let amount = 0n;
305
+ let lineItems = null;
306
+ let summary = '';
307
+ let maxExposure = '0';
308
+ let quoteId;
309
+ let jobId;
310
+ let extraHours;
311
+ const spent = Object.values(book.jobs).filter((j) => now - j.createdAt < 86_400_000 && !['expired', 'blocked'].includes(j.state)).reduce((s, j) => s + usdgRaw(j.authorizedUsdg), 0n);
312
+ if (action === 'launch' || action === 'reserve') {
313
+ quoteId = String(body.quote_id ?? '');
314
+ const q = book.quotes[quoteId]?.view;
315
+ if (!q)
316
+ return err(404, 'not_found', 'quote not found. Create quotes through the practice API so it knows them.');
317
+ if (Date.parse(q.expires_at) < now)
318
+ return err(400, 'quote_expired', 'quote expired; create a new one');
319
+ amount = usdgRaw(q.line_items?.totalUsdg ?? '0');
320
+ lineItems = q.line_items;
321
+ maxExposure = String(q.max_exposure_usdg ?? '');
322
+ const hours = (Number(q.planned_intervals) * Number(q.interval_minutes)) / 60;
323
+ const perHour = hours ? (amount * 3600n) / BigInt(Math.round(hours * 3600)) : 0n;
324
+ if (!DEFAULT_POLICY.allow_skus.includes(q.sku))
325
+ denials.push(`policy_denied: sku ${q.sku} not allowed by policy`);
326
+ if (hours > DEFAULT_POLICY.max_hours_per_job)
327
+ denials.push(`policy_denied: ${hours}h exceeds max_hours_per_job ${DEFAULT_POLICY.max_hours_per_job}`);
328
+ if (perHour > usdgRaw(DEFAULT_POLICY.hourly_cap_usdg))
329
+ denials.push(`policy_denied: ${usdg(perHour)} USDG/hour exceeds hourly cap ${DEFAULT_POLICY.hourly_cap_usdg}`);
330
+ if (amount > MAX_JOB)
331
+ denials.push(`job_cap_exceeded: job total ${usdg(amount)} exceeds cap ${usdg(MAX_JOB)} USDG`);
332
+ if (action === 'launch' && amount < MIN_JOB)
333
+ denials.push(`below_min_job: ${usdg(amount)} is below the minimum job of ${usdg(MIN_JOB)} USDG`);
334
+ summary = `${action === 'launch' ? 'Launch' : 'Reserve'} ${q.gpus}x ${q.sku} (${q.trust_class}) for ${q.planned_intervals} x ${q.interval_minutes} min: up to ${usdg(amount)} USDG (provider ${q.line_items?.providerNetUsdg} + Attesta fee ${q.line_items?.attestaFeeUsdg}), plus about $${q.line_items?.bullFeeEstimateUsd} Bull fees in ETH. Practice: nothing is sent to Attesta.`;
335
+ }
336
+ else {
337
+ jobId = String(body.job_id ?? '');
338
+ const job = jobOf(jobId);
339
+ if (!job)
340
+ return err(404, 'not_found', 'job not found');
341
+ if (action === 'extend') {
342
+ extraHours = Number(body.extra_hours);
343
+ if (!Number.isFinite(extraHours) || extraHours <= 0)
344
+ return err(400, 'bad_hours', 'extra_hours must be a positive number');
345
+ const perInterval = usdgRaw(job.netPerIntervalUsdg) + usdgRaw(String(job.quote.line_items?.attestaFeeUsdg ?? '0')) / BigInt(job.plannedIntervals);
346
+ amount = perInterval * BigInt(Math.ceil((extraHours * 3600) / job.intervalSeconds));
347
+ const hours = (job.plannedIntervals * job.intervalSeconds) / 3600 + extraHours;
348
+ if (hours > DEFAULT_POLICY.max_hours_per_job)
349
+ denials.push(`policy_denied: ${hours}h exceeds max_hours_per_job ${DEFAULT_POLICY.max_hours_per_job}`);
350
+ if (usdgRaw(job.authorizedUsdg) + amount > MAX_JOB)
351
+ denials.push(`job_cap_exceeded: job total ${usdg(usdgRaw(job.authorizedUsdg) + amount)} exceeds cap ${usdg(MAX_JOB)} USDG`);
352
+ summary = `Extend ${job.id} by ${extraHours} h: up to ${usdg(amount)} more USDG. Practice.`;
353
+ }
354
+ else {
355
+ summary = `Close ${job.id} early and recover unvested USDG. Practice.`;
356
+ }
357
+ }
358
+ if (action !== 'close') {
359
+ if (spent + amount > usdgRaw(DEFAULT_POLICY.daily_cap_usdg))
360
+ denials.push(`policy_denied: daily cap ${DEFAULT_POLICY.daily_cap_usdg} USDG would be exceeded`);
361
+ }
362
+ if (book.mutations.filter((t) => now - t < 3_600_000).length >= DEFAULT_POLICY.max_mutations_per_hour)
363
+ denials.push(`rate_limited: ${DEFAULT_POLICY.max_mutations_per_hour} confirmed spend actions per hour`);
364
+ const pid = id('pv');
365
+ book.previews[pid] = { action, quoteId, jobId, extraHours, allowed: denials.length === 0, used: false, expiresAt: now + PREVIEW_TTL_MS, amount: usdg(amount) };
366
+ return answer(201, { preview_id: pid, action, allowed: denials.length === 0, denials, summary, line_items: lineItems, max_exposure_usdg: maxExposure, policy_hash: 'practice', expires_at: iso(now + PREVIEW_TTL_MS), practice: true });
367
+ }
368
+ const usePreview = (previewId, action, match) => {
369
+ const p = book.previews[String(previewId ?? '')];
370
+ if (!p || p.action !== action)
371
+ return err(400, 'preview_required', `POST /v1/spend/preview with action ${action} first`);
372
+ if (p.used)
373
+ return err(409, 'preview_used', 'this preview was already used');
374
+ if (p.expiresAt < now)
375
+ return err(400, 'preview_expired', 'preview expired; make a new one');
376
+ if ((match.quoteId && p.quoteId !== match.quoteId) || (match.jobId && p.jobId !== match.jobId))
377
+ return err(400, 'preview_mismatch', 'preview is for a different quote or job');
378
+ if (!p.allowed)
379
+ return err(403, 'policy_denied', 'the preview was denied by the spend policy');
380
+ p.used = true;
381
+ book.mutations.push(now);
382
+ return null;
383
+ };
384
+ if (method === 'POST' && path === '/v1/jobs/reserve') {
385
+ const quoteId = String(body.quote_id ?? '');
386
+ const bad = usePreview(body.preview_id, 'reserve', { quoteId });
387
+ if (bad)
388
+ return bad;
389
+ book.reserves[quoteId] = { quoteId, until: now + RESERVE_MS };
390
+ return answer(201, { reserve_id: quoteId, quote_id: quoteId, held_until: iso(now + RESERVE_MS), practice: true });
391
+ }
392
+ if (method === 'POST' && path === '/v1/jobs') {
393
+ const quoteId = String(body.quote_id ?? body.reserve_id ?? '');
394
+ if (!quoteId)
395
+ return err(400, 'quote_required', 'quote_id or reserve_id is required');
396
+ const q = book.quotes[quoteId]?.view;
397
+ if (!q)
398
+ return err(404, 'not_found', 'quote not found. Create quotes through the practice API so it knows them.');
399
+ const held = book.reserves[quoteId]?.until ?? 0;
400
+ if (Date.parse(q.expires_at) < now && held < now)
401
+ return err(400, 'quote_expired', 'quote expired; create a new one');
402
+ const bad = usePreview(body.preview_id, 'launch', { quoteId });
403
+ if (bad)
404
+ return bad;
405
+ const planned = Number(q.planned_intervals);
406
+ const intervalSeconds = Number(q.interval_minutes) * 60;
407
+ if (!planned || !intervalSeconds)
408
+ return err(502, 'bad_quote', 'the quote has no interval plan');
409
+ const job = {
410
+ id: id('job'),
411
+ state: 'reserved',
412
+ quote: q,
413
+ workload: body.workload ?? {},
414
+ plannedIntervals: planned,
415
+ intervalSeconds,
416
+ netPerIntervalUsdg: usdg(usdgRaw(String(q.line_items?.providerNetUsdg ?? '0')) / BigInt(planned)),
417
+ authorizedUsdg: String(q.line_items?.totalUsdg ?? '0'),
418
+ creditsUsdg: '0',
419
+ streams: [],
420
+ history: [{ at: iso(now), from: null, to: 'reserved', reason: 'launch (practice)' }],
421
+ createdAt: now,
422
+ updatedAt: now,
423
+ };
424
+ move(job, 'bond_ready', 'provider bond assumed in practice');
425
+ job.streams.push(await prepareStream('fee', 'fee', PRACTICE_TREASURY, String(q.line_items?.attestaFeeUsdg ?? '0'), planned * intervalSeconds));
426
+ job.streams.push(await prepareStream('slice:0', 'provider', providerPayee(job), job.netPerIntervalUsdg, intervalSeconds, 0));
427
+ book.jobs[job.id] = job;
428
+ delete book.reserves[quoteId];
429
+ return answer(201, view(job));
430
+ }
431
+ if (method === 'GET' && path === '/v1/jobs') {
432
+ for (const j of Object.values(book.jobs))
433
+ await advance(j);
434
+ await save();
435
+ return { status: 200, body: { jobs: Object.values(book.jobs).map((j) => ({ ...view(j), next_actions: [] })) } };
436
+ }
437
+ const one = path.match(/^\/v1\/jobs\/([^/]+)(\/(funded|close|extend))?$/);
438
+ const receipt = path.match(/^\/v1\/receipts\/(job_practice_[0-9a-f]+)$/);
439
+ if (receipt && method === 'GET') {
440
+ const job = jobOf(receipt[1]);
441
+ if (!job)
442
+ return err(404, 'not_found', 'receipt not found');
443
+ return { status: 200, body: { job_id: job.id, practice: true, state: job.state, authorized_usdg: job.authorizedUsdg, credits_usdg: job.creditsUsdg, streams: view(job).streams, history: job.history } };
444
+ }
445
+ if (one) {
446
+ const job = jobOf(decodeURIComponent(one[1]));
447
+ if (!job)
448
+ return err(404, 'not_found', 'job not found');
449
+ const action = one[3];
450
+ if (!action && method === 'GET') {
451
+ await advance(job);
452
+ await save();
453
+ return { status: 200, body: view(job) };
454
+ }
455
+ if (action === 'funded' && method === 'POST') {
456
+ const s = job.streams.find((x) => x.key === body.stream_key);
457
+ if (!s)
458
+ return err(400, 'unknown_stream', `no stream ${body.stream_key} on this job`);
459
+ const streamId = String(body.stream_id ?? '');
460
+ if (!/^[A-Za-z0-9_-]{1,80}$/.test(streamId))
461
+ return err(400, 'bad_stream_id', 'stream_id is required');
462
+ if (s.status !== 'awaiting_funding')
463
+ return err(409, 'already_funded', 'stream already confirmed');
464
+ if (s.deadline < now)
465
+ return err(409, 'funding_deadline_passed', 'funding window closed');
466
+ const hashes = Array.isArray(body.tx_hashes) ? body.tx_hashes.map(String) : [];
467
+ const takes = await ctx.takes(hashes);
468
+ // Practice streams are played out at the latest block, so Bull's id counter
469
+ // never moves and two practice streams can share an id. The take that
470
+ // created a stream tells them apart.
471
+ const given = new Set(hashes.map((h) => lower(h)));
472
+ const created = takes
473
+ .filter((t) => t.status === 'filled' && (!given.size || given.has(lower(t.txHash))))
474
+ .flatMap((t) => streamsCreated(t.logs).map((c) => ({ c, t })))
475
+ .filter((x) => x.c.id === streamId);
476
+ if (!created.length) {
477
+ return err(400, 'stream_not_found', `no practice stream ${streamId} yet. Send the createStream step for ${s.key} through Stuntman, then report the stream id from its StreamCreated event.`);
478
+ }
479
+ const fresh = created.filter((x) => !book.usedStreams[lower(x.t.txHash)]);
480
+ if (!fresh.length)
481
+ return err(409, 'stream_reused', 'stream id already used');
482
+ const mismatch = (c) => lower(c.payer) !== lower(ctx.account)
483
+ ? 'payer mismatch'
484
+ : lower(c.payee) !== lower(s.payee)
485
+ ? 'payee mismatch'
486
+ : lower(c.arbiter) !== lower(PRACTICE_EXECUTOR)
487
+ ? 'arbiter is not the Attesta executor'
488
+ : lower(c.asset) !== USDG
489
+ ? 'asset is not USDG'
490
+ : c.amount !== usdgRaw(s.amountUsdg)
491
+ ? 'deposit mismatch'
492
+ : c.end - c.start !== s.durationSeconds
493
+ ? 'duration mismatch'
494
+ : null;
495
+ const hit = fresh.find((x) => !mismatch(x.c));
496
+ if (!hit)
497
+ return err(400, 'stream_mismatch', `stream ${streamId} does not match: ${mismatch(fresh[0].c)}`);
498
+ const c = hit.c;
499
+ book.usedStreams[lower(hit.t.txHash)] = job.id;
500
+ s.status = 'active';
501
+ s.streamId = streamId;
502
+ s.txHashes = [hit.t.txHash];
503
+ s.start = c.start;
504
+ s.end = c.end;
505
+ s.steps = [];
506
+ const fee = job.streams.find((x) => x.key === 'fee');
507
+ const first = job.streams.find((x) => x.key === 'slice:0');
508
+ if (job.state === 'bond_ready' && fee?.status === 'active' && first?.status === 'active') {
509
+ move(job, 'funded', 'fee stream and first interval confirmed (practice)');
510
+ move(job, 'running', 'practice: no GPU is started');
511
+ }
512
+ else if (job.state === 'paused' && s.kind === 'provider') {
513
+ move(job, 'running', `interval ${s.intervalIndex} funded (practice)`);
514
+ }
515
+ return answer(202, view(job));
516
+ }
517
+ if (action === 'extend' && method === 'POST') {
518
+ const bad = usePreview(body.preview_id, 'extend', { jobId: job.id });
519
+ if (bad)
520
+ return bad;
521
+ const extra = Number(body.extra_hours);
522
+ const added = Math.ceil((extra * 3600) / job.intervalSeconds);
523
+ const feePerInterval = usdgRaw(String(job.quote.line_items?.attestaFeeUsdg ?? '0')) / BigInt(job.plannedIntervals);
524
+ const feeKey = `fee:${job.streams.filter((x) => x.kind === 'fee').length}`;
525
+ job.streams.push(await prepareStream(feeKey, 'fee', PRACTICE_TREASURY, usdg(feePerInterval * BigInt(added)), added * job.intervalSeconds));
526
+ job.plannedIntervals += added;
527
+ job.authorizedUsdg = usdg(usdgRaw(job.authorizedUsdg) + (usdgRaw(job.netPerIntervalUsdg) + feePerInterval) * BigInt(added));
528
+ job.updatedAt = now;
529
+ return answer(200, view(job));
530
+ }
531
+ if (action === 'close' && method === 'POST') {
532
+ const bad = usePreview(body.preview_id, 'close', { jobId: job.id });
533
+ if (bad)
534
+ return bad;
535
+ let back = 0n;
536
+ for (const s of job.streams) {
537
+ if (s.status === 'awaiting_funding') {
538
+ s.status = 'cancelled';
539
+ continue;
540
+ }
541
+ if (s.status !== 'active' || s.start === undefined || s.end === undefined)
542
+ continue;
543
+ const left = Math.max(0, s.end - Math.floor(now / 1000));
544
+ const total = Math.max(1, s.end - s.start);
545
+ back += (usdgRaw(s.amountUsdg) * BigInt(Math.min(left, total))) / BigInt(total);
546
+ s.status = 'cancelled';
547
+ }
548
+ if (back > 0n)
549
+ await ctx.credit(back);
550
+ job.creditsUsdg = usdg(back);
551
+ job.closeReason = String(body.reason ?? 'buyer early close');
552
+ move(job, 'closing', job.closeReason);
553
+ move(job, 'refunded', `practice: ${usdg(back)} unvested USDG returned to the practice balance`);
554
+ return answer(202, { ...view(job), note: `Practice: ${usdg(back)} unvested USDG went back to the practice balance. Live, next_actions would hold the Bull cancel transactions to send.` });
555
+ }
556
+ }
557
+ if (path === '/v1/policy') {
558
+ if (method === 'GET')
559
+ return { status: 200, body: { wallet: checksum(ctx.account), policy: DEFAULT_POLICY, practice: true, note: "Attesta's default spend policy. Practice doesn't change your real policy." } };
560
+ return err(400, 'practice_unsupported', 'Policy changes apply to your real Attesta account. Practice uses the default policy.');
561
+ }
562
+ return err(404, 'not_found', `${method} ${path} is not part of the practice API.`);
563
+ }
564
+ catch (e) {
565
+ const code = e.code;
566
+ if (code === 'bull_error' || code === 'bull_safe_send_failed')
567
+ return err(502, code, e.message);
568
+ if (e instanceof Error && /fetch failed|timeout|aborted/i.test(e.message))
569
+ return err(502, 'bull_unreachable', `Could not reach Bull to prepare the stream: ${e.message}`);
570
+ throw e;
571
+ }
572
+ }
573
+ // ---- local practice: the book lives next to the practice ledger
574
+ export function localAttestaContext(engine) {
575
+ const path = join(ensureHome(), 'attesta.json');
576
+ const account = lower(engine.cfg.account);
577
+ return {
578
+ account: engine.cfg.account,
579
+ chainId: engine.cfg.chainId,
580
+ async readBook() {
581
+ if (!existsSync(path))
582
+ return emptyBook();
583
+ try {
584
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
585
+ return parsed.account === account && parsed.book ? { ...emptyBook(), ...parsed.book } : emptyBook();
586
+ }
587
+ catch {
588
+ return emptyBook();
589
+ }
590
+ },
591
+ async writeBook(book) {
592
+ const tmp = `${path}.${process.pid}.tmp`;
593
+ writeFileSync(tmp, JSON.stringify({ account, book }) + '\n', { mode: 0o600 });
594
+ renameSync(tmp, path);
595
+ },
596
+ async takes(hashes) {
597
+ const found = hashes.map((h) => findTakeByHash(h)).filter((t) => !!t);
598
+ return [...found, ...readTakes().slice(-50)];
599
+ },
600
+ async credit(raw) {
601
+ await fund(engine, USDG, raw);
602
+ },
603
+ };
604
+ }