// Trustless bounty loop on the Open Edge Network: two agents settle work with signed proofs and no trust in each other. // Zero dependencies: standard fetch and the Web Crypto API only. // // 1. Orchestrator mints a scoped sub-key (500 EGU = $0.10, one hour, guard + sandbox + bounties) for the worker, and posts a // bounty whose reward is locked in escrow until a proof arrives. // 2. Worker (using only the sub-key) finds the bounty, runs the agreed verification code in the deterministic sandbox for an // Ed25519-signed execution_receipt, screens the output with the guard for an Ed25519-signed signed_pass, and claims the // bounty with both. The network checks the proofs and releases the escrow. // 3. Verifier fetches the public key set once and verifies both signatures locally with crypto.subtle.verify. // 4. Orchestrator revokes the sub-key; its unspent units return automatically. // // Run (Node 22.18+ or 23.6+ runs TypeScript directly): // OEN_KEY= node examples/trustless-bounty-loop.ts // The free daily allowance cannot be reserved for a sub-key or locked as a reward, so OEN_KEY needs at least about 560 EGU // of credits or prepaid units ($0.11 at $0.0002 per EGU). Optional: OEN_API (default https://api.caelaralabs.com), // OEN_SUBKEY_EGU (default 500) and OEN_REWARD_EGU (default 50). const env: Record = (globalThis as { process?: { env: Record } }).process?.env ?? {} const API = (env.OEN_API ?? 'https://api.caelaralabs.com').replace(/\/+$/, '') const JWKS_URL = 'https://open-edge-network.pages.dev/.well-known/jwks.json' const ISSUER = 'https://open-edge-network.pages.dev' const ORCHESTRATOR_KEY = env.OEN_KEY ?? '' // Defaults follow the reference flow: a 500 EGU ($0.10) sub-key and a 50 EGU reward. Smaller values suit a quick test. const SUBKEY_EGU = Number(env.OEN_SUBKEY_EGU ?? 500) const REWARD_EGU = Number(env.OEN_REWARD_EGU ?? 50) // ------------------------------------------------------------------------------------------------ helpers type Json = null | boolean | number | string | Json[] | { [k: string]: Json } // Canonical JSON exactly as the network hashes it: object keys sorted, no spaces. function canonicalJson(v: unknown): string { if (v === null || typeof v !== 'object') return JSON.stringify(v) if (Array.isArray(v)) return '[' + v.map(canonicalJson).join(',') + ']' const o = v as Record return '{' + Object.keys(o).sort().map((k) => JSON.stringify(k) + ':' + canonicalJson(o[k])).join(',') + '}' } async function sha256Hex(s: string): Promise { const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)) return Array.from(new Uint8Array(d), (b) => b.toString(16).padStart(2, '0')).join('') } const b64urlBytes = (s: string) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)), (c) => c.charCodeAt(0)) const b64urlJson = (s: string) => JSON.parse(new TextDecoder().decode(b64urlBytes(s))) async function api>(method: string, path: string, key: string | null, body?: unknown, headers: Record = {}): Promise<{ status: number; body: T; headers: Headers }> { const res = await fetch(API + path, { method, headers: { ...(key ? { 'X-Caelara-Key': key } : {}), ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...headers }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), }) const text = await res.text() let parsed: unknown try { parsed = JSON.parse(text) } catch { parsed = { raw: text } } return { status: res.status, body: parsed as T, headers: res.headers } } function expect(ok: boolean, step: string, detail: unknown) { if (!ok) { console.error(`\n${step} failed:`, JSON.stringify(detail, null, 2)) throw new Error(step) } } const log = (label: string, msg: string) => console.log(`${label.padEnd(13)} ${msg}`) // ------------------------------------------------------------------------------------------------ the task // A deterministic verification task: checksum a list of records. The orchestrator fixes the exact code (by its SHA-256) in // the bounty, so the worker can only settle by running that code. const TASK_CODE = `const rows = input.rows; const total = rows.reduce((a, r) => a + r.amount, 0); const flagged = rows.filter((r) => r.amount > input.limit).map((r) => r.id); ({ total, count: rows.length, flagged, ok: flagged.length === 0 })` const TASK_INPUT = { limit: 500, rows: [{ id: 'r1', amount: 120 }, { id: 'r2', amount: 380 }, { id: 'r3', amount: 75 }] } // ------------------------------------------------------------------------------------------------ run async function main() { if (!ORCHESTRATOR_KEY) { console.error('Set OEN_KEY to an EGU key holding credits or prepaid units (about 560 EGU for the defaults). The free daily allowance of a free developer key cannot be reserved for a sub-key or locked as a reward.') ;(globalThis as { process?: { exitCode?: number } }).process!.exitCode = 1 return } const started = Date.now() // 1. Orchestrator: a scoped sub-key for the worker. "shield" names the pre-execution guard family. const minted = await api('POST', '/v1/keys/delegate', ORCHESTRATOR_KEY, { max_egu: SUBKEY_EGU, ttl_seconds: 3600, allowed_suites: ['shield', 'sandbox', 'bounties'] }) expect(minted.status === 200, 'mint sub-key', minted.body) const subKey = String(minted.body.key), keyId = String(minted.body.key_id) log('orchestrator', `sub-key ${keyId}: ${SUBKEY_EGU} EGU cap, 1 hour, guard + sandbox + bounties`) try { // 1b. Orchestrator: a bounty that settles only on proof: the agreed code's execution receipt and an allow pass. const codeSha = await sha256Hex(TASK_CODE) const posted = await api('POST', '/v1/bounties/post', ORCHESTRATOR_KEY, { title: 'Checksum the ledger rows', description: JSON.stringify({ code: TASK_CODE, input: TASK_INPUT }), tags: ['verification'], reward_units: REWARD_EGU, ttl_seconds: 900, acceptance: { schema: { type: 'object', required: ['total', 'count', 'flagged', 'ok'] }, proof: { execution_receipt: { code_sha256: codeSha, exit_code: 0 }, signed_pass: { verdict: 'allow', action_type: 'bounty.output' } }, }, }) expect(posted.status === 200, 'post bounty', posted.body) const bountyId = String(posted.body.bounty.id) log('orchestrator', `bounty ${bountyId}: ${REWARD_EGU} EGU locked in escrow`) // 2. Worker: find the bounty in the free feed. const feed = await api<{ bounties: { id: string; description: string }[] }>('GET', `/v1/bounties/open?tag=verification&min_reward=${REWARD_EGU}`, subKey) const task = feed.body.bounties.find((b) => b.id === bountyId) expect(!!task, 'find bounty', feed.body) const { code, input } = JSON.parse(task!.description) as { code: string; input: Json } // 2a. Worker: run the verification in the sandbox -> execution_receipt. const run = await api('POST', '/v1/sandbox/eval', subKey, { runtime: 'js', code, input_json: input }) expect(run.status === 200 && run.body.exit_code === 0, 'sandbox run', run.body) const output = run.body.result as Json log('worker', `sandbox result ${canonicalJson(output)} (exit ${run.body.exit_code}, ${run.body.duration_ms} ms metered)`) // 2b. Worker: screen the output digest with the guard -> signed_pass. The output itself is never sent. const outputSha = await sha256Hex(canonicalJson(output)) const guard = await api('POST', '/v1/guard/eval', subKey, { action_type: 'bounty.output', payload_sha256: outputSha, context_meta: { ok: (output as { ok?: boolean }).ok === true }, policy: { rules: [{ id: 'kind', path: 'action_type', op: 'eq', value: 'bounty.output' }, { id: 'clean', path: 'context_meta.ok', op: 'eq', value: true }] }, }) expect(guard.status === 200 && guard.body.verdict === 'allow', 'guard screen', guard.body) log('worker', `guard verdict ${guard.body.verdict}, pass ${String(guard.body.receipt_hash).slice(0, 16)}...`) // 2c. Worker: claim with both proofs; the network verifies them and releases the escrow. const claim = await api('POST', '/v1/bounties/claim', subKey, { bounty_id: bountyId, output, execution_receipt: run.body.execution_receipt, signed_pass: guard.body.signed_pass }) expect(claim.status === 200 && claim.body.verdict === 'pass', 'claim', claim.body) log('worker', `bounty settled: ${claim.body.reward_units} EGU released`) // 3. Verifier: one key-set fetch, then purely local signature checks. const jwks = await fetch(JWKS_URL).then((r) => (r.ok ? r.json() : null)).catch(() => null) ?? (await api('GET', '/.well-known/jwks.json', null)).body for (const [label, token] of [['execution_receipt', String(run.body.execution_receipt)], ['signed_pass', String(guard.body.signed_pass)]] as const) { const t0 = performance.now() const claims = await verifyJws(jwks as { keys: JsonWebKey[] }, token) const ms = performance.now() - t0 expect(!!claims && claims.iss === ISSUER, `verify ${label}`, claims) log('verifier', `${label} signature valid (kid ${b64urlJson(token.split('.')[0]).kid}) in ${ms.toFixed(3)} ms, no network call`) } const receiptClaims = b64urlJson(String(run.body.execution_receipt).split('.')[1]) expect(receiptClaims.code_sha256 === codeSha && receiptClaims.result_sha256 === outputSha, 'receipt binds code and result', receiptClaims) log('verifier', 'receipt commits to the agreed code and to this exact output') } finally { // 4. Orchestrator: revoke the sub-key; unspent units return to the orchestrator. const revoked = await api('DELETE', `/v1/keys/delegate/${keyId}`, ORCHESTRATOR_KEY) log('orchestrator', `sub-key ${revoked.body.status ?? revoked.status}, ${revoked.body.refunded_egu ?? 0} EGU returned`) } log('done', `${((Date.now() - started) / 1000).toFixed(1)} s end to end`) } // Verifies a compact JWS (EdDSA) against a JWKS with Web Crypto only. Returns the claims, or null. async function verifyJws(jwks: { keys: JsonWebKey[] }, token: string): Promise | null> { const [h, p, s] = token.split('.') const head = b64urlJson(h) const jwk = jwks.keys.find((k) => (k as { kid?: string }).kid === head.kid) if (!jwk || head.alg !== 'EdDSA') return null const key = await crypto.subtle.importKey('jwk', { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, { name: 'Ed25519' }, false, ['verify']) const ok = await crypto.subtle.verify('Ed25519', key, b64urlBytes(s), new TextEncoder().encode(`${h}.${p}`)) return ok ? b64urlJson(p) : null } main().catch((e) => { console.error(e instanceof Error ? e.message : e) ;(globalThis as { process?: { exitCode?: number } }).process!.exitCode = 1 })