@oracle-agent/oracle 0.35.38 → 0.35.40

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 (60) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-sessions.mjs +13 -13
  3. package/dist/assets/skills/blocked-page-recovery.md +16 -0
  4. package/dist/assets/skills/browser-use.md +19 -0
  5. package/dist/assets/skills/chrome-profile-browser.md +21 -0
  6. package/dist/assets/skills/oracle-agentic-crypto/SKILL.md +27 -0
  7. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  8. package/dist/assets/skills/oracle-x402/SKILL.md +54 -11
  9. package/dist/assets/skills/web-form-filling.md +19 -0
  10. package/dist/assets/skills/web-research.md +17 -0
  11. package/dist/assets/skills/x-read-browser.md +17 -0
  12. package/dist/assets/skills/xurl.md +1 -1
  13. package/dist/bin/desk-server.mjs +30 -30
  14. package/dist/bin/oracle-data-mcp.mjs +17 -13
  15. package/dist/bin/oracle-public-server.mjs +1 -1
  16. package/dist/bin/oracle-route.mjs +26 -14
  17. package/dist/bin/oracle-scan.mjs +4 -4
  18. package/dist/bin/oracle.mjs +11 -10
  19. package/dist/cli/commands/agent-session.mjs +18 -18
  20. package/dist/cli/commands/auth.mjs +20 -17
  21. package/dist/cli/commands/chat.mjs +231 -228
  22. package/dist/cli/commands/data.mjs +5 -5
  23. package/dist/cli/commands/doctor.mjs +1 -1
  24. package/dist/cli/commands/eval.mjs +154 -152
  25. package/dist/cli/commands/extension-policy.mjs +1 -1
  26. package/dist/cli/commands/follow.mjs +57 -19
  27. package/dist/cli/commands/governance-prepare.mjs +1 -1
  28. package/dist/cli/commands/init.mjs +2 -2
  29. package/dist/cli/commands/model.mjs +235 -232
  30. package/dist/cli/commands/public.mjs +3 -3
  31. package/dist/cli/commands/route.mjs +1 -1
  32. package/dist/cli/commands/setup.mjs +62 -59
  33. package/dist/cli/commands/signer.mjs +4 -4
  34. package/dist/cli/commands/upgrade.mjs +2 -2
  35. package/dist/cli/commands/x402.mjs +19 -0
  36. package/dist/control-plane/index.mjs +1 -1
  37. package/dist/data/desk-data.mjs +28 -28
  38. package/dist/index.mjs +46 -46
  39. package/dist/local-signer/runtime.mjs +6 -6
  40. package/dist/teams/index.mjs +6 -5
  41. package/dist/tui/standalone-client.mjs +84 -82
  42. package/package.json +1 -1
  43. package/public/eval-report.json +2 -2
  44. package/public/oracle-splash/docs/browser-and-web/index.html +32 -0
  45. package/public/oracle-splash/docs/connectors/index.html +18 -0
  46. package/public/oracle-splash/docs/docs.css +21 -0
  47. package/public/oracle-splash/docs/docs.js +108 -0
  48. package/public/oracle-splash/docs/getting-started/index.html +36 -0
  49. package/public/oracle-splash/docs/index.html +26 -0
  50. package/public/oracle-splash/docs/reference/index.html +20 -0
  51. package/public/oracle-splash/docs/security/index.html +19 -0
  52. package/public/oracle-splash/docs/using-oracle/index.html +32 -0
  53. package/public/oracle-splash/download/index.html +2584 -0
  54. package/public/oracle-splash/index.html +313 -942
  55. package/public/oracle-splash/pricing/index.html +2570 -0
  56. package/public/oracle-splash/security/index.html +2574 -0
  57. package/public/oracle-splash/what-it-does/index.html +2608 -0
  58. package/public/oracle-splash/where-it-works/index.html +2635 -0
  59. package/server.json +2 -2
  60. package/dist/assets/equities-fixtures/bridge_routes.json +0 -159
@@ -7,18 +7,18 @@ import Bs from"node:fs";import re from"node:path";import pm from"node:os";import
7
7
  `),s=[],c=new Map,d=new Set,l=new Set;for(let f=0;f<u.length;f+=1){let p=u[f];if(Buffer.byteLength(p,"utf8")>Ea)return{ok:!1,reason:"event-size-limit",line:f+1,count:s.length,workflows:c.size,events:s,paths:n};let w;try{w=JSON.parse(p)}catch{return{ok:!1,reason:"malformed-json",line:f+1,count:s.length,workflows:c.size,events:s,paths:n}}let g;try{g=Ld(w)}catch(A){return{ok:!1,reason:"event-invalid",line:f+1,detail:String(A?.message||A),count:s.length,workflows:c.size,events:s,paths:n}}if(d.has(g.id))return{ok:!1,reason:"duplicate-event-id",line:f+1,count:s.length,workflows:c.size,events:s,paths:n};let h=Hn(g),y=Dn(g.tenantId,g.workflowId,g.idempotencyKey);if(l.has(y))return{ok:!1,reason:"duplicate-idempotency-key",line:f+1,count:s.length,workflows:c.size,events:s,paths:n};let b=c.get(h)??null,S=String(BigInt(b?.sequence??"0")+1n);if(g.sequence!==S)return{ok:!1,reason:"sequence-gap",line:f+1,count:s.length,workflows:c.size,events:s,paths:n};if(g.previousEventHash!==(b?.eventHash??null))return{ok:!1,reason:"previous-event-hash-mismatch",line:f+1,count:s.length,workflows:c.size,events:s,paths:n};if(b&&Date.parse(g.recordedAt)<Date.parse(b.recordedAt))return{ok:!1,reason:"recorded-at-regression",line:f+1,count:s.length,workflows:c.size,events:s,paths:n};d.add(g.id),l.add(y),c.set(h,g),s.push(g)}let m=new Map;for(let f of s){let p=Hn(f);m.has(p)||m.set(p,[]),m.get(p).push(f)}for(let[f,p]of m)try{Nr(p)}catch(w){return{ok:!1,reason:"workflow-invalid",streamKey:f,detail:String(w?.message||w),count:s.length,workflows:c.size,events:s,heads:c,paths:n}}if(r){if(!it(n.checkpoint))return s.length===0?{ok:!0,count:0,workflows:0,events:s,heads:c,paths:n,empty:!0}:{ok:!1,reason:"checkpoint-missing",recoverable:!0,count:s.length,workflows:c.size,events:s,heads:c,paths:n};let f;try{Lr(n.checkpoint,"checkpoint");let g=_r(n.checkpoint,"utf8");if(!g.endsWith(`
8
8
  `))throw new B("checkpoint truncated","CHECKPOINT_INVALID");f=JSON.parse(g),$d(f)}catch(g){return{ok:!1,reason:"checkpoint-invalid",recoverable:!1,detail:String(g?.message||g),count:s.length,workflows:c.size,events:s,heads:c,paths:n}}let p=xa(n.ledger,s,i),w=Bd(f,p);if(!w.ok)return{...w,count:s.length,workflows:c.size,events:s,heads:c,paths:n}}return{ok:!0,count:s.length,workflows:c.size,events:s,heads:c,paths:n,raw:i,lastEventHash:s.at(-1)?.eventHash??null}}catch(o){return{ok:!1,reason:"io-error",detail:String(o?.message||o),count:0,workflows:0,events:[],paths:n}}}function Fd(e){let t={ok:e.ok,count:e.count,workflows:e.workflows,...e.reason?{reason:e.reason}:{},...e.line?{line:e.line}:{},...e.detail?{detail:e.detail}:{},...e.recoverable!==void 0?{recoverable:e.recoverable}:{},...e.lastEventHash!==void 0?{lastEventHash:e.lastEventHash}:{}};return ae(t)}function jd(e){if(!Number.isSafeInteger(e)||e<=0)return"invalid";try{return process.kill(e,0),"active"}catch(t){return t?.code==="ESRCH"?"stale":"active"}}function Aa(e){let{lock:t}=st(e);Lr(t,"lock");let r=JSON.parse(_r(t,"utf8"));if(Se(r,wa,wa,"workflow ledger lock"),r.schemaVersion!==Un)throw new B("lock schema mismatch","LOCK_INVALID");if(V(r.token,"workflow ledger lock.token"),!Number.isSafeInteger(r.pid)||r.pid<=0)throw new B("lock pid invalid","LOCK_INVALID");return Pe(r.createdAt,"workflow ledger lock.createdAt"),r}function va({path:e}={}){let{lock:t}=st(e);if(!it(t))return ae({state:"unlocked",lock:null});try{let r=Aa(e);return ae({state:jd(r.pid),lock:r})}catch(r){return ae({state:"invalid",lock:null,error:String(r?.message||r)})}}function qd(e){let t=st(e);Cd(t.directory);let r={schemaVersion:Un,token:ha(),pid:process.pid,createdAt:new Date().toISOString()},n;try{return n=$r(t.lock,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),Jn(n,Buffer.from(`${JSON.stringify(r)}
9
9
  `,"utf8")),Rr(n),at(n),n=void 0,zn(t.lock,384),Pr(t.directory),r}catch(o){throw n!==void 0&&at(n),o}}async function Md(e,t){if(!Number.isSafeInteger(t)||t<0||t>12e4)throw new B("lockTimeoutMs out of bounds","LOCK_TIMEOUT_INVALID");let r=Date.now();for(;;)try{return qd(e)}catch(n){if(n?.code!=="EEXIST")throw n;if(Date.now()-r>=t){let o=va({path:e});throw new B(`ledger busy (${o.state} lock); explicit token-bound recovery is required for stale locks`,"LEDGER_BUSY",o)}await Nd(10)}}function Cr(e,t){let r=Aa(e);if(r.token!==t||r.pid!==process.pid)throw new B("lock fencing token no longer owned","LOCK_FENCED");return!0}function Hd(e,t){let r=st(e);Cr(e,t),ga(r.lock),Pr(r.directory)}function zd(e){return{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,idempotencyKey:e.idempotencyKey,occurredAt:e.occurredAt,recordedAt:e.recordedAt,type:e.type,external:e.external,evidence:e.evidence,data:e.data}}async function Kn(e={}){Se(e,["path","event","lockTimeoutMs","maxBytes"],["path","event"],"appendWorkflowEvent options");let t=st(e.path).ledger,r=Mn(e.event),n=e.lockTimeoutMs??ba,o=e.maxBytes??Vn,i=await Md(t,n),a=null;try{Cr(t,i.token);let u=Dd({path:t,maxBytes:o});if(!u.ok)throw new B(`append refused until ledger recovery: ${u.reason}`,"LEDGER_CORRUPT",Fd(u));let s=u.events.find(b=>b.tenantId===r.tenantId&&b.workflowId===r.workflowId&&b.idempotencyKey===r.idempotencyKey);if(s){if(ot(zd(s))!==ot(r))throw new B("idempotency key reused with different payload","IDEMPOTENCY_CONFLICT");return ae({event:s,duplicate:!0})}if(u.events.some(b=>b.id===r.id))throw new B("event id already exists","EVENT_ID_CONFLICT");let c=Ne(r.tenantId,r.workflowId),d=u.heads.get(c)??null,l=Tr({...r,sequence:String(BigInt(d?.sequence??"0")+1n),previousEventHash:d?.eventHash??null}),m=u.events.filter(b=>Ne(b.tenantId,b.workflowId)===c);Nr([...m,l]);let f=Buffer.from(`${JSON.stringify(l)}
10
- `,"utf8");if(f.length>Ea)throw new B("event exceeds size limit","EVENT_SIZE_LIMIT");let p=Buffer.concat([u.raw??Buffer.alloc(0),f]);if(p.length>o)throw new B("append would exceed ledger size limit","LEDGER_SIZE_LIMIT");let w=[...u.events,l],g=Sa(t,w,p),h=it(t);h&&Lr(t,"ledger"),Cr(t,i.token);let y;try{y=_d(t),Jn(y,f),Rr(y)}finally{y!==void 0&&at(y)}return zn(t,384),h||Pr(ya(t)),Cr(t,i.token),Pd(t,w,p,g),ae({event:l,duplicate:!1})}catch(u){throw a=u,u}finally{try{Hd(t,i.token)}catch(u){if(a===null)throw u}}}var wy=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),hy=Object.freeze(["read","simulate"]);var gy=1440*60;var ky=Object.freeze(["privkey","wif","xprv","seed"]);var Oy=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),Ty=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);var Gn=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),Ly=Object.freeze(Object.fromEntries(Gn.map((e,t)=>[e,Object.freeze(t+1<Gn.length?[Gn[t+1]]:[])])));var Wd=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"});import{createHash as Yd,randomBytes as Xd}from"node:crypto";var Ud=Object.freeze(["owner","operator","agent","viewer"]),Vd=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),Jd=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),lb=Object.freeze(["owner"]),db=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),fb=new Set(Ud),pb=new Set(Vd),mb=new Set(Object.values(Jd));var Kd=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;var Gd=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export","context:read","context:create","context:update","context:delete","context:manage","context:export","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:delete","lifecycle:manage","lifecycle:approve","lifecycle:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create","context:read","context:create","context:update","context:delete","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:manage"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create","context:read","context:create","context:update","lifecycle:read"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read","context:read","lifecycle:read"])}),wb=Object.freeze(Object.fromEntries(Object.entries(Gd).map(([e,t])=>[e,Object.freeze([...t])]))),Br=class extends Error{constructor(t,r="invalid-context"){super(t),this.name="TenantContextError",this.code=r}};function Ia(e,t){let r=String(e??"").trim();if(!Kd.test(r))throw new Br(`${t} is invalid`);return r}function ka(e,t){let r=Ia(e,"tenantId"),n=Ia(t,"workflowId");if(r.includes(":")||n.includes(":"))throw new Br("stream key parts must not contain ':'","invalid-stream-key");return`${r}:${n}`}var La=1,Ra=1,Zd=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),Qd=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),$a=Object.freeze(["taskId","intentId","planId","runId","eventId"]);function Oa(e,t){return ka(e,t)}var tr=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),ef=new Set(Zd),tf=new Set(Qd),rf=new Set($a),nf=/^[0-9a-f]{32}$/,Ta=/^[0-9a-f]{16}$/;var of=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,95}$/,af=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,sf=/^[A-Za-z][A-Za-z0-9_.-]*$/,cf=Object.freeze(["authorization","bearer","cookie","credential","password","passphrase","secret","token","privatekey","privkey","seed","mnemonic","keystore","signature","prompt","systemmessage","usermessage","assistantmessage","rawtransaction","signedtransaction","serializedtransaction","transactionbytes","calldata","callbytes","inputdata"]),uf=/(?:^|\s)Bearer\s+\S+|-----BEGIN [A-Z ]*PRIVATE KEY-----|\bxprv[0-9A-Za-z]{20,}\b|\bsk-[A-Za-z0-9_-]{16,}\b|[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{16,}/i,lf=/(?:0x)?[0-9a-fA-F]{66,}/,df=/[A-Za-z0-9+/=_-]{96,}/,F=class extends Error{constructor(t,r="invalid-telemetry"){super(t),this.name="WorkflowTelemetryError",this.code=r}};function Dr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Fr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Fr(t)}return e}function Yn(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Yn).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Yn(e[t])}`).join(",")}}`}function Pa(e){return Yd("sha256").update(Yn(e)).digest("hex")}function Na(e,t,r){let n=r?r(e,t):Xd(e).toString("hex");return String(n??"").trim().toLowerCase()}function Ba(e={}){if(e==null)return{};if(!Dr(e))throw new F("correlation must be a plain object");let t=Object.keys(e).filter(n=>!rf.has(n));if(t.length)throw new F(`unknown correlation fields: ${t.sort().join(", ")}`);let r={};for(let n of $a){if(e[n]==null)continue;let o=String(e[n]).trim();if(!af.test(o))throw new F(`${n} is invalid`);r[n]=o}return r}function Da(e){if(!Dr(e)||e.schemaVersion!==La)throw new F("trace context version is invalid","invalid-trace");if(!nf.test(e.traceId||"")||!Ta.test(e.spanId||"")||/^0+$/.test(e.traceId)||/^0+$/.test(e.spanId))throw new F("trace or span id is invalid","invalid-trace");if(e.parentSpanId!==null&&!Ta.test(e.parentSpanId||""))throw new F("parent span id is invalid","invalid-trace");if(typeof e.sampled!="boolean")throw new F("sampled must be boolean","invalid-trace");return Ba(e.correlation),e}function ff({traceId:e,spanId:t,parentSpanId:r=null,sampled:n=!1,correlation:o={}}={},{idFactory:i}={}){let a=e==null?Na(16,"trace",i):String(e).trim().toLowerCase(),u=t==null?Na(8,"span",i):String(t).trim().toLowerCase(),s=r==null?null:String(r).trim().toLowerCase(),c=Fr({schemaVersion:La,traceId:a,spanId:u,parentSpanId:s,sampled:n===!0,correlation:Ba(o)});return Da(c)}var Fa=ff;var bb=Object.freeze({taskId:"x-oracle-task-id",intentId:"x-oracle-intent-id",planId:"x-oracle-plan-id",runId:"x-oracle-run-id",eventId:"x-oracle-event-id"});function Ca(e){let t=String(e).replace(/[^a-z0-9]/gi,"").toLowerCase();return cf.some(r=>t.includes(r))}function pf(e){return uf.test(e)||lf.test(e)||df.test(e)?{value:"[REDACTED]",redacted:!0,truncated:!1}:e.length>tr.maxStringLength?{value:`${e.slice(0,tr.maxStringLength-1)}\u2026`,redacted:!1,truncated:!0}:{value:e,redacted:!1,truncated:!1}}function ja(e){if(typeof e=="string")return pf(e);if(typeof e=="boolean")return{value:e,redacted:!1,truncated:!1};if(typeof e=="number"&&Number.isFinite(e))return{value:e,redacted:!1,truncated:!1};if(Array.isArray(e)){let t=e.slice(0,tr.maxArrayLength),r=[],n=!1,o=e.length>t.length;for(let i of t){if(!["string","boolean","number"].includes(typeof i))return null;let a=ja(i);if(!a)return null;r.push(a.value),n||=a.redacted,o||=a.truncated}return{value:r,redacted:n,truncated:o}}return null}function mf(e={}){if(!Dr(e))throw new F("telemetry attributes must be a plain object");let t={},r=0,n=0,o=0,i=Object.keys(e).sort();for(let a of i){if(Object.keys(t).length>=tr.maxAttributes){n+=1;continue}if(a.length>tr.maxKeyLength||!sf.test(a)||Ca(a)){n+=1,Ca(a)&&(r+=1);continue}let u=ja(e[a]);if(!u){n+=1;continue}t[a]=u.value,u.redacted&&(r+=1),u.truncated&&(o+=1)}return Fr({attributes:t,redactedCount:r,droppedCount:n,truncatedCount:o})}function _a(e,t){if(!Number.isSafeInteger(e)||e<0)throw new F(`${t} must be a non-negative integer milliseconds value`);return e}function wf(e){if(e==null)return null;let t=String(e).trim();if(!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(t))throw new F("outcomeCode is invalid");return t}function hf({streamKey:e,tenantId:t,workflowId:r,sourceEvent:n}){let o=e??n?.streamKey??null,i=t??n?.tenantId??null,a=r??n?.workflowId??null;if(o!=null){let u=String(o).trim();if(i!=null&&a!=null){let s=Oa(i,a);if(u!==s)throw new F("streamKey must equal tenantId:workflowId","invalid-stream-key");return s}if(!/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}:[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(u)||u.split(":").length!==2)throw new F("streamKey must be tenantId:workflowId","invalid-stream-key");return u}return i!=null&&a!=null?Oa(i,a):null}function gf({trace:e,name:t,kind:r,diagnosticOutcome:n=null,outcome:o=null,outcomeCode:i=null,startedAt:a,endedAt:u,attributes:s,authority:c,sourceEvent:d=null,streamKey:l=null,tenantId:m=null,workflowId:f=null}){Da(e);let p=String(t??"").trim();if(!of.test(p))throw new F("workflow telemetry name is invalid");if(!tf.has(r))throw new F("workflow telemetry kind is invalid");let w=c==="ledger_projection"?o:n;if(!ef.has(w))throw new F("workflow telemetry outcome is invalid");let g=_a(a,"startedAt"),h=_a(u,"endedAt");if(h<g)throw new F("endedAt must not be before startedAt");let y=mf(s),b=hf({streamKey:l,tenantId:m,workflowId:f,sourceEvent:d}),S={schemaVersion:Ra,recordType:"oracle.workflow.telemetry",authority:c,streamKey:b,trace:{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,sampled:e.sampled},correlation:{...e.correlation},name:p,kind:r,...c==="ledger_projection"?{outcome:o,sourceEvent:{...d}}:{diagnosticOutcome:n},outcomeCode:wf(i),startedAt:g,endedAt:h,durationMs:h-g,attributes:{...y.attributes},attributePolicy:{redactedCount:y.redactedCount,droppedCount:y.droppedCount,truncatedCount:y.truncatedCount}};return Fr({...S,recordId:Pa(S)})}function Xn({trace:e,name:t,kind:r="workflow",outcome:n,outcomeCode:o=null,startedAt:i,endedAt:a,attributes:u={},tenantId:s=null,workflowId:c=null,streamKey:d=null}={}){return gf({trace:e,name:t,kind:r,diagnosticOutcome:n,outcomeCode:o,startedAt:i,endedAt:a,attributes:u,authority:"diagnostic",tenantId:s,workflowId:c,streamKey:d})}function Zn(e){if(!Dr(e)||!Object.isFrozen(e)||e.schemaVersion!==Ra||e.recordType!=="oracle.workflow.telemetry")return!1;let{recordId:t,...r}=e;return typeof t=="string"&&t===Pa(r)}function Qn({exporter:e=null}={}){if(e!=null&&typeof e!="function"&&typeof e?.export!="function")throw new F("exporter must be a function or expose export(record)");let t=typeof e=="function"?e:e?.export?.bind(e);return Object.freeze({exporterConfigured:!!t,defaultExporter:"none",async emit(r){let n=Zn(r)?r:Xn(r);if(!t)return Object.freeze({record:n,exported:!1,exporterFailed:!1});try{return await t(n),Object.freeze({record:n,exported:!0,exporterFailed:!1})}catch{return Object.freeze({record:n,exported:!1,exporterFailed:!0})}}})}var yf="ORACLE_LEDGER_DUAL_WRITE",qa=/^[a-f0-9]{64}$/,bf=/^0x[a-f0-9]{64}$/,Ef=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"});function Ct(e,t){return String(e??"").slice(0,t)}function Ma(e=process.env){return String(e?.[yf]??"")==="1"}function Ha({path:e,tenantId:t="local-signer",nowMs:r=Date.now,onError:n=null,telemetry:o=null,append:i=Kn}={}){if(typeof e!="string"||e.trim().length===0)throw new Error("ledger observer requires an explicit ledger path");if(typeof i!="function")throw new Error("ledger observer requires an append function");let a=typeof n=="function"?n:()=>{},u=new Map,s=Promise.resolve(),c=()=>new Date(r()).toISOString();function d(f,p,w){if(!(!o||typeof o.emit!="function"))try{let g=r(),h=Xn({trace:f.trace,name:p,kind:"workflow",outcome:Ef[p]??"succeeded",startedAt:g,endedAt:g,attributes:w,tenantId:t,workflowId:f.workflowId});s=s.then(()=>o.emit(h)).catch(y=>{a(`signer telemetry emit failed: ${Ct(y?.message||y,200)}`)})}catch(g){a(`signer telemetry record failed: ${Ct(g?.message||g,200)}`)}}function l(f,p,{external:w=!1,source:g="local-signer",reference:h=null,data:y={}}={}){let b=c(),S={tenantId:t,id:`${f.workflowId}:${p}`,workflowId:f.workflowId,idempotencyKey:`${f.workflowId}:${p}`,occurredAt:b,recordedAt:b,type:p,external:w,evidence:{status:"verified",source:w?"external":g,reference:`${w?`${g}:`:""}${h??`${p}:${f.workflowId}`}`},data:y};return s=s.then(()=>i({path:e,event:S})).catch(A=>{a(`workflow ledger dual-write failed for ${p}: ${Ct(A?.message||A,200)}`)}),d(f,p,{digest:f.digest}),s}function m(f){let p=String(f??"").toLowerCase();return qa.test(p)?u.get(p)??null:null}return Object.freeze({queued({digest:f,createdAtMs:p}={}){let w=String(f??"").toLowerCase();if(!qa.test(w))return a("ledger observer: queued without a valid artifact digest"),s;let g=Number.isFinite(Number(p))?Number(p):r(),h={workflowId:`signer-${w}-${g}`,digest:w,trace:Fa()};return u.set(w,h),l(h,"workflow.drafted",{source:"local-signer-queue",reference:`artifact:${w}`,data:{intentSpecId:`${h.workflowId}:intent`}}),l(h,"workflow.checked",{source:"local-signer-policy",reference:`artifact:${w}`,data:{checksPassed:!0}}),l(h,"workflow.approval_requested",{source:"local-signer-queue",reference:`artifact:${w}`}),s},denied({digest:f}={}){let p=m(f);return p&&(u.delete(p.digest),l(p,"workflow.cancelled",{source:"owner-ack",reference:`deny:${p.digest}`})),s},approved({digest:f,channel:p="owner-ack"}={}){let w=m(f);return w&&l(w,"workflow.approval_granted",{external:!0,source:p,reference:`ack:${w.digest}`}),s},executed({digest:f,owner:p=null,result:w=null}={}){let g=m(f);if(!g)return s;u.delete(g.digest),l(g,"workflow.signed",{external:!0,reference:`signed:${g.digest}`,data:{artifactHash:g.digest,signer:Ct(p||"owner-wallet",256)}});let h=w?.hash??w?.txHash??w?.transactionHash??w?.signature??null,y=typeof h=="string"?h.trim().toLowerCase():null;return y&&bf.test(y)?l(g,"workflow.submitted",{external:!0,reference:`submitted:${g.digest}`,data:{transactionHash:y,endpoint:"local-signer-broadcast"}}):h&&l(g,"workflow.annotated",{reference:`submission:${g.digest}`,data:{note:"non-evm-submission-reference",reference:Ct(h,512)}}),s},failed({digest:f,reason:p=""}={}){let w=m(f);return w&&(u.delete(w.digest),l(w,"workflow.failed",{reference:`failed:${w.digest}`,data:{reason:Ct(p,300)}})),s},flush(){return s}})}import{appendFileSync as xf,existsSync as Sf,mkdirSync as Af,renameSync as vf,statSync as If}from"node:fs";import{dirname as kf}from"node:path";var Of="ORACLE_TELEMETRY_JSONL",Tf=32*1024*1024,za=4096;function Nf({path:e,maxBytes:t=Tf}={}){if(typeof e!="string"||e.trim().length===0)throw new F("jsonl exporter requires an explicit file path","invalid-exporter-path");let r=Number(t);if(!Number.isFinite(r)||r<za)throw new F(`jsonl exporter maxBytes must be >= ${za}`,"invalid-exporter-cap");let n=e;return Object.freeze({path:n,maxBytes:r,export(o){if(!Zn(o))throw new F("jsonl exporter accepts only sealed workflow telemetry records","invalid-record");let i=`${JSON.stringify(o)}
11
- `;Af(kf(n),{recursive:!0,mode:448}),Sf(n)&&If(n).size+Buffer.byteLength(i)>r&&vf(n,`${n}.1`),xf(n,i,{mode:384})}})}function Wa(e=process.env,{maxBytes:t}={}){let r=String(e?.[Of]??"").trim();return r?Qn({exporter:Nf({path:r,...t===void 0?{}:{maxBytes:t}})}):Qn({})}import{createCipheriv as Nb,createDecipheriv as Cf,randomBytes as _f,scryptSync as Lf}from"node:crypto";import D from"node:fs";import _t from"node:path";var Rf="ORACLE-LOCAL-VAULT",$f=1,qr=Object.freeze({N:1<<17,r:8,p:1}),Pf=256*1024*1024,Bf=16*1024;function jr(e,t,r,{max:n=t}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${r} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<t||o.length>n)throw new Error(`local-vault: invalid ${r} length`);return o}function Df(e,t,r=qr){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");if(n.includes("\0"))throw new Error("local-vault: refusing zeroed passphrase material");return Lf(n,t,32,{...r,maxmem:Pf})}function Ua(e,t){if(e?.magic!==Rf||e?.version!==$f)throw new Error("local-vault: unsupported vault file");if(e?.kdf?.name!=="scrypt"||e?.cipher?.name!=="aes-256-gcm")throw new Error("local-vault: unsupported cryptography");if(e.kdf.N!==qr.N||e.kdf.r!==qr.r||e.kdf.p!==qr.p)throw new Error("local-vault: unsupported KDF parameters");if(Object.keys(e.kdf).sort().join(",")!=="N,name,p,r,salt"||Object.keys(e.cipher).sort().join(",")!=="iv,name")throw new Error("local-vault: unexpected cryptography field");if(!e.meta||Object.keys(e.meta).some(l=>!["address","addresses","kind","createdAt"].includes(l))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||JSON.stringify(e.meta.addresses||{}).length>1024||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let r=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(l=>!r.includes(l)))throw new Error("local-vault: unexpected vault field");let n=jr(e.kdf.salt,32,"salt"),o=jr(e.cipher.iv,12,"iv"),i=jr(e.tag,16,"tag"),a=jr(e.ciphertext,1,"ciphertext",{max:Bf}),{ciphertext:u,tag:s,...c}=e,d=Df(t,n);try{let l=Cf("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(c))),l.setAuthTag(i),Buffer.concat([l.update(a),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function Ff(e){if(!e.isFile())throw new Error("local-vault: secret source must be a regular file");if(e.uid!==process.getuid?.())throw new Error("local-vault: secret source must be owned by this user");if(e.nlink!==1)throw new Error("local-vault: refusing hard-linked secret source");if((e.mode&63)!==0)throw new Error("local-vault: secret source must be owner-only (0600)")}function jf(e){let t=_t.dirname(e),r=D.lstatSync(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(r.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((r.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=D.lstatSync(e);if(n.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!n.isFile()||n.uid!==process.getuid?.()||n.nlink!==1)throw new Error("local-vault: unsafe destination file");if(n.dev!==r.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function R(e){let t;try{t=D.openSync(e,D.constants.O_RDONLY|D.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=D.fstatSync(t);if(Ff(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=D.lstatSync(e);if(n.isSymbolicLink()||n.dev!==r.dev||n.ino!==r.ino)throw new Error("local-vault: secret source changed or is too large");return D.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{D.closeSync(t)}}function Va(e){return JSON.parse(R(e))}function Ae(e,t){D.mkdirSync(_t.dirname(e),{recursive:!0,mode:448}),jf(e);let r=_t.join(_t.dirname(e),`.${_t.basename(e)}.${process.pid}.${_f(6).toString("hex")}.tmp`);try{let n=D.openSync(r,D.constants.O_CREAT|D.constants.O_EXCL|D.constants.O_WRONLY|D.constants.O_NOFOLLOW,384);try{D.writeFileSync(n,String(t)),D.fsyncSync(n)}finally{D.closeSync(n)}D.renameSync(r,e),D.chmodSync(e,384);let o=D.openSync(_t.dirname(e),"r");try{D.fsyncSync(o)}finally{D.closeSync(o)}}catch(n){try{D.unlinkSync(r)}catch{}throw n}}var Ja=/^0x[0-9a-fA-F]+$/,qf=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});function Mf(e){let t=process.env[`ORACLE_PRIVATE_RELAY_${Number(e)}`];if(!t)return null;let r=t.split(",").map(n=>n.trim()).filter(Boolean);return r.length?r:null}function Hf(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=qf[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=Mf(r),i=o||n.endpoints,a=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&a!=="public-only";if(t&&!u)throw new Error(`private relay: no keyless private endpoint for chain ${r} (${n.name}); set ORACLE_PRIVATE_RELAY_${r} to force one, or allow public fallback`);return{chainId:r,name:n.name,mode:a,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function Ka(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!Ja.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let a=Hf(t,{requirePrivate:r}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let s=[];for(let c of a.endpoints){let d=new AbortController,l=setTimeout(()=>d.abort(),i);try{let m=await u(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendRawTransaction",params:[e]}),signal:d.signal}),f=await m.text(),p=null;try{p=JSON.parse(f)}catch{}if(p&&p.result&&Ja.test(p.result))return{hash:p.result,endpoint:c,mode:a.mode,chainId:a.chainId,fellBack:!1};s.push({endpoint:c,error:p&&p.error&&p.error.message||`http ${m.status}`})}catch(m){s.push({endpoint:c,error:String(m&&m.message||m).slice(0,160)})}finally{clearTimeout(l)}}if(n&&!r)return{fellBack:!0,mode:a.mode,chainId:a.chainId,attempts:s};throw new Error(`submitPrivate: all private endpoints failed for chain ${a.chainId} (${s.map(c=>`${c.endpoint}:${c.error}`).join("; ")||"none configured"})`)}import{createHmac as Wf,randomBytes as Uf,timingSafeEqual as Vf}from"node:crypto";import te from"node:fs";import ct from"node:path";import{homedir as eo}from"node:os";import{join as to}from"node:path";var Ga=process.env.ORACLE_PUBLIC_DESKTOP==="1",zf=Ga?process.env.ORACLE_CONFIG_DIR||to(eo(),".config","oracle"):to(eo(),".config","oracle"),Bb=Ga?zf:to(eo(),".config","mad-desk");var Mb="0".repeat(64),Hb=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});function Mr(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Mr).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Mr(e[r])).join(",")+"}"}var zb=Promise.resolve();function ut(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=a=>{try{return te.realpathSync(a)}catch{return ct.resolve(a)}},n=r(ct.dirname(ct.resolve(e))),o=r(ct.dirname(ct.resolve(t))),i=(a,u)=>u===a||u.startsWith(a+ct.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var Jf=864e5,ue=(e,t)=>Wf("sha256",t).update(Mr(e)).digest("hex"),Ce=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Vf(r,n)},Kf=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Gf(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(e.integrity.mac,ue(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function zr(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=R(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!Ce(n?.integrity?.mac,ue(n?.marker,t)))throw new Error("policy: sequence anchor integrity failed");return{sequence:Number(n?.marker?.policySequence||0),policyMac:n?.marker?.policyMac??null,present:!0,ledgerInitialized:n?.marker?.ledgerInitialized===!0}}function Yf(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let u=zr(e,r);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(t),policyMac:String(n)};i&&(a.ledgerInitialized=!0),Ae(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(a,r)}})+`
10
+ `,"utf8");if(f.length>Ea)throw new B("event exceeds size limit","EVENT_SIZE_LIMIT");let p=Buffer.concat([u.raw??Buffer.alloc(0),f]);if(p.length>o)throw new B("append would exceed ledger size limit","LEDGER_SIZE_LIMIT");let w=[...u.events,l],g=Sa(t,w,p),h=it(t);h&&Lr(t,"ledger"),Cr(t,i.token);let y;try{y=_d(t),Jn(y,f),Rr(y)}finally{y!==void 0&&at(y)}return zn(t,384),h||Pr(ya(t)),Cr(t,i.token),Pd(t,w,p,g),ae({event:l,duplicate:!1})}catch(u){throw a=u,u}finally{try{Hd(t,i.token)}catch(u){if(a===null)throw u}}}var my=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),wy=Object.freeze(["read","simulate"]);var hy=1440*60;var Iy=Object.freeze(["privkey","wif","xprv","seed"]);var ky=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),Oy=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);var Gn=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),_y=Object.freeze(Object.fromEntries(Gn.map((e,t)=>[e,Object.freeze(t+1<Gn.length?[Gn[t+1]]:[])])));var Wd=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"});import{createHash as Yd,randomBytes as Xd}from"node:crypto";var Ud=Object.freeze(["owner","operator","agent","viewer"]),Vd=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),Jd=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),ub=Object.freeze(["owner"]),lb=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),db=new Set(Ud),fb=new Set(Vd),pb=new Set(Object.values(Jd));var Kd=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;var Gd=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export","context:read","context:create","context:update","context:delete","context:manage","context:export","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:delete","lifecycle:manage","lifecycle:approve","lifecycle:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create","context:read","context:create","context:update","context:delete","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:manage"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create","context:read","context:create","context:update","lifecycle:read"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read","context:read","lifecycle:read"])}),mb=Object.freeze(Object.fromEntries(Object.entries(Gd).map(([e,t])=>[e,Object.freeze([...t])]))),Br=class extends Error{constructor(t,r="invalid-context"){super(t),this.name="TenantContextError",this.code=r}};function Ia(e,t){let r=String(e??"").trim();if(!Kd.test(r))throw new Br(`${t} is invalid`);return r}function ka(e,t){let r=Ia(e,"tenantId"),n=Ia(t,"workflowId");if(r.includes(":")||n.includes(":"))throw new Br("stream key parts must not contain ':'","invalid-stream-key");return`${r}:${n}`}var La=1,Ra=1,Zd=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),Qd=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),$a=Object.freeze(["taskId","intentId","planId","runId","eventId"]);function Oa(e,t){return ka(e,t)}var tr=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),ef=new Set(Zd),tf=new Set(Qd),rf=new Set($a),nf=/^[0-9a-f]{32}$/,Ta=/^[0-9a-f]{16}$/;var of=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,95}$/,af=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,sf=/^[A-Za-z][A-Za-z0-9_.-]*$/,cf=Object.freeze(["authorization","bearer","cookie","credential","password","passphrase","secret","token","privatekey","privkey","seed","mnemonic","keystore","signature","prompt","systemmessage","usermessage","assistantmessage","rawtransaction","signedtransaction","serializedtransaction","transactionbytes","calldata","callbytes","inputdata"]),uf=/(?:^|\s)Bearer\s+\S+|-----BEGIN [A-Z ]*PRIVATE KEY-----|\bxprv[0-9A-Za-z]{20,}\b|\bsk-[A-Za-z0-9_-]{16,}\b|[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{16,}/i,lf=/(?:0x)?[0-9a-fA-F]{66,}/,df=/[A-Za-z0-9+/=_-]{96,}/,F=class extends Error{constructor(t,r="invalid-telemetry"){super(t),this.name="WorkflowTelemetryError",this.code=r}};function Dr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Fr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Fr(t)}return e}function Yn(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Yn).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Yn(e[t])}`).join(",")}}`}function Pa(e){return Yd("sha256").update(Yn(e)).digest("hex")}function Na(e,t,r){let n=r?r(e,t):Xd(e).toString("hex");return String(n??"").trim().toLowerCase()}function Ba(e={}){if(e==null)return{};if(!Dr(e))throw new F("correlation must be a plain object");let t=Object.keys(e).filter(n=>!rf.has(n));if(t.length)throw new F(`unknown correlation fields: ${t.sort().join(", ")}`);let r={};for(let n of $a){if(e[n]==null)continue;let o=String(e[n]).trim();if(!af.test(o))throw new F(`${n} is invalid`);r[n]=o}return r}function Da(e){if(!Dr(e)||e.schemaVersion!==La)throw new F("trace context version is invalid","invalid-trace");if(!nf.test(e.traceId||"")||!Ta.test(e.spanId||"")||/^0+$/.test(e.traceId)||/^0+$/.test(e.spanId))throw new F("trace or span id is invalid","invalid-trace");if(e.parentSpanId!==null&&!Ta.test(e.parentSpanId||""))throw new F("parent span id is invalid","invalid-trace");if(typeof e.sampled!="boolean")throw new F("sampled must be boolean","invalid-trace");return Ba(e.correlation),e}function ff({traceId:e,spanId:t,parentSpanId:r=null,sampled:n=!1,correlation:o={}}={},{idFactory:i}={}){let a=e==null?Na(16,"trace",i):String(e).trim().toLowerCase(),u=t==null?Na(8,"span",i):String(t).trim().toLowerCase(),s=r==null?null:String(r).trim().toLowerCase(),c=Fr({schemaVersion:La,traceId:a,spanId:u,parentSpanId:s,sampled:n===!0,correlation:Ba(o)});return Da(c)}var Fa=ff;var yb=Object.freeze({taskId:"x-oracle-task-id",intentId:"x-oracle-intent-id",planId:"x-oracle-plan-id",runId:"x-oracle-run-id",eventId:"x-oracle-event-id"});function Ca(e){let t=String(e).replace(/[^a-z0-9]/gi,"").toLowerCase();return cf.some(r=>t.includes(r))}function pf(e){return uf.test(e)||lf.test(e)||df.test(e)?{value:"[REDACTED]",redacted:!0,truncated:!1}:e.length>tr.maxStringLength?{value:`${e.slice(0,tr.maxStringLength-1)}\u2026`,redacted:!1,truncated:!0}:{value:e,redacted:!1,truncated:!1}}function ja(e){if(typeof e=="string")return pf(e);if(typeof e=="boolean")return{value:e,redacted:!1,truncated:!1};if(typeof e=="number"&&Number.isFinite(e))return{value:e,redacted:!1,truncated:!1};if(Array.isArray(e)){let t=e.slice(0,tr.maxArrayLength),r=[],n=!1,o=e.length>t.length;for(let i of t){if(!["string","boolean","number"].includes(typeof i))return null;let a=ja(i);if(!a)return null;r.push(a.value),n||=a.redacted,o||=a.truncated}return{value:r,redacted:n,truncated:o}}return null}function mf(e={}){if(!Dr(e))throw new F("telemetry attributes must be a plain object");let t={},r=0,n=0,o=0,i=Object.keys(e).sort();for(let a of i){if(Object.keys(t).length>=tr.maxAttributes){n+=1;continue}if(a.length>tr.maxKeyLength||!sf.test(a)||Ca(a)){n+=1,Ca(a)&&(r+=1);continue}let u=ja(e[a]);if(!u){n+=1;continue}t[a]=u.value,u.redacted&&(r+=1),u.truncated&&(o+=1)}return Fr({attributes:t,redactedCount:r,droppedCount:n,truncatedCount:o})}function _a(e,t){if(!Number.isSafeInteger(e)||e<0)throw new F(`${t} must be a non-negative integer milliseconds value`);return e}function wf(e){if(e==null)return null;let t=String(e).trim();if(!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(t))throw new F("outcomeCode is invalid");return t}function hf({streamKey:e,tenantId:t,workflowId:r,sourceEvent:n}){let o=e??n?.streamKey??null,i=t??n?.tenantId??null,a=r??n?.workflowId??null;if(o!=null){let u=String(o).trim();if(i!=null&&a!=null){let s=Oa(i,a);if(u!==s)throw new F("streamKey must equal tenantId:workflowId","invalid-stream-key");return s}if(!/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}:[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(u)||u.split(":").length!==2)throw new F("streamKey must be tenantId:workflowId","invalid-stream-key");return u}return i!=null&&a!=null?Oa(i,a):null}function gf({trace:e,name:t,kind:r,diagnosticOutcome:n=null,outcome:o=null,outcomeCode:i=null,startedAt:a,endedAt:u,attributes:s,authority:c,sourceEvent:d=null,streamKey:l=null,tenantId:m=null,workflowId:f=null}){Da(e);let p=String(t??"").trim();if(!of.test(p))throw new F("workflow telemetry name is invalid");if(!tf.has(r))throw new F("workflow telemetry kind is invalid");let w=c==="ledger_projection"?o:n;if(!ef.has(w))throw new F("workflow telemetry outcome is invalid");let g=_a(a,"startedAt"),h=_a(u,"endedAt");if(h<g)throw new F("endedAt must not be before startedAt");let y=mf(s),b=hf({streamKey:l,tenantId:m,workflowId:f,sourceEvent:d}),S={schemaVersion:Ra,recordType:"oracle.workflow.telemetry",authority:c,streamKey:b,trace:{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,sampled:e.sampled},correlation:{...e.correlation},name:p,kind:r,...c==="ledger_projection"?{outcome:o,sourceEvent:{...d}}:{diagnosticOutcome:n},outcomeCode:wf(i),startedAt:g,endedAt:h,durationMs:h-g,attributes:{...y.attributes},attributePolicy:{redactedCount:y.redactedCount,droppedCount:y.droppedCount,truncatedCount:y.truncatedCount}};return Fr({...S,recordId:Pa(S)})}function Xn({trace:e,name:t,kind:r="workflow",outcome:n,outcomeCode:o=null,startedAt:i,endedAt:a,attributes:u={},tenantId:s=null,workflowId:c=null,streamKey:d=null}={}){return gf({trace:e,name:t,kind:r,diagnosticOutcome:n,outcomeCode:o,startedAt:i,endedAt:a,attributes:u,authority:"diagnostic",tenantId:s,workflowId:c,streamKey:d})}function Zn(e){if(!Dr(e)||!Object.isFrozen(e)||e.schemaVersion!==Ra||e.recordType!=="oracle.workflow.telemetry")return!1;let{recordId:t,...r}=e;return typeof t=="string"&&t===Pa(r)}function Qn({exporter:e=null}={}){if(e!=null&&typeof e!="function"&&typeof e?.export!="function")throw new F("exporter must be a function or expose export(record)");let t=typeof e=="function"?e:e?.export?.bind(e);return Object.freeze({exporterConfigured:!!t,defaultExporter:"none",async emit(r){let n=Zn(r)?r:Xn(r);if(!t)return Object.freeze({record:n,exported:!1,exporterFailed:!1});try{return await t(n),Object.freeze({record:n,exported:!0,exporterFailed:!1})}catch{return Object.freeze({record:n,exported:!1,exporterFailed:!0})}}})}var yf="ORACLE_LEDGER_DUAL_WRITE",qa=/^[a-f0-9]{64}$/,bf=/^0x[a-f0-9]{64}$/,Ef=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"});function Ct(e,t){return String(e??"").slice(0,t)}function Ma(e=process.env){return String(e?.[yf]??"")==="1"}function Ha({path:e,tenantId:t="local-signer",nowMs:r=Date.now,onError:n=null,telemetry:o=null,append:i=Kn}={}){if(typeof e!="string"||e.trim().length===0)throw new Error("ledger observer requires an explicit ledger path");if(typeof i!="function")throw new Error("ledger observer requires an append function");let a=typeof n=="function"?n:()=>{},u=new Map,s=Promise.resolve(),c=()=>new Date(r()).toISOString();function d(f,p,w){if(!(!o||typeof o.emit!="function"))try{let g=r(),h=Xn({trace:f.trace,name:p,kind:"workflow",outcome:Ef[p]??"succeeded",startedAt:g,endedAt:g,attributes:w,tenantId:t,workflowId:f.workflowId});s=s.then(()=>o.emit(h)).catch(y=>{a(`signer telemetry emit failed: ${Ct(y?.message||y,200)}`)})}catch(g){a(`signer telemetry record failed: ${Ct(g?.message||g,200)}`)}}function l(f,p,{external:w=!1,source:g="local-signer",reference:h=null,data:y={}}={}){let b=c(),S={tenantId:t,id:`${f.workflowId}:${p}`,workflowId:f.workflowId,idempotencyKey:`${f.workflowId}:${p}`,occurredAt:b,recordedAt:b,type:p,external:w,evidence:{status:"verified",source:w?"external":g,reference:`${w?`${g}:`:""}${h??`${p}:${f.workflowId}`}`},data:y};return s=s.then(()=>i({path:e,event:S})).catch(A=>{a(`workflow ledger dual-write failed for ${p}: ${Ct(A?.message||A,200)}`)}),d(f,p,{digest:f.digest}),s}function m(f){let p=String(f??"").toLowerCase();return qa.test(p)?u.get(p)??null:null}return Object.freeze({queued({digest:f,createdAtMs:p}={}){let w=String(f??"").toLowerCase();if(!qa.test(w))return a("ledger observer: queued without a valid artifact digest"),s;let g=Number.isFinite(Number(p))?Number(p):r(),h={workflowId:`signer-${w}-${g}`,digest:w,trace:Fa()};return u.set(w,h),l(h,"workflow.drafted",{source:"local-signer-queue",reference:`artifact:${w}`,data:{intentSpecId:`${h.workflowId}:intent`}}),l(h,"workflow.checked",{source:"local-signer-policy",reference:`artifact:${w}`,data:{checksPassed:!0}}),l(h,"workflow.approval_requested",{source:"local-signer-queue",reference:`artifact:${w}`}),s},denied({digest:f}={}){let p=m(f);return p&&(u.delete(p.digest),l(p,"workflow.cancelled",{source:"owner-ack",reference:`deny:${p.digest}`})),s},approved({digest:f,channel:p="owner-ack"}={}){let w=m(f);return w&&l(w,"workflow.approval_granted",{external:!0,source:p,reference:`ack:${w.digest}`}),s},executed({digest:f,owner:p=null,result:w=null}={}){let g=m(f);if(!g)return s;u.delete(g.digest),l(g,"workflow.signed",{external:!0,reference:`signed:${g.digest}`,data:{artifactHash:g.digest,signer:Ct(p||"owner-wallet",256)}});let h=w?.hash??w?.txHash??w?.transactionHash??w?.signature??null,y=typeof h=="string"?h.trim().toLowerCase():null;return y&&bf.test(y)?l(g,"workflow.submitted",{external:!0,reference:`submitted:${g.digest}`,data:{transactionHash:y,endpoint:"local-signer-broadcast"}}):h&&l(g,"workflow.annotated",{reference:`submission:${g.digest}`,data:{note:"non-evm-submission-reference",reference:Ct(h,512)}}),s},failed({digest:f,reason:p=""}={}){let w=m(f);return w&&(u.delete(w.digest),l(w,"workflow.failed",{reference:`failed:${w.digest}`,data:{reason:Ct(p,300)}})),s},flush(){return s}})}import{appendFileSync as xf,existsSync as Sf,mkdirSync as Af,renameSync as vf,statSync as If}from"node:fs";import{dirname as kf}from"node:path";var Of="ORACLE_TELEMETRY_JSONL",Tf=32*1024*1024,za=4096;function Nf({path:e,maxBytes:t=Tf}={}){if(typeof e!="string"||e.trim().length===0)throw new F("jsonl exporter requires an explicit file path","invalid-exporter-path");let r=Number(t);if(!Number.isFinite(r)||r<za)throw new F(`jsonl exporter maxBytes must be >= ${za}`,"invalid-exporter-cap");let n=e;return Object.freeze({path:n,maxBytes:r,export(o){if(!Zn(o))throw new F("jsonl exporter accepts only sealed workflow telemetry records","invalid-record");let i=`${JSON.stringify(o)}
11
+ `;Af(kf(n),{recursive:!0,mode:448}),Sf(n)&&If(n).size+Buffer.byteLength(i)>r&&vf(n,`${n}.1`),xf(n,i,{mode:384})}})}function Wa(e=process.env,{maxBytes:t}={}){let r=String(e?.[Of]??"").trim();return r?Qn({exporter:Nf({path:r,...t===void 0?{}:{maxBytes:t}})}):Qn({})}import{createCipheriv as Tb,createDecipheriv as Cf,randomBytes as _f,scryptSync as Lf}from"node:crypto";import D from"node:fs";import _t from"node:path";var Rf="ORACLE-LOCAL-VAULT",$f=1,qr=Object.freeze({N:1<<17,r:8,p:1}),Pf=256*1024*1024,Bf=16*1024;function jr(e,t,r,{max:n=t}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${r} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<t||o.length>n)throw new Error(`local-vault: invalid ${r} length`);return o}function Df(e,t,r=qr){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");if(n.includes("\0"))throw new Error("local-vault: refusing zeroed passphrase material");return Lf(n,t,32,{...r,maxmem:Pf})}function Ua(e,t){if(e?.magic!==Rf||e?.version!==$f)throw new Error("local-vault: unsupported vault file");if(e?.kdf?.name!=="scrypt"||e?.cipher?.name!=="aes-256-gcm")throw new Error("local-vault: unsupported cryptography");if(e.kdf.N!==qr.N||e.kdf.r!==qr.r||e.kdf.p!==qr.p)throw new Error("local-vault: unsupported KDF parameters");if(Object.keys(e.kdf).sort().join(",")!=="N,name,p,r,salt"||Object.keys(e.cipher).sort().join(",")!=="iv,name")throw new Error("local-vault: unexpected cryptography field");if(!e.meta||Object.keys(e.meta).some(l=>!["address","addresses","kind","createdAt"].includes(l))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||JSON.stringify(e.meta.addresses||{}).length>1024||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let r=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(l=>!r.includes(l)))throw new Error("local-vault: unexpected vault field");let n=jr(e.kdf.salt,32,"salt"),o=jr(e.cipher.iv,12,"iv"),i=jr(e.tag,16,"tag"),a=jr(e.ciphertext,1,"ciphertext",{max:Bf}),{ciphertext:u,tag:s,...c}=e,d=Df(t,n);try{let l=Cf("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(c))),l.setAuthTag(i),Buffer.concat([l.update(a),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function Ff(e){if(!e.isFile())throw new Error("local-vault: secret source must be a regular file");if(e.uid!==process.getuid?.())throw new Error("local-vault: secret source must be owned by this user");if(e.nlink!==1)throw new Error("local-vault: refusing hard-linked secret source");if((e.mode&63)!==0)throw new Error("local-vault: secret source must be owner-only (0600)")}function jf(e){let t=_t.dirname(e),r=D.lstatSync(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(r.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((r.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=D.lstatSync(e);if(n.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!n.isFile()||n.uid!==process.getuid?.()||n.nlink!==1)throw new Error("local-vault: unsafe destination file");if(n.dev!==r.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function R(e){let t;try{t=D.openSync(e,D.constants.O_RDONLY|D.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=D.fstatSync(t);if(Ff(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=D.lstatSync(e);if(n.isSymbolicLink()||n.dev!==r.dev||n.ino!==r.ino)throw new Error("local-vault: secret source changed or is too large");return D.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{D.closeSync(t)}}function Va(e){return JSON.parse(R(e))}function Ae(e,t){D.mkdirSync(_t.dirname(e),{recursive:!0,mode:448}),jf(e);let r=_t.join(_t.dirname(e),`.${_t.basename(e)}.${process.pid}.${_f(6).toString("hex")}.tmp`);try{let n=D.openSync(r,D.constants.O_CREAT|D.constants.O_EXCL|D.constants.O_WRONLY|D.constants.O_NOFOLLOW,384);try{D.writeFileSync(n,String(t)),D.fsyncSync(n)}finally{D.closeSync(n)}D.renameSync(r,e),D.chmodSync(e,384);let o=D.openSync(_t.dirname(e),"r");try{D.fsyncSync(o)}finally{D.closeSync(o)}}catch(n){try{D.unlinkSync(r)}catch{}throw n}}var Ja=/^0x[0-9a-fA-F]+$/,qf=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});function Mf(e){let t=process.env[`ORACLE_PRIVATE_RELAY_${Number(e)}`];if(!t)return null;let r=t.split(",").map(n=>n.trim()).filter(Boolean);return r.length?r:null}function Hf(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=qf[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=Mf(r),i=o||n.endpoints,a=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&a!=="public-only";if(t&&!u)throw new Error(`private relay: no keyless private endpoint for chain ${r} (${n.name}); set ORACLE_PRIVATE_RELAY_${r} to force one, or allow public fallback`);return{chainId:r,name:n.name,mode:a,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function Ka(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!Ja.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let a=Hf(t,{requirePrivate:r}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let s=[];for(let c of a.endpoints){let d=new AbortController,l=setTimeout(()=>d.abort(),i);try{let m=await u(c,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendRawTransaction",params:[e]}),signal:d.signal}),f=await m.text(),p=null;try{p=JSON.parse(f)}catch{}if(p&&p.result&&Ja.test(p.result))return{hash:p.result,endpoint:c,mode:a.mode,chainId:a.chainId,fellBack:!1};s.push({endpoint:c,error:p&&p.error&&p.error.message||`http ${m.status}`})}catch(m){s.push({endpoint:c,error:String(m&&m.message||m).slice(0,160)})}finally{clearTimeout(l)}}if(n&&!r)return{fellBack:!0,mode:a.mode,chainId:a.chainId,attempts:s};throw new Error(`submitPrivate: all private endpoints failed for chain ${a.chainId} (${s.map(c=>`${c.endpoint}:${c.error}`).join("; ")||"none configured"})`)}import{createHmac as Wf,randomBytes as Uf,timingSafeEqual as Vf}from"node:crypto";import te from"node:fs";import ct from"node:path";import{homedir as eo}from"node:os";import{join as to}from"node:path";var Ga=process.env.ORACLE_PUBLIC_DESKTOP==="1",zf=Ga?process.env.ORACLE_CONFIG_DIR||to(eo(),".config","oracle"):to(eo(),".config","oracle"),Pb=Ga?zf:to(eo(),".config","mad-desk");var qb="0".repeat(64),Mb=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});function Mr(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Mr).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Mr(e[r])).join(",")+"}"}var Hb=Promise.resolve();function ut(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=a=>{try{return te.realpathSync(a)}catch{return ct.resolve(a)}},n=r(ct.dirname(ct.resolve(e))),o=r(ct.dirname(ct.resolve(t))),i=(a,u)=>u===a||u.startsWith(a+ct.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var Jf=864e5,ue=(e,t)=>Wf("sha256",t).update(Mr(e)).digest("hex"),Ce=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Vf(r,n)},Kf=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Gf(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(e.integrity.mac,ue(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function zr(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=R(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!Ce(n?.integrity?.mac,ue(n?.marker,t)))throw new Error("policy: sequence anchor integrity failed");return{sequence:Number(n?.marker?.policySequence||0),policyMac:n?.marker?.policyMac??null,present:!0,ledgerInitialized:n?.marker?.ledgerInitialized===!0}}function Yf(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let u=zr(e,r);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(t),policyMac:String(n)};i&&(a.ledgerInitialized=!0),Ae(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(a,r)}})+`
12
12
  `)}function Xf(e,t){let r=zr(e,t);if(!r.present)throw new Error("policy: sequence anchor required");if(r.ledgerInitialized)return!0;if(r.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");return Yf(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function Wr(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=R(t),o;try{o=JSON.parse(R(e))}catch(s){throw new Error(`policy: cannot read sealed policy: ${s?.message||s}`)}let i=Gf(o,n);ut(r,e);let a=zr(r,n),u=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(u!==a.sequence)throw new Error("policy: rolled back to a superseded policy");if(a.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!Ce(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Rt(e,t,r,n,o){let i=`${e}.continuity`,a;try{let u=JSON.parse(R(e));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(u?.integrity?.mac,ue(u.ledger,t)))throw new Error("integrity verification failed");if(a=u.ledger,!Number.isFinite(a?.windowStartMs)||!Array.isArray(a?.entries)||a.sequence!==void 0&&(!Number.isSafeInteger(a.sequence)||a.sequence<0))throw new Error("invalid ledger")}catch(u){if(u?.code==="ENOENT"){if(te.existsSync(i)||te.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let s=zr(o,t);if(s.present&&s.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:r,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}try{let u=JSON.parse(R(i));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(u?.integrity?.mac,ue(u.marker,t)))throw new Error("continuity verification failed");if(u.marker?.version===2&&(u.marker.sequence!==a.sequence||!Ce(u.marker.ledgerMac,ue(a,t))))throw new Error("continuity rollback detected");if(u.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(te.existsSync(n)&&(u.marker?.version!==2||a.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(u.marker?.version===2){let s=JSON.parse(R(n));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(s?.integrity?.mac,ue(s.marker,t))||s.marker?.version!==1||s.marker.sequence!==a.sequence||!Ce(s.marker.ledgerMac,ue(a,t)))throw new Error("checkpoint rollback detected")}}catch(u){throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}if(r-a.windowStartMs>=Jf){let u=new Date(r).toISOString().slice(0,10),s=d=>String(d||"").startsWith("cex:")&&String(d).endsWith(`:${u}`),c=a.entries.map(d=>{if(d.state==="reserved"||d.state==="consumed")return d;if(Array.isArray(d.units)){let l=d.units.map(f=>s(f.unit)?f:{...f,value:"0",notional:"0"}),m=l.some(f=>BigInt(f.value??0)>0n||BigInt(f.notional??0)>0n);return{...d,state:m?d.state:"consumed",units:l}}return s(d.unit)?d:{...d,state:"consumed",value:"0",notional:"0"}});return{windowStartMs:r,entries:c,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function Zf(e){return Array.isArray(e.units)?e.units:[{unit:e.unit||"wei",value:e.value,notional:e.notional,fee:e.fee}]}function ge(e,t,r){return e.reduce((n,o)=>{if(o.state==="released")return n;let i=Zf(o).find(a=>a.unit===r);return i?n+BigInt(i[t]??0):n},0n)}function Hr(e){if(!Array.isArray(e)||e.length===0)throw new Error("ledger: units array required");let t=new Set,r=e.map(n=>{let o=String(n?.unit||"");if(!o)throw new Error("ledger: unit required");if(t.has(o))throw new Error("ledger: duplicate unit in units array");t.add(o);let i=BigInt(n.value??0),a=BigInt(n.notional??0);if(i<0n||a<0n)throw new Error("ledger: unit value/notional must be non-negative");let u=n.fee===void 0?0n:BigInt(n.fee);if(u<0n)throw new Error("ledger: unit fee must be non-negative");return{unit:o,value:i.toString(),notional:a.toString(),fee:u.toString()}});return r.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),r}function Qf(e,t){let r=e[t];if(r==null||r==="")throw new Error(`ledger: ${t} required`);return se(r,`ledger: ${t}`)}function Lt(e,t){if(String(t).startsWith("cex:")){let[,n,o,i,a,u]=String(t).split(":");if(!/^[A-Za-z0-9._-]{1,64}$/.test(n||"")||!/^[A-Za-z0-9._-]{1,64}$/.test(o||"")||!/^[a-z0-9._-]{1,32}$/.test(i||"")||!/^[A-Z0-9._-]{1,24}$/.test(a||"")||!/^\d{4}-\d{2}-\d{2}$/.test(u||""))throw new Error("ledger: invalid CEX accounting unit");let s=e.cexAccounts?.[n];if(!s||String(s.accountId)!==o||!Array.isArray(s.venues)||!s.venues.includes(i))throw new Error("ledger: CEX account/venue policy required");if(!s.symbolQuotes||!Object.values(s.symbolQuotes).includes(a))throw new Error("ledger: CEX quote policy required");let c=se(s.dailyGrossQuoteCap,"ledger: dailyGrossQuoteCap"),d=se(s.perOrderQuoteCap,"ledger: perOrderQuoteCap");return[c,c,d]}if(String(t).startsWith("erc20:")){let n=String(t).slice(6).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("ledger: invalid ERC20 accounting unit");let o=Object.entries(e.tokenCaps||e.nftPaymentTokenCaps||{}).find(([a])=>String(a).toLowerCase()===n)?.[1];if(!o)throw new Error("ledger: ERC-20 token caps required");let i=["maxDailyValueRaw","maxDailyNotionalRaw","maxPerTradeRaw"];for(let a of i)if(o[a]===void 0||o[a]===null||o[a]==="")throw new Error(`ledger: ${a} required`);return i.map(a=>BigInt(o[a]))}let r=t==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:t==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:t==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:t==="usdc"?["maxDailyValueUsdc","maxDailyNotionalUsdc","maxPerTradeUsdc"]:null;if(!r)throw new Error("ledger: unsupported accounting unit");if(t==="usdc"){let n=r.filter(s=>e[s]!==void 0&&e[s]!==null&&e[s]!=="");if(n.length===r.length)return r.map(s=>Qf(e,s));if(n.length>0){let s=r.filter(c=>!n.includes(c));throw new Error(`ledger: ${s[0]} required`)}let o=e.maxDailyNotionalUsd??e.maxNotionalUsd??e.maxNotionalUsdc,i=e.maxPerTradeUsd??e.maxNotionalUsd??e.maxNotionalUsdc;if(o==null||o==="")throw new Error("ledger: maxDailyValueUsdc required");if(i==null||i==="")throw new Error("ledger: maxPerTradeUsdc required");let a=M(o,6,"ledger: maxDailyNotionalUsdc"),u=M(i,6,"ledger: maxPerTradeUsdc");return[a,a,u]}for(let n of r)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return r.map(n=>BigInt(e[n]))}function $t(e,t){let r=`${e}.lock`,n=Uf(16).toString("hex"),o;try{o=te.openSync(r,te.constants.O_CREAT|te.constants.O_EXCL|te.constants.O_WRONLY|(te.constants.O_NOFOLLOW||0),384),te.writeFileSync(o,n),te.fsyncSync(o)}catch(i){throw o!==void 0&&te.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return t()}finally{te.closeSync(o);try{R(r)===n&&te.unlinkSync(r)}catch{}}}function De(e,t,r,n,o){let i=`${e}.continuity`,a={...t,sequence:(t.sequence??0)+1},u=ue(a,r);Ae(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:u}})+`
13
13
  `);let s={version:2,sequence:a.sequence,ledgerMac:u};Ae(i,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(s,r)}})+`
14
14
  `);let c={version:1,sequence:a.sequence,ledgerMac:u};te.mkdirSync(ct.dirname(n),{recursive:!0,mode:448}),Ae(n,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(c,r)}})+`
15
- `),o&&Xf(o,r)}function rr({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:u=0,fee:s,units:c,policy:d,retryReleasedTradeId:l,nowMs:m=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");ut(r,e);let p=R(t);return $t(e,()=>{let w=Rt(e,p,m,r,n),g=w.entries.find(y=>String(y.tradeId)===f);if(g){if(g.state!=="released"||String(l||"")!==f)throw new Error("ledger: replayed tradeId");if(c!==void 0){let y=Hr(c);if(!Array.isArray(g.units)||JSON.stringify(g.units)!==JSON.stringify(y))throw new Error("ledger: released reservation mismatch");for(let b of y){let[S,A,k]=Lt(d,b.unit);if(BigInt(b.notional)>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",b.unit)+BigInt(b.value)>S||ge(w.entries,"notional",b.unit)+BigInt(b.notional)>A)throw new Error("ledger: daily cap exceeded")}}else{let y={unit:i,value:BigInt(a).toString(),notional:BigInt(u).toString(),fee:s===void 0?"0":BigInt(s).toString()};if(Array.isArray(g.units)||g.unit!==y.unit||g.value!==y.value||g.notional!==y.notional||String(g.fee??"0")!==y.fee)throw new Error("ledger: released reservation mismatch");let[b,S,A]=Lt(d,i);if(BigInt(y.notional)>A)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+BigInt(y.value)>b||ge(w.entries,"notional",i)+BigInt(y.notional)>S)throw new Error("ledger: daily cap exceeded")}return g.state="reserved",g.atMs=m,g.retriedAtMs=m,delete g.releasedAtMs,De(e,w,p,r,n),structuredClone(g)}let h;if(c!==void 0){let y=Hr(c);for(let b of y){let[S,A,k]=Lt(d,b.unit),v=BigInt(b.value),_=BigInt(b.notional);if(_>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",b.unit)+v>S||ge(w.entries,"notional",b.unit)+_>A)throw new Error("ledger: daily cap exceeded")}h={tradeId:f,units:y,state:"reserved",atMs:m}}else{let y=BigInt(a),b=BigInt(u),[S,A,k]=Lt(d,i);if(y<0n||b<0n||b>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+y>S||ge(w.entries,"notional",i)+b>A)throw new Error("ledger: daily cap exceeded");h={tradeId:f,unit:i,value:y.toString(),notional:b.toString(),fee:s===void 0?"0":BigInt(s).toString(),state:"reserved",atMs:m}}return w.entries.push(h),De(e,w,p,r,n),structuredClone(h)})}function Ya({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:u=Date.now()}){ut(r,e);let s=R(t);return $t(e,()=>{let c=Rt(e,s,u,r,n),d=c.entries.find(w=>String(w.tradeId)===String(o?.tradeId??"")&&w.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let w=Hr(o.units);if(JSON.stringify(w)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(a){if(!Array.isArray(a.units))throw new Error("ledger: reserved units no longer match decoded economics");let g=Hr(a.units);if(g.length!==d.units.length||g.some((h,y)=>h.unit!==d.units[y].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let h=0;h<g.length;h++)if(BigInt(g[h].value)>BigInt(d.units[h].value)||BigInt(g[h].notional)>BigInt(d.units[h].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let g of d.units){let[h,y,b]=Lt(i,g.unit);if(BigInt(g.notional)>b)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",g.unit)>h||ge(c.entries,"notional",g.unit)>y)throw new Error("ledger: daily cap exceeded")}return structuredClone(d)}if(d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(d.value)||BigInt(a.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[m,f,p]=Lt(i,l);if(BigInt(d.notional)>p)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",l)>m||ge(c.entries,"notional",l)>f)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function Xa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let a=R(t);return $t(e,()=>{let u=Rt(e,a,i,r,n),s=u.entries.find(c=>String(c.tradeId)===String(o??""));if(!s)throw new Error("ledger: reservation unavailable");if(s.state==="committed"&&["fee-only","no-fee"].includes(s.settledAs))throw new Error("ledger: reservation unavailable");if(s.state==="committed")return structuredClone(s);if(s.state!=="reserved")throw new Error("ledger: reservation unavailable");return s.state="committed",s.committedAtMs=i,De(e,u,a,r,n),structuredClone(s)})}function Za({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let a=R(t);return $t(e,()=>{let u=Rt(e,a,i,r,n),s=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!s)throw new Error("ledger: reservation unavailable");let c=structuredClone(s);return s.state="released",s.releasedAtMs=i,De(e,u,a,r,n),c})}function ep(e,t){if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(e)))throw new Error("ledger: authoritative CEX fill invalid");let[r,n=""]=String(e).split("."),o=n.length;return BigInt(r+n)>BigInt(t)*10n**BigInt(o)}function Qa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:a,disposition:u,nowMs:s=Date.now()}){if(ut(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let c=R(t);return $t(e,()=>{let d=Rt(e,c,s,r,n),l=d.entries.find(m=>m.tradeId===o&&m.state==="reserved"&&m.unit===i);if(!l)throw new Error("ledger: exact held CEX reservation unavailable");if(ep(a,l.notional))throw new Error("ledger: CEX overfill refused; reservation retained");if(u==="release"){if(!/^0(?:\.0+)?$/.test(a))throw new Error("ledger: nonzero CEX fill cannot release");let m=structuredClone(l);return l.state="consumed",l.releasedAtMs=s,l.value="0",l.notional="0",l.fee="0",De(e,d,c,r,n),m}return l.state="committed",l.committedAtMs=s,l.filledQuote=a,De(e,d,c,r,n),structuredClone(l)})}function es({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let a=R(t);return $t(e,()=>{let u=Rt(e,a,i,r,n),s=u.entries.find(d=>String(d.tradeId)===String(o??""));if(!s)throw new Error("ledger: reservation unavailable");if(s.state==="committed"&&["fee-only","no-fee"].includes(s.settledAs))return structuredClone(s);if(s.state!=="reserved")throw new Error("ledger: reservation unavailable");if(Array.isArray(s.units))return s.state="committed",s.committedAtMs=i,s.units=s.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),s.settledAs=s.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",De(e,u,a,r,n),structuredClone(s);let c=BigInt(s.fee??0);return c<=0n?(s.state="committed",s.committedAtMs=i,s.value="0",s.notional="0",s.settledAs="no-fee",De(e,u,a,r,n),structuredClone(s)):(s.state="committed",s.committedAtMs=i,s.value="0",s.notional=c.toString(),s.settledAs="fee-only",De(e,u,a,r,n),structuredClone(s))})}function ts(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(Kf(t))};return Ce(e.mac,ue(o,R(r)))}function tp(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function rs(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(t.owner).toLowerCase(),action:String(t.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(tp(t))};return Ce(e.mac,ue(o,R(r)))}import{spawnSync as rp}from"node:child_process";function ns(e="oracle-local-signer",t=process.env.USER||process.env.USERNAME||"oracle"){let r,n;if(process.platform==="darwin")r="/usr/bin/security",n=["find-generic-password","-s",e,"-a",t,"-w"];else if(process.platform==="linux")r="secret-tool",n=["lookup","service",e,"account",t];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let o=rp(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}var np=/^0x[0-9a-f]{40}$/,op=/^0x(?:[0-9a-f]{2})*$/,ip=/^(?:0x)?[0-9a-f]{64}$/,ap=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,sp=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,cp=new Set([12,15,18,21,24]),Ur=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function ro(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(sp.test(e)||cp.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new Ur(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,i)=>ro(o,`${t}[${i}]`,r));lt(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(ap.test(i))throw new Ur(`${t}.${o}`);e[o]!==void 0&&(n[o]=ro(e[o],`${t}.${o}`,o))}return n}function lt(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function nr(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Pt(e,t){let r=String(nr(e,t)).toLowerCase();if(!np.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function Fe(e,t,{positive:r=!1}={}){try{let n=BigInt(nr(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function no(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function os(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))os(t);Object.freeze(e)}return e}function up(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};lt(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:no(String(n),`${t}.reason`)}}function lp(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>up(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function dp(e){if(e==null)return null;if(lt(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:no(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=Fe(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=Fe(e.gasLimit,"simulation.gasLimit")),t}function fp(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{lt(t,`assetDeltas[${r}]`);let n=Fe(t.before,`assetDeltas[${r}].before`),o=Fe(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),a;try{a=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(a!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:no(String(nr(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:a}})}function pp(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{lt(t,`approvalDeltas[${r}]`);let n=Fe(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Pt(t.token,`approvalDeltas[${r}].token`),spender:Pt(t.spender,`approvalDeltas[${r}].spender`),owner:Pt(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function is(e={}){lt(e,"input");let t=ro(e),r=t.tx==null?t:lt(t.tx,"tx"),n=Fe(t.chainId??r.chainId,"chainId",{positive:!0}),o=Pt(t.account??t.from??r.from,"account/from"),i=Pt(t.destination??t.to??r.to,"destination/to"),a=String(nr(t.prepareHash,"prepareHash")).toLowerCase();if(!ip.test(a))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let u=t.route??t.venue;if(u==null)throw new TypeError("sign-time review: route/venue required");let s=t.decodedCalldata??t.decodedAction;if(s==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let c=String(nr(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!op.test(c))throw new TypeError("sign-time review: calldata/data must be even-length hex");let d=t.policyChecks!==void 0&&t.policyChecks!==null,l=lp(d?t.policyChecks:[]),m=dp(t.simulation),f=fp(t.assetDeltas),p=pp(t.approvalDeltas),w=t.allowlistHits??[];if(!Array.isArray(w))throw new TypeError("sign-time review: allowlistHits must be an array");let g=m?.willRevert===!0||["failed","error"].includes(m?.status),h=m!=null&&m.willRevert===!1&&["ok","success"].includes(m.status),y=g||l.failed>0?"BLOCKED":h&&d&&l.checks.length>0&&f!=null?"READY":"UNKNOWN",b=typeof s=="string"?s:s.method??s.action??s.type??"transaction",S=`${y}: review ${b} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${f?.length??0} asset delta${f?.length===1?"":"s"}; local signature required`,A={reviewVersion:1,status:y,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:u,venue:t.venue??(typeof u=="string"?u:u.venue??u.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:Pt(t.spender,"spender")},prepareHash:a,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:c,data:c,selector:c.length>=10?c.slice(0,10):null,value:Fe(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:Fe(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:Fe(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:l,allowlistHits:w,assetDeltas:f,approvalDeltas:p,summary:S};return os(A)}import{readFileSync as mp,readdirSync as wp,existsSync as cs}from"node:fs";import{dirname as hp,join as Bt}from"node:path";import{fileURLToPath as gp}from"node:url";var or=hp(gp(import.meta.url));function yp(){let e=[Bt(or,"descriptors"),Bt(or,"clear-sign","descriptors"),Bt(or,"..","clear-sign","descriptors"),Bt(or,"..","..","clear-sign","descriptors"),Bt(or,"..","..","..","clear-sign","descriptors")];for(let t of e)if(cs(t))return t;return e[0]}var bp=yp(),Ep=/^0x[0-9a-f]{8}/,xp=/^0x[0-9a-fA-F]{40}$/;function Sp(e=bp){if(!cs(e))return[];let t=[];for(let r of wp(e).filter(n=>n.endsWith(".json")).sort()){let n=mp(Bt(e,r),"utf8"),o;try{o=JSON.parse(n)}catch(i){throw new Error(`clear-sign descriptor ${r} is not valid JSON: ${i.message}`)}t.push({file:r,doc:o})}return t}function Ap(e,{to:t=null,chainId:r=null}={},n=Sp()){let o=String(e||"").toLowerCase(),i=Ep.test(o)?o.slice(0,10):null;if(!i)return null;let a=t&&xp.test(String(t))?String(t).toLowerCase():null;for(let{file:u,doc:s}of n){let c=s?.display?.formats||{};for(let[d,l]of Object.entries(c)){if(String(l?.$selector||"").toLowerCase()!==i)continue;let m=s?.context?.contract?.deployments||[],f=m.length===0,p=m.some(w=>(r==null||Number(w.chainId)===Number(r))&&a&&String(w.address||"").toLowerCase()===a);if(f||p)return{file:u,signature:d,format:l,doc:s,selector:i,generic:f}}}return null}function us(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function vp(e,t){let r=us(e,t);return r?`0x${r.slice(24)}`:null}function as(e,t){let r=us(e,t);return r?BigInt(`0x${r}`).toString():null}var Ip=(1n<<256n)-1n;function ss(e){if(e==null)return"unknown";let t=BigInt(e);return t>=Ip/2n?"UNLIMITED":t.toString()}function ls(e,{to:t=null,chainId:r=null}={},n=void 0){let o=Ap(e,{to:t,chainId:r},n);if(!o)return null;let i=String(e||"").toLowerCase(),a=i.slice(10),u=[],s=[];for(let c of o.format.fields||[]){if(c.visible==="never")continue;let d=c.$wordIndex,l=null;Number.isInteger(d)&&(l=c.format==="addressName"||c.format==="raw-address"?vp(a,d):c.format==="amount"||c.format==="tokenAmount"?ss(as(a,d)):as(a,d)),l!=null&&(s.push({label:c.label,value:l}),u.push(`${c.label}: ${l}`))}if(oe(i)){let c=null,d=null;try{c=Re(i)}catch(l){let m=String(l?.message||l);if(/unlimited approvals are refused/i.test(m))d="ORACLE POLICY: unlimited approval \u2014 Oracle refuses to prepare this; bound the amount";else return{ok:!1,refused:`descriptor matched but reviewed decoder refused: ${m}`,intent:o.format.intent}}if(c){let l=s.find(p=>/spender/i.test(p.label))?.value?.toLowerCase();if(l&&c.spender&&l!==c.spender.toLowerCase())return{ok:!1,refused:"descriptor spender disagrees with reviewed decoder",intent:o.format.intent};let m=s.find(p=>/amount|allowance/i.test(p.label))?.value,f=ss(c.amount);if(m!=null&&c.amount!=null&&String(m)!==f)return{ok:!1,refused:"descriptor amount disagrees with reviewed decoder",intent:o.format.intent}}return d&&u.push(d),{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:s,lines:u,...d?{policyNote:d}:{}}}return{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:s,lines:u}}var kp=/^0x[0-9a-f]{40}$/;function ir(e){let t=String(e??"").toLowerCase();return kp.test(t)?t:null}function Op(e,{token:t,owner:r}){if(!oe(e))return[];let n;try{n=Re(e)}catch{return[]}let o={token:ir(n.token??t),spender:ir(n.spender),owner:ir(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Tp(e,t,r={}){let n=e?.version===1&&e?.surface?e:null,o=n?.surface||"evm";if(o!=="evm"&&o!=="evm-nft")return null;let i=n?.artifact||e||{},a=ir(n?.owner??i.from),u=ir(i.to??n?.destination),s=String(i.data??"0x").toLowerCase();if(!a||!u)return null;let c=[],d=r?.destinationAllowlist;if(Array.isArray(d)&&d.length){let l=d.map(m=>String(m).toLowerCase()).includes(u);c.push({name:"destination-allowlist",passed:l,reason:l?"destination is allowlisted":"destination is not on the allowlist"})}try{return is({chainId:i.chainId,account:a,destination:u,calldata:s,value:i.value??0,prepareHash:t,route:n?.provider??n?.venue??o,decodedAction:n?.action??"transaction",...i.gasLimit==null?{}:{gasLimit:i.gasLimit},...c.length?{policyChecks:c}:{},approvalDeltas:Op(s,{token:u,owner:a})})}catch{return null}}function ds(e,t,r={}){let n=Tp(e,t,r);if(!n)return[];let o=[`REVIEW status=${n.status} action=${n.decodedAction??"transaction"} selector=${n.selector??"none"}`,`REVIEW route=${typeof n.route=="string"?n.route:n.venue??"n/a"} value=${n.value} signing=local custody=${n.custody}`];n.policyChecks.checks.length&&o.push(`REVIEW policy passed=${n.policyChecks.passed} failed=${n.policyChecks.failed}${n.policyChecks.failed?` reasons=${n.policyChecks.reasons.join("; ")}`:""}`);for(let i of n.approvalDeltas)o.push(`REVIEW APPROVAL token=${i.token} spender=${i.spender} amount=${i.amount} revokeLike=${i.revokeLike}`);n.assetDeltas==null&&o.push("REVIEW assetDeltas=unavailable (no simulated balance change supplied)"),n.status!=="READY"&&o.push("REVIEW status is not READY: these facts are decoded, not proven safe.");try{let i=e?.artifact||e||{},a=ls(String(i.data??"0x"),{to:i.to??null,chainId:i.chainId??null});if(a?.ok){o.push(`CLEAR-SIGN intent=${a.intent} [${a.descriptor}]`);for(let u of a.lines)o.push(`CLEAR-SIGN ${u}`)}else a&&a.refused&&o.push(`CLEAR-SIGN REFUSED: ${a.refused}`)}catch{}return o}import{Wallet as oo}from"ethers";import{base58 as io}from"@scure/base";import{ed25519 as hs}from"@noble/curves/ed25519.js";import{NETWORK as gs,TEST_NETWORK as ys,WIF as Np,p2wpkh as fs}from"@scure/btc-signer";import{pubECDSA as Cp}from"@scure/btc-signer/utils.js";var Vr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},_p=e=>{let t=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return null;let r=Buffer.from(t,"base64");return r.toString("base64")===t?r:null},ps=e=>{let t=String(e||"").trim();try{let r=Buffer.from(io.decode(t));return io.encode(r)===t?r:null}catch{return null}},ao=e=>{if(!(e instanceof Uint8Array))throw new Error("sol: key bytes required");if(e.length!==32&&e.length!==64)throw new Error("sol: expected 32-byte private key material");let t=Buffer.from(e.subarray(0,32));if(e.length===64){let r=Buffer.from(e.subarray(32,64)),n=Buffer.from(hs.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},ms=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),je=(e,t)=>{if(t==="sol")return ao(e);if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)},Lp=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return je(r,t)};function so(e,t){let r=String(t||"").trim();if(e==="evm")return new oo(r).privateKey;if(e==="btc")for(let i of[gs,ys])try{return Buffer.from(Np(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let c=Vr(r.slice(4));if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}if(/^base58:/i.test(r)){let c=ps(r.slice(7));if(!ms(c))throw new Error("sol: invalid explicit base58 private key");return ao(c)}if(/^0x/i.test(r)){let c=Vr(r);if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}let i=Vr(r),a=i&&(i.length===32||i.length===64)?je(i,"sol"):null,u=ps(r),s=ms(u);if(a&&s&&!a.equals(s))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(s)return ao(u);if(i)return je(i,"sol")}let n=Vr(r);if(n)return e==="evm"?new oo(`0x${n.toString("hex")}`).privateKey:je(n,e);let o=_p(r);if(o)return je(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Lp(i,e);let a=i.privateKey??i.secretKey??i.key;if(a)return so(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function ws(e,t){if(e==="evm"){let r=new oo(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=je(t,"btc"),n=Cp(r);return{kind:e,secret:r.toString("hex"),addresses:[fs(n,gs).address,fs(n,ys).address]}}if(e==="sol"){let r=je(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[io.encode(hs.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function bs(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:ws(t.kind||"evm",so(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=ws(i,so(i,n[i])));if(n.cex!==void 0){if(!n.cex||typeof n.cex!="object"||Array.isArray(n.cex))throw new Error("local-vault: cex credential records invalid");o.cex={};for(let[i,a]of Object.entries(n.cex)){if(!/^[A-Za-z0-9._-]{1,64}$/.test(i)||!a||typeof a!="object")throw new Error("local-vault: cex credential record invalid");if(!/^(?:binance|bybit|okx|coinbase)$/.test(a.venue)||!/^[A-Za-z0-9._-]{1,64}$/.test(a.accountId||""))throw new Error("local-vault: cex credential binding invalid");let u=(c,d=!0)=>{let l=a[c];if(!(!d&&l===void 0)){if(!Array.isArray(l)||l.length<4||l.some(m=>!Number.isInteger(m)||m<0||m>255))throw new Error("local-vault: cex credential bytes invalid");return Buffer.from(l)}},s=a.apiSecretEncoding;if(s!==(a.venue==="coinbase"?"base64":"raw"))throw new Error("local-vault: explicit cex secret encoding refused");o.cex[i]=Object.freeze({venue:a.venue,accountId:a.accountId,apiKeyBytes:u("apiKeyBytes"),apiSecretBytes:u("apiSecretBytes"),apiSecretEncoding:s,passphraseBytes:u("passphraseBytes",!1)})}if(!Object.keys(o.cex).length)throw new Error("local-vault: empty cex credential records refused");Object.freeze(o.cex)}if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function co(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Rp=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),$p=Object.freeze(["binance","bybit","okx","coinbase"]),Pp=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Bp=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Dp=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),y0=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),Fp=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),b0=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),E0=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),x0=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),S0=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function uo(e,t){let r=String(e??"");if(!/^\d+$/.test(r))throw new Error(`cex-policy: ${t} must be an integer string`);return BigInt(r)}function le(e,t,r){let n=String(e??"");if(!r.test(n))throw new Error(`cex-policy: bounded ${t} required`);return n}function Es(e,t){let r=String(e??"");if(!/^(?:0|[1-9]\d{0,29})(?:\.\d{1,18})?$/.test(r))throw new Error(`cex-policy: positive decimal ${t} required`);let[n,o=""]=r.split("."),i=BigInt(`${n}${o}`);if(i<=0n)throw new Error(`cex-policy: positive decimal ${t} required`);return{text:r,numerator:i,scale:o.length}}function jp(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function qp(e){return new Date(e).toISOString().slice(0,10)}function Mp(e,t){let r=le(e.credentialRef,"credentialRef",/^[A-Za-z0-9._-]{1,64}$/),n=t.cexAccounts?.[r];if(!n||typeof n!="object")throw new Error("cex-policy: sealed account policy required");return{credentialRef:r,account:n}}function Jr(e={},t={},r=Date.now()){for(let C of Object.keys(e)){let z=C.toLowerCase();if(Fp.some(W=>W.toLowerCase()===z))throw new Error(`cex-policy: envelope field ${C} forbidden`);if(!Dp.includes(C))throw new Error(`cex-policy: envelope field ${C} not in allowlist`)}if(e.version!==1)throw new Error("cex-policy: version 1 required");if(e.surface!=="cex")throw new Error("cex-policy: surface cex required");let n=String(e.kind||"");if(!Rp.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=le(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!$p.includes(o)||!Pp[o]||!Bp[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:a}=Mp(e,t);if(!Array.isArray(a.venues)||!a.venues.includes(o))throw new Error(`cex-policy: venue ${o} not allowlisted`);let u=le(e.symbol,"symbol",/^[A-Z0-9._/-]{1,32}$/);if(!Array.isArray(a.symbols)||!a.symbols.includes(u))throw new Error(`cex-policy: symbol ${u} not allowlisted`);let s=le(e.quote,"quote",/^[A-Z0-9._-]{1,24}$/);if(!a.symbolQuotes||typeof a.symbolQuotes!="object"||a.symbolQuotes[u]!==s)throw new Error("cex-policy: quote does not match sealed symbol policy");let c=le(a.accountId,"accountId",/^[A-Za-z0-9._-]{1,64}$/);if(!Array.isArray(a.allowedOperations)||!a.allowedOperations.includes(n))throw new Error("cex-policy: operation not in sealed allowlist");let d=le(e.base,"base",/^[A-Z0-9._-]{1,24}$/);if(a.base!==d||a.quote!==s)throw new Error("cex-policy: base/quote do not match sealed account policy");if(a.credentialRecordRef!==i)throw new Error("cex-policy: credential record reference mismatch");let l=a.filters?.[u];if(!l||typeof l.tickSize!="string"||typeof l.stepSize!="string"||typeof l.minNotional!="string")throw new Error("cex-policy: sealed symbol filters required");le(e.nonce,"nonce",/^[A-Za-z0-9._:-]{1,128}$/),le(e.grantId,"grantId",/^[A-Za-z0-9._:-]{1,128}$/),le(e.artifactHash,"artifactHash",/^[A-Za-z0-9._:-]{1,128}$/);let m=e.clientOrderId===void 0?void 0:le(e.clientOrderId,"clientOrderId",/^[A-Za-z0-9._-]{1,64}$/),f,p,w,g,h=0n,y=0n,b;if(n==="spot-limit-create"){if(f=le(e.side,"side",/^(?:buy|sell)$/),p=le(e.timeInForce,"timeInForce",/^GTC$/),w=Es(e.baseSize,"baseSize"),g=Es(e.limitPrice,"limitPrice"),!m)throw new Error("cex-policy: clientOrderId required");if(h=uo(e.maxQuoteNotional,"maxQuoteNotional"),y=jp(w,g),h<y)throw new Error("cex-policy: maxQuoteNotional understates baseSize times limitPrice")}else{for(let C of["side","baseSize","limitPrice","maxQuoteNotional","timeInForce"])if(e[C]!==void 0)throw new Error(`cex-policy: ${C} forbidden for cancel/status`);if(b=e.venueOrderId===void 0?void 0:le(e.venueOrderId,"venueOrderId",/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/),!b&&!m)throw new Error("cex-policy: exact prior order id required")}let S=uo(a.perOrderQuoteCap,"sealed perOrderQuoteCap"),A=uo(a.dailyGrossQuoteCap,"sealed dailyGrossQuoteCap");if(h>S)throw new Error("cex-policy: maxQuoteNotional exceeds sealed perOrderQuoteCap");if(h>A)throw new Error("cex-policy: maxQuoteNotional exceeds sealed dailyGrossQuoteCap");let k=Number(e.expiresAtMs);if(!Number.isSafeInteger(k)||k<=r||k-r>12e4)throw new Error("cex-policy: bounded expiry required");let v=`cex:${i}:${o}:${c}:${m||b}`,_=`cex:${i}:${c}:${o}:${s}:${qp(r)}`;return Object.freeze({kind:n,venue:o,symbol:u,base:d,quote:s,side:f,timeInForce:p,baseSize:w?.text,limitPrice:g?.text,clientOrderId:m,venueOrderId:b,filter:Object.freeze({...l}),accountId:c,credentialRef:i,tradeId:v,unit:_,notional:h.toString(),impliedNotional:y.toString()})}function xs({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Wr(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Jr(e,n,r);return rr({file:t.ledger,keyFile:t.policyKey,anchorFile:t.ledgerAnchor,policyAnchorFile:t.policyAnchor,tradeId:o.tradeId,unit:o.unit,value:o.notional,notional:o.notional,policy:n,nowMs:r})}import J from"node:fs";import dt from"node:path";import{createHmac as Hp,randomBytes as zp,timingSafeEqual as Wp}from"node:crypto";var Kr=(e,t)=>Hp("sha256",e).update(JSON.stringify(t)).digest("hex"),Ss=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Wp(r,n)},As=e=>Buffer.from(R(e));function vs({file:e,keyFile:t,anchorFile:r}){if(!e||!t||!r)throw new Error("cex-state: protected paths required");if(dt.dirname(dt.resolve(e))===dt.dirname(dt.resolve(r)))throw new Error("cex-state: external rollback anchor required");let n=`${e}.lock`,o=(()=>{try{return J.readFileSync(`/proc/${process.pid}/stat`,"utf8").trim().split(/\s+/)[21]}catch{return null}})(),i=d=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,d),a=d=>{if(!Number.isSafeInteger(d.pid)||d.pid<1||typeof d.processStart!="string"||!d.processStart)return null;try{process.kill(d.pid,0)}catch(l){return l?.code==="ESRCH"?!1:null}try{return J.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{J.mkdirSync(dt.dirname(n),{recursive:!0,mode:448});let l=zp(16).toString("hex"),m=Date.now()+5e3,f=`${n}.${process.pid}.${l}.tmp`,p=JSON.stringify({version:1,pid:process.pid,processStart:o,token:l,createdAtMs:Date.now()})+`
15
+ `),o&&Xf(o,r)}function rr({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:u=0,fee:s,units:c,policy:d,retryReleasedTradeId:l,nowMs:m=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");ut(r,e);let p=R(t);return $t(e,()=>{let w=Rt(e,p,m,r,n),g=w.entries.find(y=>String(y.tradeId)===f);if(g){if(g.state!=="released"||String(l||"")!==f)throw new Error("ledger: replayed tradeId");if(c!==void 0){let y=Hr(c);if(!Array.isArray(g.units)||JSON.stringify(g.units)!==JSON.stringify(y))throw new Error("ledger: released reservation mismatch");for(let b of y){let[S,A,k]=Lt(d,b.unit);if(BigInt(b.notional)>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",b.unit)+BigInt(b.value)>S||ge(w.entries,"notional",b.unit)+BigInt(b.notional)>A)throw new Error("ledger: daily cap exceeded")}}else{let y={unit:i,value:BigInt(a).toString(),notional:BigInt(u).toString(),fee:s===void 0?"0":BigInt(s).toString()};if(Array.isArray(g.units)||g.unit!==y.unit||g.value!==y.value||g.notional!==y.notional||String(g.fee??"0")!==y.fee)throw new Error("ledger: released reservation mismatch");let[b,S,A]=Lt(d,i);if(BigInt(y.notional)>A)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+BigInt(y.value)>b||ge(w.entries,"notional",i)+BigInt(y.notional)>S)throw new Error("ledger: daily cap exceeded")}return g.state="reserved",g.atMs=m,g.retriedAtMs=m,delete g.releasedAtMs,De(e,w,p,r,n),structuredClone(g)}let h;if(c!==void 0){let y=Hr(c);for(let b of y){let[S,A,k]=Lt(d,b.unit),v=BigInt(b.value),_=BigInt(b.notional);if(_>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",b.unit)+v>S||ge(w.entries,"notional",b.unit)+_>A)throw new Error("ledger: daily cap exceeded")}h={tradeId:f,units:y,state:"reserved",atMs:m}}else{let y=BigInt(a),b=BigInt(u),[S,A,k]=Lt(d,i);if(y<0n||b<0n||b>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+y>S||ge(w.entries,"notional",i)+b>A)throw new Error("ledger: daily cap exceeded");h={tradeId:f,unit:i,value:y.toString(),notional:b.toString(),fee:s===void 0?"0":BigInt(s).toString(),state:"reserved",atMs:m}}return w.entries.push(h),De(e,w,p,r,n),structuredClone(h)})}function Ya({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:u=Date.now()}){ut(r,e);let s=R(t);return $t(e,()=>{let c=Rt(e,s,u,r,n),d=c.entries.find(w=>String(w.tradeId)===String(o?.tradeId??"")&&w.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let w=Hr(o.units);if(JSON.stringify(w)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(a){if(!Array.isArray(a.units))throw new Error("ledger: reserved units no longer match decoded economics");let g=Hr(a.units);if(g.length!==d.units.length||g.some((h,y)=>h.unit!==d.units[y].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let h=0;h<g.length;h++)if(BigInt(g[h].value)>BigInt(d.units[h].value)||BigInt(g[h].notional)>BigInt(d.units[h].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let g of d.units){let[h,y,b]=Lt(i,g.unit);if(BigInt(g.notional)>b)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",g.unit)>h||ge(c.entries,"notional",g.unit)>y)throw new Error("ledger: daily cap exceeded")}return structuredClone(d)}if(d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(d.value)||BigInt(a.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[m,f,p]=Lt(i,l);if(BigInt(d.notional)>p)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",l)>m||ge(c.entries,"notional",l)>f)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function Xa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let a=R(t);return $t(e,()=>{let u=Rt(e,a,i,r,n),s=u.entries.find(c=>String(c.tradeId)===String(o??""));if(!s)throw new Error("ledger: reservation unavailable");if(s.state==="committed"&&["fee-only","no-fee"].includes(s.settledAs))throw new Error("ledger: reservation unavailable");if(s.state==="committed")return structuredClone(s);if(s.state!=="reserved")throw new Error("ledger: reservation unavailable");return s.state="committed",s.committedAtMs=i,De(e,u,a,r,n),structuredClone(s)})}function Za({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let a=R(t);return $t(e,()=>{let u=Rt(e,a,i,r,n),s=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!s)throw new Error("ledger: reservation unavailable");let c=structuredClone(s);return s.state="released",s.releasedAtMs=i,De(e,u,a,r,n),c})}function ep(e,t){if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(e)))throw new Error("ledger: authoritative CEX fill invalid");let[r,n=""]=String(e).split("."),o=n.length;return BigInt(r+n)>BigInt(t)*10n**BigInt(o)}function Qa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:a,disposition:u,nowMs:s=Date.now()}){if(ut(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let c=R(t);return $t(e,()=>{let d=Rt(e,c,s,r,n),l=d.entries.find(m=>m.tradeId===o&&m.state==="reserved"&&m.unit===i);if(!l)throw new Error("ledger: exact held CEX reservation unavailable");if(ep(a,l.notional))throw new Error("ledger: CEX overfill refused; reservation retained");if(u==="release"){if(!/^0(?:\.0+)?$/.test(a))throw new Error("ledger: nonzero CEX fill cannot release");let m=structuredClone(l);return l.state="consumed",l.releasedAtMs=s,l.value="0",l.notional="0",l.fee="0",De(e,d,c,r,n),m}return l.state="committed",l.committedAtMs=s,l.filledQuote=a,De(e,d,c,r,n),structuredClone(l)})}function es({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let a=R(t);return $t(e,()=>{let u=Rt(e,a,i,r,n),s=u.entries.find(d=>String(d.tradeId)===String(o??""));if(!s)throw new Error("ledger: reservation unavailable");if(s.state==="committed"&&["fee-only","no-fee"].includes(s.settledAs))return structuredClone(s);if(s.state!=="reserved")throw new Error("ledger: reservation unavailable");if(Array.isArray(s.units))return s.state="committed",s.committedAtMs=i,s.units=s.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),s.settledAs=s.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",De(e,u,a,r,n),structuredClone(s);let c=BigInt(s.fee??0);return c<=0n?(s.state="committed",s.committedAtMs=i,s.value="0",s.notional="0",s.settledAs="no-fee",De(e,u,a,r,n),structuredClone(s)):(s.state="committed",s.committedAtMs=i,s.value="0",s.notional=c.toString(),s.settledAs="fee-only",De(e,u,a,r,n),structuredClone(s))})}function ts(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(Kf(t))};return Ce(e.mac,ue(o,R(r)))}function tp(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function rs(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(t.owner).toLowerCase(),action:String(t.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(tp(t))};return Ce(e.mac,ue(o,R(r)))}import{spawnSync as rp}from"node:child_process";function ns(e="oracle-local-signer",t=process.env.USER||process.env.USERNAME||"oracle"){let r,n;if(process.platform==="darwin")r="/usr/bin/security",n=["find-generic-password","-s",e,"-a",t,"-w"];else if(process.platform==="linux")r="secret-tool",n=["lookup","service",e,"account",t];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let o=rp(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}var np=/^0x[0-9a-f]{40}$/,op=/^0x(?:[0-9a-f]{2})*$/,ip=/^(?:0x)?[0-9a-f]{64}$/,ap=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,sp=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,cp=new Set([12,15,18,21,24]),Ur=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function ro(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(sp.test(e)||cp.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new Ur(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,i)=>ro(o,`${t}[${i}]`,r));lt(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(ap.test(i))throw new Ur(`${t}.${o}`);e[o]!==void 0&&(n[o]=ro(e[o],`${t}.${o}`,o))}return n}function lt(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function nr(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Pt(e,t){let r=String(nr(e,t)).toLowerCase();if(!np.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function Fe(e,t,{positive:r=!1}={}){try{let n=BigInt(nr(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function no(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function os(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))os(t);Object.freeze(e)}return e}function up(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};lt(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:no(String(n),`${t}.reason`)}}function lp(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>up(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function dp(e){if(e==null)return null;if(lt(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:no(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=Fe(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=Fe(e.gasLimit,"simulation.gasLimit")),t}function fp(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{lt(t,`assetDeltas[${r}]`);let n=Fe(t.before,`assetDeltas[${r}].before`),o=Fe(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),a;try{a=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(a!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:no(String(nr(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:a}})}function pp(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{lt(t,`approvalDeltas[${r}]`);let n=Fe(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Pt(t.token,`approvalDeltas[${r}].token`),spender:Pt(t.spender,`approvalDeltas[${r}].spender`),owner:Pt(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function is(e={}){lt(e,"input");let t=ro(e),r=t.tx==null?t:lt(t.tx,"tx"),n=Fe(t.chainId??r.chainId,"chainId",{positive:!0}),o=Pt(t.account??t.from??r.from,"account/from"),i=Pt(t.destination??t.to??r.to,"destination/to"),a=String(nr(t.prepareHash,"prepareHash")).toLowerCase();if(!ip.test(a))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let u=t.route??t.venue;if(u==null)throw new TypeError("sign-time review: route/venue required");let s=t.decodedCalldata??t.decodedAction;if(s==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let c=String(nr(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!op.test(c))throw new TypeError("sign-time review: calldata/data must be even-length hex");let d=t.policyChecks!==void 0&&t.policyChecks!==null,l=lp(d?t.policyChecks:[]),m=dp(t.simulation),f=fp(t.assetDeltas),p=pp(t.approvalDeltas),w=t.allowlistHits??[];if(!Array.isArray(w))throw new TypeError("sign-time review: allowlistHits must be an array");let g=m?.willRevert===!0||["failed","error"].includes(m?.status),h=m!=null&&m.willRevert===!1&&["ok","success"].includes(m.status),y=g||l.failed>0?"BLOCKED":h&&d&&l.checks.length>0&&f!=null?"READY":"UNKNOWN",b=typeof s=="string"?s:s.method??s.action??s.type??"transaction",S=`${y}: review ${b} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${f?.length??0} asset delta${f?.length===1?"":"s"}; local signature required`,A={reviewVersion:1,status:y,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:u,venue:t.venue??(typeof u=="string"?u:u.venue??u.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:Pt(t.spender,"spender")},prepareHash:a,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:c,data:c,selector:c.length>=10?c.slice(0,10):null,value:Fe(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:Fe(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:Fe(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:l,allowlistHits:w,assetDeltas:f,approvalDeltas:p,summary:S};return os(A)}import{readFileSync as mp,readdirSync as wp,existsSync as cs}from"node:fs";import{dirname as hp,join as Bt}from"node:path";import{fileURLToPath as gp}from"node:url";var or=hp(gp(import.meta.url));function yp(){let e=[Bt(or,"descriptors"),Bt(or,"clear-sign","descriptors"),Bt(or,"..","clear-sign","descriptors"),Bt(or,"..","..","clear-sign","descriptors"),Bt(or,"..","..","..","clear-sign","descriptors")];for(let t of e)if(cs(t))return t;return e[0]}var bp=yp(),Ep=/^0x[0-9a-f]{8}/,xp=/^0x[0-9a-fA-F]{40}$/;function Sp(e=bp){if(!cs(e))return[];let t=[];for(let r of wp(e).filter(n=>n.endsWith(".json")).sort()){let n=mp(Bt(e,r),"utf8"),o;try{o=JSON.parse(n)}catch(i){throw new Error(`clear-sign descriptor ${r} is not valid JSON: ${i.message}`)}t.push({file:r,doc:o})}return t}function Ap(e,{to:t=null,chainId:r=null}={},n=Sp()){let o=String(e||"").toLowerCase(),i=Ep.test(o)?o.slice(0,10):null;if(!i)return null;let a=t&&xp.test(String(t))?String(t).toLowerCase():null;for(let{file:u,doc:s}of n){let c=s?.display?.formats||{};for(let[d,l]of Object.entries(c)){if(String(l?.$selector||"").toLowerCase()!==i)continue;let m=s?.context?.contract?.deployments||[],f=m.length===0,p=m.some(w=>(r==null||Number(w.chainId)===Number(r))&&a&&String(w.address||"").toLowerCase()===a);if(f||p)return{file:u,signature:d,format:l,doc:s,selector:i,generic:f}}}return null}function us(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function vp(e,t){let r=us(e,t);return r?`0x${r.slice(24)}`:null}function as(e,t){let r=us(e,t);return r?BigInt(`0x${r}`).toString():null}var Ip=(1n<<256n)-1n;function ss(e){if(e==null)return"unknown";let t=BigInt(e);return t>=Ip/2n?"UNLIMITED":t.toString()}function ls(e,{to:t=null,chainId:r=null}={},n=void 0){let o=Ap(e,{to:t,chainId:r},n);if(!o)return null;let i=String(e||"").toLowerCase(),a=i.slice(10),u=[],s=[];for(let c of o.format.fields||[]){if(c.visible==="never")continue;let d=c.$wordIndex,l=null;Number.isInteger(d)&&(l=c.format==="addressName"||c.format==="raw-address"?vp(a,d):c.format==="amount"||c.format==="tokenAmount"?ss(as(a,d)):as(a,d)),l!=null&&(s.push({label:c.label,value:l}),u.push(`${c.label}: ${l}`))}if(oe(i)){let c=null,d=null;try{c=Re(i)}catch(l){let m=String(l?.message||l);if(/unlimited approvals are refused/i.test(m))d="ORACLE POLICY: unlimited approval \u2014 Oracle refuses to prepare this; bound the amount";else return{ok:!1,refused:`descriptor matched but reviewed decoder refused: ${m}`,intent:o.format.intent}}if(c){let l=s.find(p=>/spender/i.test(p.label))?.value?.toLowerCase();if(l&&c.spender&&l!==c.spender.toLowerCase())return{ok:!1,refused:"descriptor spender disagrees with reviewed decoder",intent:o.format.intent};let m=s.find(p=>/amount|allowance/i.test(p.label))?.value,f=ss(c.amount);if(m!=null&&c.amount!=null&&String(m)!==f)return{ok:!1,refused:"descriptor amount disagrees with reviewed decoder",intent:o.format.intent}}return d&&u.push(d),{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:s,lines:u,...d?{policyNote:d}:{}}}return{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:s,lines:u}}var kp=/^0x[0-9a-f]{40}$/;function ir(e){let t=String(e??"").toLowerCase();return kp.test(t)?t:null}function Op(e,{token:t,owner:r}){if(!oe(e))return[];let n;try{n=Re(e)}catch{return[]}let o={token:ir(n.token??t),spender:ir(n.spender),owner:ir(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Tp(e,t,r={}){let n=e?.version===1&&e?.surface?e:null,o=n?.surface||"evm";if(o!=="evm"&&o!=="evm-nft")return null;let i=n?.artifact||e||{},a=ir(n?.owner??i.from),u=ir(i.to??n?.destination),s=String(i.data??"0x").toLowerCase();if(!a||!u)return null;let c=[],d=r?.destinationAllowlist;if(Array.isArray(d)&&d.length){let l=d.map(m=>String(m).toLowerCase()).includes(u);c.push({name:"destination-allowlist",passed:l,reason:l?"destination is allowlisted":"destination is not on the allowlist"})}try{return is({chainId:i.chainId,account:a,destination:u,calldata:s,value:i.value??0,prepareHash:t,route:n?.provider??n?.venue??o,decodedAction:n?.action??"transaction",...i.gasLimit==null?{}:{gasLimit:i.gasLimit},...c.length?{policyChecks:c}:{},approvalDeltas:Op(s,{token:u,owner:a})})}catch{return null}}function ds(e,t,r={}){let n=Tp(e,t,r);if(!n)return[];let o=[`REVIEW status=${n.status} action=${n.decodedAction??"transaction"} selector=${n.selector??"none"}`,`REVIEW route=${typeof n.route=="string"?n.route:n.venue??"n/a"} value=${n.value} signing=local custody=${n.custody}`];n.policyChecks.checks.length&&o.push(`REVIEW policy passed=${n.policyChecks.passed} failed=${n.policyChecks.failed}${n.policyChecks.failed?` reasons=${n.policyChecks.reasons.join("; ")}`:""}`);for(let i of n.approvalDeltas)o.push(`REVIEW APPROVAL token=${i.token} spender=${i.spender} amount=${i.amount} revokeLike=${i.revokeLike}`);n.assetDeltas==null&&o.push("REVIEW assetDeltas=unavailable (no simulated balance change supplied)"),n.status!=="READY"&&o.push("REVIEW status is not READY: these facts are decoded, not proven safe.");try{let i=e?.artifact||e||{},a=ls(String(i.data??"0x"),{to:i.to??null,chainId:i.chainId??null});if(a?.ok){o.push(`CLEAR-SIGN intent=${a.intent} [${a.descriptor}]`);for(let u of a.lines)o.push(`CLEAR-SIGN ${u}`)}else a&&a.refused&&o.push(`CLEAR-SIGN REFUSED: ${a.refused}`)}catch{}return o}import{Wallet as oo}from"ethers";import{base58 as io}from"@scure/base";import{ed25519 as hs}from"@noble/curves/ed25519.js";import{NETWORK as gs,TEST_NETWORK as ys,WIF as Np,p2wpkh as fs}from"@scure/btc-signer";import{pubECDSA as Cp}from"@scure/btc-signer/utils.js";var Vr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},_p=e=>{let t=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return null;let r=Buffer.from(t,"base64");return r.toString("base64")===t?r:null},ps=e=>{let t=String(e||"").trim();try{let r=Buffer.from(io.decode(t));return io.encode(r)===t?r:null}catch{return null}},ao=e=>{if(!(e instanceof Uint8Array))throw new Error("sol: key bytes required");if(e.length!==32&&e.length!==64)throw new Error("sol: expected 32-byte private key material");let t=Buffer.from(e.subarray(0,32));if(e.length===64){let r=Buffer.from(e.subarray(32,64)),n=Buffer.from(hs.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},ms=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),je=(e,t)=>{if(t==="sol")return ao(e);if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)},Lp=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return je(r,t)};function so(e,t){let r=String(t||"").trim();if(e==="evm")return new oo(r).privateKey;if(e==="btc")for(let i of[gs,ys])try{return Buffer.from(Np(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let c=Vr(r.slice(4));if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}if(/^base58:/i.test(r)){let c=ps(r.slice(7));if(!ms(c))throw new Error("sol: invalid explicit base58 private key");return ao(c)}if(/^0x/i.test(r)){let c=Vr(r);if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}let i=Vr(r),a=i&&(i.length===32||i.length===64)?je(i,"sol"):null,u=ps(r),s=ms(u);if(a&&s&&!a.equals(s))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(s)return ao(u);if(i)return je(i,"sol")}let n=Vr(r);if(n)return e==="evm"?new oo(`0x${n.toString("hex")}`).privateKey:je(n,e);let o=_p(r);if(o)return je(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Lp(i,e);let a=i.privateKey??i.secretKey??i.key;if(a)return so(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function ws(e,t){if(e==="evm"){let r=new oo(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=je(t,"btc"),n=Cp(r);return{kind:e,secret:r.toString("hex"),addresses:[fs(n,gs).address,fs(n,ys).address]}}if(e==="sol"){let r=je(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[io.encode(hs.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function bs(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:ws(t.kind||"evm",so(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=ws(i,so(i,n[i])));if(n.cex!==void 0){if(!n.cex||typeof n.cex!="object"||Array.isArray(n.cex))throw new Error("local-vault: cex credential records invalid");o.cex={};for(let[i,a]of Object.entries(n.cex)){if(!/^[A-Za-z0-9._-]{1,64}$/.test(i)||!a||typeof a!="object")throw new Error("local-vault: cex credential record invalid");if(!/^(?:binance|bybit|okx|coinbase)$/.test(a.venue)||!/^[A-Za-z0-9._-]{1,64}$/.test(a.accountId||""))throw new Error("local-vault: cex credential binding invalid");let u=(c,d=!0)=>{let l=a[c];if(!(!d&&l===void 0)){if(!Array.isArray(l)||l.length<4||l.some(m=>!Number.isInteger(m)||m<0||m>255))throw new Error("local-vault: cex credential bytes invalid");return Buffer.from(l)}},s=a.apiSecretEncoding;if(s!==(a.venue==="coinbase"?"base64":"raw"))throw new Error("local-vault: explicit cex secret encoding refused");o.cex[i]=Object.freeze({venue:a.venue,accountId:a.accountId,apiKeyBytes:u("apiKeyBytes"),apiSecretBytes:u("apiSecretBytes"),apiSecretEncoding:s,passphraseBytes:u("passphraseBytes",!1)})}if(!Object.keys(o.cex).length)throw new Error("local-vault: empty cex credential records refused");Object.freeze(o.cex)}if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function co(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Rp=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),$p=Object.freeze(["binance","bybit","okx","coinbase"]),Pp=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Bp=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Dp=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),g0=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),Fp=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),y0=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),b0=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),E0=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),x0=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function uo(e,t){let r=String(e??"");if(!/^\d+$/.test(r))throw new Error(`cex-policy: ${t} must be an integer string`);return BigInt(r)}function le(e,t,r){let n=String(e??"");if(!r.test(n))throw new Error(`cex-policy: bounded ${t} required`);return n}function Es(e,t){let r=String(e??"");if(!/^(?:0|[1-9]\d{0,29})(?:\.\d{1,18})?$/.test(r))throw new Error(`cex-policy: positive decimal ${t} required`);let[n,o=""]=r.split("."),i=BigInt(`${n}${o}`);if(i<=0n)throw new Error(`cex-policy: positive decimal ${t} required`);return{text:r,numerator:i,scale:o.length}}function jp(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function qp(e){return new Date(e).toISOString().slice(0,10)}function Mp(e,t){let r=le(e.credentialRef,"credentialRef",/^[A-Za-z0-9._-]{1,64}$/),n=t.cexAccounts?.[r];if(!n||typeof n!="object")throw new Error("cex-policy: sealed account policy required");return{credentialRef:r,account:n}}function Jr(e={},t={},r=Date.now()){for(let C of Object.keys(e)){let z=C.toLowerCase();if(Fp.some(W=>W.toLowerCase()===z))throw new Error(`cex-policy: envelope field ${C} forbidden`);if(!Dp.includes(C))throw new Error(`cex-policy: envelope field ${C} not in allowlist`)}if(e.version!==1)throw new Error("cex-policy: version 1 required");if(e.surface!=="cex")throw new Error("cex-policy: surface cex required");let n=String(e.kind||"");if(!Rp.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=le(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!$p.includes(o)||!Pp[o]||!Bp[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:a}=Mp(e,t);if(!Array.isArray(a.venues)||!a.venues.includes(o))throw new Error(`cex-policy: venue ${o} not allowlisted`);let u=le(e.symbol,"symbol",/^[A-Z0-9._/-]{1,32}$/);if(!Array.isArray(a.symbols)||!a.symbols.includes(u))throw new Error(`cex-policy: symbol ${u} not allowlisted`);let s=le(e.quote,"quote",/^[A-Z0-9._-]{1,24}$/);if(!a.symbolQuotes||typeof a.symbolQuotes!="object"||a.symbolQuotes[u]!==s)throw new Error("cex-policy: quote does not match sealed symbol policy");let c=le(a.accountId,"accountId",/^[A-Za-z0-9._-]{1,64}$/);if(!Array.isArray(a.allowedOperations)||!a.allowedOperations.includes(n))throw new Error("cex-policy: operation not in sealed allowlist");let d=le(e.base,"base",/^[A-Z0-9._-]{1,24}$/);if(a.base!==d||a.quote!==s)throw new Error("cex-policy: base/quote do not match sealed account policy");if(a.credentialRecordRef!==i)throw new Error("cex-policy: credential record reference mismatch");let l=a.filters?.[u];if(!l||typeof l.tickSize!="string"||typeof l.stepSize!="string"||typeof l.minNotional!="string")throw new Error("cex-policy: sealed symbol filters required");le(e.nonce,"nonce",/^[A-Za-z0-9._:-]{1,128}$/),le(e.grantId,"grantId",/^[A-Za-z0-9._:-]{1,128}$/),le(e.artifactHash,"artifactHash",/^[A-Za-z0-9._:-]{1,128}$/);let m=e.clientOrderId===void 0?void 0:le(e.clientOrderId,"clientOrderId",/^[A-Za-z0-9._-]{1,64}$/),f,p,w,g,h=0n,y=0n,b;if(n==="spot-limit-create"){if(f=le(e.side,"side",/^(?:buy|sell)$/),p=le(e.timeInForce,"timeInForce",/^GTC$/),w=Es(e.baseSize,"baseSize"),g=Es(e.limitPrice,"limitPrice"),!m)throw new Error("cex-policy: clientOrderId required");if(h=uo(e.maxQuoteNotional,"maxQuoteNotional"),y=jp(w,g),h<y)throw new Error("cex-policy: maxQuoteNotional understates baseSize times limitPrice")}else{for(let C of["side","baseSize","limitPrice","maxQuoteNotional","timeInForce"])if(e[C]!==void 0)throw new Error(`cex-policy: ${C} forbidden for cancel/status`);if(b=e.venueOrderId===void 0?void 0:le(e.venueOrderId,"venueOrderId",/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/),!b&&!m)throw new Error("cex-policy: exact prior order id required")}let S=uo(a.perOrderQuoteCap,"sealed perOrderQuoteCap"),A=uo(a.dailyGrossQuoteCap,"sealed dailyGrossQuoteCap");if(h>S)throw new Error("cex-policy: maxQuoteNotional exceeds sealed perOrderQuoteCap");if(h>A)throw new Error("cex-policy: maxQuoteNotional exceeds sealed dailyGrossQuoteCap");let k=Number(e.expiresAtMs);if(!Number.isSafeInteger(k)||k<=r||k-r>12e4)throw new Error("cex-policy: bounded expiry required");let v=`cex:${i}:${o}:${c}:${m||b}`,_=`cex:${i}:${c}:${o}:${s}:${qp(r)}`;return Object.freeze({kind:n,venue:o,symbol:u,base:d,quote:s,side:f,timeInForce:p,baseSize:w?.text,limitPrice:g?.text,clientOrderId:m,venueOrderId:b,filter:Object.freeze({...l}),accountId:c,credentialRef:i,tradeId:v,unit:_,notional:h.toString(),impliedNotional:y.toString()})}function xs({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Wr(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Jr(e,n,r);return rr({file:t.ledger,keyFile:t.policyKey,anchorFile:t.ledgerAnchor,policyAnchorFile:t.policyAnchor,tradeId:o.tradeId,unit:o.unit,value:o.notional,notional:o.notional,policy:n,nowMs:r})}import J from"node:fs";import dt from"node:path";import{createHmac as Hp,randomBytes as zp,timingSafeEqual as Wp}from"node:crypto";var Kr=(e,t)=>Hp("sha256",e).update(JSON.stringify(t)).digest("hex"),Ss=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Wp(r,n)},As=e=>Buffer.from(R(e));function vs({file:e,keyFile:t,anchorFile:r}){if(!e||!t||!r)throw new Error("cex-state: protected paths required");if(dt.dirname(dt.resolve(e))===dt.dirname(dt.resolve(r)))throw new Error("cex-state: external rollback anchor required");let n=`${e}.lock`,o=(()=>{try{return J.readFileSync(`/proc/${process.pid}/stat`,"utf8").trim().split(/\s+/)[21]}catch{return null}})(),i=d=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,d),a=d=>{if(!Number.isSafeInteger(d.pid)||d.pid<1||typeof d.processStart!="string"||!d.processStart)return null;try{process.kill(d.pid,0)}catch(l){return l?.code==="ESRCH"?!1:null}try{return J.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{J.mkdirSync(dt.dirname(n),{recursive:!0,mode:448});let l=zp(16).toString("hex"),m=Date.now()+5e3,f=`${n}.${process.pid}.${l}.tmp`,p=JSON.stringify({version:1,pid:process.pid,processStart:o,token:l,createdAtMs:Date.now()})+`
16
16
  `;for(;;)try{let w=J.openSync(f,"wx",384);try{J.writeFileSync(w,p),J.fsyncSync(w)}finally{J.closeSync(w)}try{J.linkSync(f,n)}finally{J.unlinkSync(f)}break}catch(w){try{J.existsSync(f)&&J.unlinkSync(f)}catch{}if(w?.code!=="EEXIST")throw new Error("cex-state: lock refused");let g;try{g=J.readFileSync(n,"utf8")}catch(b){if(b?.code==="ENOENT")continue;throw new Error("cex-state: corrupt lock refused")}let h;try{h=JSON.parse(g)}catch{throw new Error("cex-state: corrupt lock refused")}if(h?.version!==1||!/^[0-9a-f]{32}$/.test(h.token||"")||!Number.isSafeInteger(h.createdAtMs))throw new Error("cex-state: corrupt lock refused");if(a(h)===!1&&Date.now()-h.createdAtMs>3e4){try{J.unlinkSync(n)}catch{throw new Error("cex-state: stale lock recovery refused")}continue}if(Date.now()>=m)throw new Error("cex-state: lock busy");i(10)}try{return d()}finally{let w;try{w=JSON.parse(J.readFileSync(n,"utf8"))}catch{throw new Error("cex-state: lock ownership lost")}if(w.token!==l||w.pid!==process.pid||w.processStart!==o)throw new Error("cex-state: lock ownership lost");J.unlinkSync(n)}},s=()=>{let d=As(t);try{if(!J.existsSync(e)){if(J.existsSync(r))throw new Error("cex-state: rollback detected");return{version:1,sequence:0,orders:[]}}let l=JSON.parse(R(e));if(!Ss(l.mac,Kr(d,l.state)))throw new Error("cex-state: integrity failed");let m=JSON.parse(R(r));if(!Ss(m.mac,Kr(d,m.marker))||m.marker.sequence!==l.state.sequence||m.marker.stateMac!==l.mac)throw new Error("cex-state: rollback detected");return l.state}finally{d.fill(0)}},c=d=>{let l=As(t);try{let m={...d,sequence:d.sequence+1},f=Kr(l,m),p={version:1,sequence:m.sequence,stateMac:f};return J.mkdirSync(dt.dirname(e),{recursive:!0,mode:448}),J.mkdirSync(dt.dirname(r),{recursive:!0,mode:448}),Ae(r,JSON.stringify({marker:p,mac:Kr(l,p)})+`
17
17
  `),Ae(e,JSON.stringify({state:m,mac:f})+`
18
18
  `),m}finally{l.fill(0)}};return Object.freeze({getByTradeId(d){return u(()=>s().orders.find(l=>l.tradeId===d)||null)},prepare(d){return u(()=>{let l=s(),m=l.orders.find(p=>p.tradeId===d.tradeId||p.requestDigest===d.requestDigest);if(m)throw new Error(`cex-state: ${m.state} order requires status reconciliation; create not resent`);let f={...d,state:"prepared",preparedAtMs:d.nowMs};return c({...l,orders:[...l.orders,f]}),Object.freeze(f)})},transition(d,l,m,f={}){return u(()=>{let p=s(),w=p.orders.findIndex(h=>h.tradeId===d);if(w<0)throw new Error("cex-state: durable prior order required");if(![].concat(l).includes(p.orders[w].state))throw new Error(`cex-state: ${p.orders[w].state} status requires reconciliation`);let g={...p.orders[w],...f,state:m};return p.orders[w]=g,c(p),Object.freeze(g)})},requirePrior({venue:d,accountId:l,credentialRef:m,symbol:f,venueOrderId:p}){return u(()=>{let w=s().orders.find(g=>g.venue===d&&g.accountId===l&&g.credentialRef===m&&g.symbol===f&&g.venueOrderId===p);if(!w)throw new Error("cex-state: exact durable prior order required");return Object.freeze(w)})}})}import{createHash as tm}from"node:crypto";import{createHash as Up}from"node:crypto";var po=Object.freeze({binance:Object.freeze({create:["POST","/api/v3/order"],cancel:["DELETE","/api/v3/order"],status:["GET","/api/v3/order"]}),bybit:Object.freeze({create:["POST","/v5/order/create"],cancel:["POST","/v5/order/cancel"],status:["GET","/v5/order/realtime"]}),okx:Object.freeze({create:["POST","/api/v5/trade/order"],cancel:["POST","/api/v5/trade/cancel-order"],status:["GET","/api/v5/trade/order"]}),coinbase:Object.freeze({create:["POST","/orders"],cancel:["DELETE","/orders/{order_id}"],status:["GET","/orders/{order_id}"]})}),ar=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Vp=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,Jp=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/,Is=(e,t)=>{let r=String(e??"");if(!Vp.test(r))throw new Error(`cex: ${t} must be a decimal string`);let[n,o=""]=r.split(".");return{text:r,integer:BigInt(n+o),scale:o.length}};var lo=(e,t)=>{let r=String(e??"");if(!Jp.test(r))throw new Error(`cex: bounded ${t} required`);return r},fo=e=>{if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(fo).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${fo(e[t])}`).join(",")}}`;throw new Error("cex: non-canonical request fact refused")};function Kp(e){if(!e||!["create","cancel","status"].includes(e.operation))throw new Error("cex: operation refused");if(!/^[A-Z0-9._/-]{1,32}$/.test(String(e.symbol||"")))throw new Error("cex: symbol required");if(e.operation==="create"){if(!/^(?:buy|sell)$/.test(e.side)||e.timeInForce!==void 0&&e.timeInForce!=="GTC")throw new Error("cex: LIMIT GTC spot order required");Is(e.baseSize,"baseSize"),Is(e.limitPrice,"limitPrice"),lo(e.clientOrderId,"clientOrderId")}else lo(e.venueOrderId,"venueOrderId");return e}function Gp(e,t){let r=t.side==="buy"?"BUY":"SELL";if(e==="binance")return t.operation==="create"?{params:{symbol:t.symbol,side:r,type:"LIMIT",timeInForce:"GTC",quantity:t.baseSize,price:t.limitPrice,newClientOrderId:t.clientOrderId}}:{params:{symbol:t.symbol,orderId:t.venueOrderId}};if(e==="bybit"){let n=t.operation==="create"?{category:"spot",symbol:t.symbol,side:r==="BUY"?"Buy":"Sell",orderType:"Limit",qty:t.baseSize,price:t.limitPrice,timeInForce:"GTC",orderLinkId:t.clientOrderId,isLeverage:0}:{category:"spot",symbol:t.symbol,orderId:t.venueOrderId};return t.operation==="status"?{params:n}:{body:n}}if(e==="okx"){let n=t.operation==="create"?{instId:t.symbol,tdMode:"cash",clOrdId:t.clientOrderId,side:t.side,ordType:"limit",sz:t.baseSize,px:t.limitPrice}:{instId:t.symbol,ordId:t.venueOrderId};return t.operation==="status"?{params:n}:{body:n}}if(e==="coinbase")return{body:t.operation==="create"?{type:"limit",side:t.side,product_id:t.symbol,size:t.baseSize,price:t.limitPrice,time_in_force:"GTC",client_oid:t.clientOrderId}:void 0};throw new Error("cex: venue refused")}function ks({venue:e,order:t,timestamp:r,recvWindow:n=5e3}){Kp(t);let o=po[e]?.[t.operation];if(!o)throw new Error("cex: venue or operation refused");if(!Number.isSafeInteger(n)||n<1||n>5e3)throw new Error("cex: recvWindow refused");let i=String(r??"");if(!(e==="okx"?/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(i):e==="coinbase"?/^\d{10}(?:\.\d{1,3})?$/.test(i):/^\d{13}$/.test(i)))throw new Error("cex: timestamp refused");let[a,u]=o;u.includes("{order_id}")&&(u=u.replace("{order_id}",encodeURIComponent(lo(t.venueOrderId,"venueOrderId"))));let s={venue:e,operation:t.operation,method:a,path:u,timestamp:i,recvWindow:n,...Gp(e,t)};return Object.freeze({...s,params:s.params&&Object.freeze(s.params),body:s.body&&Object.freeze(s.body),requestDigest:Up("sha256").update(fo(s)).digest("hex")})}import{createHmac as Yp}from"node:crypto";var Gr=(e,t,r="hex")=>Yp("sha256",e).update(t).digest(r),Os=e=>new URLSearchParams(Object.entries(e||{})).toString(),Xp=e=>e===void 0?"":JSON.stringify(e),mo=(e,t)=>{if(!(Array.isArray(e)||e instanceof Uint8Array)||e.length<4||[...e].some(r=>!Number.isInteger(r)||r<0||r>255))throw new Error(`cex: invalid ${t}`);return Buffer.from(e)};function Zp(e,t){let r=mo(e.apiSecretBytes,"credential"),n=t==="coinbase"?"base64":"raw";if(e.apiSecretEncoding!==n)throw r.fill(0),new Error("cex: explicit secret encoding refused");if(n==="raw")return r;try{let o=r.toString("ascii");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o))throw new Error("base64");let i=Buffer.from(o,"base64");if(i.length<4||i.toString("base64")!==o)throw i.fill(0),new Error("base64");return i}finally{r.fill(0)}}var ft=e=>Buffer.from(e).toString("utf8");function Ts(e,t){if(t?.venue!==e.venue)throw new Error("cex: credential venue mismatch");let r=mo(t.apiKeyBytes,"credential"),n=Zp(t,e.venue),o=t.passphraseBytes?mo(t.passphraseBytes,"credential"):null;try{let i={accept:"application/json"},a=Xp(e.body);a&&(i["content-type"]="application/json");let u=Os(e.params),s=e.path;if(e.venue==="binance"){let c=Os({...e.params,timestamp:e.timestamp,recvWindow:String(e.recvWindow)});u=`${c}&signature=${Gr(n,c)}`,i["X-MBX-APIKEY"]=ft(r)}else if(e.venue==="bybit"){let c=e.method==="GET"?u:a;Object.assign(i,{"X-BAPI-API-KEY":ft(r),"X-BAPI-TIMESTAMP":e.timestamp,"X-BAPI-RECV-WINDOW":String(e.recvWindow),"X-BAPI-SIGN":Gr(n,e.timestamp+ft(r)+e.recvWindow+c)})}else if(e.venue==="okx"){let c=s+(u?`?${u}`:"");Object.assign(i,{"OK-ACCESS-KEY":ft(r),"OK-ACCESS-SIGN":Gr(n,e.timestamp+e.method+c+a,"base64"),"OK-ACCESS-TIMESTAMP":e.timestamp,"OK-ACCESS-PASSPHRASE":ft(o||Buffer.alloc(0))})}else Object.assign(i,{"CB-ACCESS-KEY":ft(r),"CB-ACCESS-SIGN":Gr(n,e.timestamp+e.method+s+a,"base64"),"CB-ACCESS-TIMESTAMP":e.timestamp,"CB-ACCESS-PASSPHRASE":ft(o||Buffer.alloc(0))});return{url:ar[e.venue]+s+(u?`?${u}`:""),method:e.method,headers:i,body:a||void 0}}finally{r.fill(0),n.fill(0),o?.fill(0)}}var Ns=256*1024,Qp=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/;function em(e,t,r){if(!t.includes("{order_id}"))return r===t;let[n,o]=t.split("{order_id}");if(!r.startsWith(n)||!r.endsWith(o))return!1;let i=r.slice(n.length,r.length-o.length||void 0),a;try{a=decodeURIComponent(i)}catch{return!1}if(!Qp.test(a)||encodeURIComponent(a)!==i)return!1;try{return new URL(r,e).pathname===r&&r===`${n}${i}${o}`}catch{return!1}}async function wo(e,t){let r=po[e.venue]?.[e.operation],n=ar[e.venue];if(!r||!n||r[0]!==e.method||!em(n,r[1],e.path))throw new Error("cex transport refused");let o=Ts(e,t),i=new AbortController,a=setTimeout(()=>i.abort(),5e3);try{let u=await fetch(o.url,{method:o.method,headers:o.headers,body:o.body,redirect:"manual",signal:i.signal});if(u.status<200||u.status>=300)throw new Error("http status");if(u.status>=300&&u.status<400)throw new Error("redirect");let s=new URL(u.url||o.url),c=new URL(ar[e.venue]);if(s.origin!==c.origin)throw new Error("origin");if(!String(u.headers.get("content-type")||"").toLowerCase().startsWith("application/json"))throw new Error("content type");let d=Number(u.headers.get("content-length"));if(Number.isFinite(d)&&d>Ns)throw new Error("size");let l=new Uint8Array(await u.arrayBuffer());if(l.length>Ns)throw new Error("size");let m;try{m=JSON.parse(new TextDecoder().decode(l))}catch{throw new Error("json")}return{statusCode:u.status,value:m,responseBodyBytes:l}}catch{throw new Error("cex transport refused")}finally{clearTimeout(a);for(let u of Object.values(o.headers));o.headers=null,o.body=void 0}}var rm=e=>tm("sha256").update(e).digest("hex"),nm=(e,t)=>e==="okx"?new Date(t).toISOString():String(e==="coinbase"?t/1e3:t),ho=e=>/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/.test(String(e||""))?String(e):null,sr=e=>typeof e=="string"&&/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e)?e:null;var Cs=e=>/^0(?:\.0+)?$/.test(String(e));function om(e,t){if(!sr(e)||!sr(t))throw new Error("cex authoritative decimal refused");let[r,n=""]=e.split("."),[o,i=""]=t.split("."),a=n.length+i.length,u=BigInt(r+n)*BigInt(o+i);if(!a)return u.toString();let s=u.toString().padStart(a+1,"0");return`${s.slice(0,-a)}.${s.slice(-a)}`}function im(e,t,r){let n,o,i;return e==="binance"&&t?.code===void 0?(n=t?.orderId,o=t?.symbol,i=t?.clientOrderId):e==="bybit"&&t?.retCode===0?(n=t?.result?.orderId,o=t?.result?.symbol,i=t?.result?.orderLinkId):e==="okx"&&t?.code==="0"&&t?.data?.length===1&&t.data[0]?.sCode==="0"?(n=t.data[0].ordId,o=t.data[0].instId,i=t.data[0].clOrdId):e==="coinbase"&&!t?.message&&(n=t?.id,o=t?.product_id,i=t?.client_oid),o!==void 0&&o!==r.symbol||i!==void 0&&i!==r.clientOrderId?null:ho(n)}function am(e,t,r){let n=null;return e==="binance"&&t&&typeof t=="object"&&t.code===void 0?n=t.orderId:e==="bybit"&&t?.retCode===0?n=t?.result?.orderId:e==="okx"&&t?.code==="0"&&t?.data?.length===1&&t.data[0]?.sCode==="0"?n=t.data[0].ordId:e==="coinbase"&&typeof t=="string"&&(n=t),ho(n)===r.venueOrderId}function sm(e,t,r){let n=t,o,i,a,u,s;if(e==="binance"?(o=t?.orderId,i=t?.clientOrderId,a=t?.symbol,u={CANCELED:"cancelled",REJECTED:"rejected",FILLED:"filled",PARTIALLY_FILLED:"partial",NEW:"open",PENDING_CANCEL:"open"}[t?.status],s=t?.cummulativeQuoteQty):e==="bybit"&&t?.retCode===0&&t?.result?.list?.length===1?(n=t.result.list[0],o=n.orderId,i=n.orderLinkId,a=n.symbol,u={Cancelled:"cancelled",Rejected:"rejected",Filled:"filled",PartiallyFilled:"partial",New:"open"}[n.orderStatus],s=n.cumExecValue):e==="okx"&&t?.code==="0"&&t?.data?.length===1?(n=t.data[0],o=n.ordId,i=n.clOrdId,a=n.instId,u={canceled:"cancelled",filled:"filled",partially_filled:"partial",live:"open"}[n.state],sr(n.accFillSz)&&sr(n.avgPx)&&(Cs(n.accFillSz)||!Cs(n.avgPx))&&(s=om(n.accFillSz,n.avgPx))):e==="coinbase"&&(o=t?.id,i=t?.client_oid,a=t?.product_id,u=t?.status==="done"?t?.done_reason==="canceled"?"cancelled":"filled":{rejected:"rejected",open:"open",pending:"open",active:"open"}[t?.status],s=t?.executed_value),ho(o)!==r.venueOrderId||String(a||"")!==r.symbol||r.clientOrderId&&String(i||"")!==r.clientOrderId||!u||!sr(s))throw new Error("cex authoritative status identity refused");return{status:u,filledQuote:s}}async function cm(e,t){let r=t?.nowMs?.()??Date.now(),n=t?.transport||wo,o=t.credential(e.credentialRef);if(!o||o.accountId!==e.accountId||o.venue!==e.venue)throw new Error("cex: credential binding refused");let i=e.order.operation!=="create"?e.store.requirePrior({...e,...e.order}):null,a=i?.tradeId||e.tradeId,u=ks({venue:e.venue,order:e.order,timestamp:nm(e.venue,r),recvWindow:5e3}),s;e.order.operation==="create"?s=e.store.prepare({tradeId:e.tradeId,venue:e.venue,accountId:e.accountId,credentialRef:e.credentialRef,symbol:e.order.symbol,clientOrderId:e.order.clientOrderId,reservedNotional:e.reservedNotional,requestDigest:u.requestDigest,nowMs:r}):s=e.store.transition(a,["open","uncertain","sent","cancel-pending","settlement-pending"],"prepared",{operation:e.order.operation,requestDigest:u.requestDigest,nowMs:r}),e.store.transition(a,"prepared","sent",{sentAtMs:r});let c;try{c=await n(u,o)}catch{throw e.store.transition(a,"sent","uncertain",{uncertainAtMs:r}),new Error("cex transport refused; order is uncertain and requires status reconciliation")}let d=rm(c.responseBodyBytes);if(e.order.operation==="create"){let f=im(e.venue,c.value,e.order);if(!f)throw e.store.transition(a,"sent","uncertain",{responseDigest:d}),new Error("cex response refused; order is uncertain and requires status reconciliation");return e.store.transition(a,"sent","open",{venueOrderId:f,responseDigest:d,openedAtMs:r})}if(e.order.operation==="cancel")return e.store.transition(a,"sent",am(e.venue,c.value,i)?"cancel-pending":"uncertain",{responseDigest:d,observedAtMs:r});let l;try{l=sm(e.venue,c.value,i)}catch{return e.store.transition(a,"sent","uncertain",{responseDigest:d,observedAtMs:r})}let m=["cancelled","rejected","filled"].includes(l.status);if(m||l.status==="partial"){e.store.transition(a,"sent","settlement-pending",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote});let f=m&&(l.status==="cancelled"||l.status==="rejected")&&/^0(?:\.0+)?$/.test(l.filledQuote)?"release":"commit";return await t.settleLedger({tradeId:i.tradeId,filledQuote:l.filledQuote,disposition:f}),e.store.transition(a,"settlement-pending","terminal",{settledAtMs:r})}return e.store.transition(a,"sent","open",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote})}function _s(e){if(!e||typeof e.credential!="function"||typeof e.settleLedger!="function")throw new Error("cex: sealed runtime dependencies required");let t=Object.freeze({credential:e.credential,transport:e.transport||wo,nowMs:e.nowMs||Date.now,settleLedger:e.settleLedger});return Object.freeze({execute:r=>cm(r,t)})}import{createHash as um,createHmac as Ls,randomBytes as lm,timingSafeEqual as dm}from"node:crypto";var Rs="oracle-local-signer-cex-owner-allow-v1",Dt=e=>/^(?:0|[1-9]\d{0,19})$/.test(String(e||""))?String(e):null,$s=e=>JSON.stringify(e),fm=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&dm(r,n)};function Ps({keyFile:e,approvedTelegramOwners:t,nowMs:r=Date.now}={}){if(!e)throw new Error("cex owner proof: signer policy key required");let n=new Set((t||[]).map(Dt).filter(Boolean));if(!n.size)throw new Error("cex owner proof: approved owner context required");let o=new Set,i=u=>{let s=Buffer.from(R(e));try{return u(s)}finally{s.fill(0)}},a=i(u=>um("sha256").update("cex-owner-instance\0").update(u).digest("hex"));return Object.freeze({mint({digest:u,senderId:s,chatId:c,platform:d,ttlMs:l=15e3}={}){let m=Dt(s),f=Dt(c),p=r();if(d!=="telegram"||!m||f!==m||!n.has(m))throw new Error("cex owner proof: exact Telegram owner DM required");if(!/^[0-9a-f]{64}$/.test(String(u||""))||!Number.isSafeInteger(l)||l<1||l>3e4)throw new Error("cex owner proof: binding refused");let w={version:1,decision:"Allow",digest:u,ownerSenderId:m,telegramChatId:f,audience:Rs,instance:a,nonce:lm(16).toString("hex"),issuedAtMs:p,expiresAtMs:p+l},g=i(h=>Ls("sha256",h).update($s(w)).digest("hex"));return{claims:w,mac:g}},verify(u,{digest:s}={}){let c=u?.claims,d=r();if(!c||c.version!==1||c.decision!=="Allow"||c.digest!==s||c.audience!==Rs||c.instance!==a||!/^[0-9a-f]{32}$/.test(c.nonce||"")||Dt(c.ownerSenderId)!==Dt(c.telegramChatId)||!n.has(Dt(c.ownerSenderId))||!Number.isSafeInteger(c.issuedAtMs)||!Number.isSafeInteger(c.expiresAtMs)||c.expiresAtMs<=d||c.issuedAtMs>d||c.expiresAtMs-c.issuedAtMs>3e4||o.has(c.nonce))return!1;let l=i(m=>Ls("sha256",m).update($s(c)).digest("hex"));return fm(u.mac,l)?(o.add(c.nonce),!0):!1}})}var Le=new So(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Ds=new So(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),yo=new So(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function Em({isArmed:e,disarmNow:t}){if(typeof e!="function"||typeof t!="function")throw new TypeError("signer: serialized arm fence callbacks required");let r=1,n=Promise.resolve(),o=i=>{let a=n.then(i,i);return n=a.then(()=>{},()=>{}),a};return Object.freeze({armGeneration:()=>r,disarm:()=>o(()=>(r+=1,t(),!0)),broadcastWithArmFence:(i,a)=>o(async()=>{if(i!==r||!e())throw new Error("signer: disarmed generation changed before broadcast handoff");return a()})})}function xm(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||re.join(process.env.XDG_STATE_HOME||re.join(pm.homedir(),".local","state"),"oracle"),r=mm("sha256").update(re.resolve(e)).digest("hex").slice(0,16);return{vault:re.join(e,"vault.json"),policy:re.join(e,"signer-policy.json"),policyKey:re.join(e,"policy-integrity-key"),policyAnchor:re.join(t,`signer-policy-${r}.high-water`),ledger:re.join(e,"signer-ledger.json"),ledgerAnchor:re.join(t,`signer-ledger-${r}.high-water`),executionOutbox:re.join(e,"signer-execution-outbox.json"),cexOrders:re.join(e,"cex-orders.json"),cexOrdersAnchor:re.join(t,`cex-orders-${r}.high-water`),token:re.join(e,"signer-token"),lock:re.join(t,`signer-${r}.lock`),workflowLedger:re.join(e,"workflow-events.jsonl")}}function Sm(e){try{return R(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=wm(32).toString("hex");return Ae(e,t+`
19
- `),t}function NE(e,t,r){let n=String(e||"").toLowerCase();if(n!==String(t||"").toLowerCase())throw new Error("signer: wallet does not match vault metadata");if(!Array.isArray(r)||!r.some(o=>String(o).toLowerCase()===n))throw new Error("signer: wallet is not an allowed policy owner");return!0}function bo(e,t,r){if(!t)throw new Error(`signer: ${e} key is required by policy`);let n=new Set((r||[]).map(o=>String(o).toLowerCase()));if(!t.addresses.some(o=>n.has(String(o).toLowerCase())))throw new Error(`signer: ${e} vault address is not an allowed policy owner`);return!0}function Fs(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function K(e,t){return e.surfaces.includes(t)}function _e(e,t){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`signer: invalid ${t}`);return r}function js(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function Am(e,t){let r=e?.anvilQuote;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("signer: exact prepared Anvil quote is required");if(!e?.artifact?.anvilQuote||JSON.stringify(e.artifact.anvilQuote)!==JSON.stringify(r))throw new Error("signer: exact prepared Anvil quote artifact mismatch");return Object.freeze(t==="buy"?{totalCostRaw:BigInt(r.totalCostRaw).toString(),baseCostRaw:BigInt(r.baseCostRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString(),available:r.available===!0}:{netPayoutRaw:BigInt(r.netPayoutRaw).toString(),grossPayoutRaw:BigInt(r.grossPayoutRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString()})}function vm(e,t,r){if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("signer: exact prepared Anvil quote confirmation required");let n=e.artifact,o=t==="buy"?[r.totalCostRaw,e.maxPaymentTokenAmountRaw,n?.maxPaymentTokenAmountRaw,e.exactQuoteTotalCostRaw,n?.exactQuoteTotalCostRaw,e.preconditions?.confirmedTotalCostRaw]:[r.netPayoutRaw,e.minPayoutRaw,n?.minPayoutRaw,e.exactQuoteNetPayoutRaw,n?.exactQuoteNetPayoutRaw,e.preconditions?.confirmedNetPayoutRaw],i;try{i=BigInt(o[0]);for(let c of o.slice(1))if(BigInt(c)!==i)throw new Error("mismatch")}catch{throw new Error(`signer: exact Anvil ${t} settlement limit mismatch`)}let a=n?.transactions;if(!Array.isArray(a)||a.length!==1)throw new Error("signer: exact Anvil action transaction required");let u=t==="buy"?"buySpecificNFT":"sellNFT",s;try{if(s=Le.decodeFunctionData(u,a[0].data),Le.encodeFunctionData(u,[s[0],s[1]]).toLowerCase()!==String(a[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${t} calldata required`)}if(BigInt(s[0])!==BigInt(e.tokenId)||BigInt(s[1])!==i)throw new Error(`signer: exact Anvil ${t} calldata limit mismatch`);return i}async function qe(e,t,r,n,o,i=[]){let a=await e.send("eth_call",[{to:t,data:r.encodeFunctionData(n,i)},o]);return r.decodeFunctionResult(n,a)[0]}async function Im(e,t,r,{nowMs:n=Date.now(),signerAddress:o}={}){if(t?.surface!=="evm-nft"||String(t?.provider).toLowerCase()!=="anvil-nft")return null;if(!e||typeof e.send!="function")throw new Error("signer: trusted RPC cannot attest Anvil market");let i=_e(t.destination,"Anvil market"),a=_e(t.contract,"Anvil collection"),u=_e(t.paymentToken,"Anvil payment token"),s=BigInt(t.nativeSwapFeeWei),c=Number(t.paymentTokenDecimals),d=_e(o,"Anvil signer identity"),l=_e(t.owner,"Anvil envelope owner");if(d!==l)throw new Error("signer: Anvil signer identity mismatch");let m=BigInt(t.tokenId);if(m<0n)throw new Error("signer: invalid Anvil tokenId");let f=String(t.nftAction||"").toLowerCase();if(f!=="buy"&&f!=="sell")throw new Error("signer: unsupported Anvil NFT action");let p=Am(t,f),w=vm(t,f,p),g=t.anvilAttestation;if(!g||typeof g!="object"||Number(g.snapshotExpiresAtMs)<=Number(n))throw new Error("signer: fresh provider Anvil attestation required");let h=String(js(r.anvilRuntimeCodeHashes,i)||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(h)||h!==String(g.runtimeCodeHash||"").toLowerCase())throw new Error("signer: Anvil runtime is not reviewed by policy");let y=js(r.nftPaymentTokenCaps,u);if(!y||Number(y.decimals)!==c)throw new Error("signer: Anvil payment token decimals are not reviewed by policy");let b=String(await e.send("eth_chainId",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(b)||BigInt(b)!==4663n)throw new Error("signer: trusted RPC Anvil chain mismatch");let S=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(S))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let A=BigInt(S),k=await e.send("eth_getBlockByNumber",[S,!1]),v=String(k?.hash||"").toLowerCase();if(String(k?.number||"").toLowerCase()!==S||!/^0x[0-9a-f]{64}$/.test(v))throw new Error("signer: trusted RPC returned an invalid Anvil block attestation");let _=Object.freeze({blockHash:v,requireCanonical:!0}),C=String(await e.send("eth_getCode",[i,_])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(C)||C==="0x")throw new Error("signer: Anvil market runtime is empty");let z=ym(C).toLowerCase();if(z!==h)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[W,L,$]=await Promise.all([qe(e,i,Le,"collection",_),qe(e,i,Le,"token",_),qe(e,i,Le,"robinhoodSwapFeeWei",_)]),Ke=_e(W,"live Anvil collection"),pt=_e(L,"live Anvil payment token"),Ft=BigInt($).toString();if(Ke!==a)throw new Error("signer: live Anvil collection mismatch");if(pt!==u)throw new Error("signer: live Anvil payment token mismatch");if(Ft!==s.toString())throw new Error("signer: live Anvil native swap fee mismatch");let jt=Number(await qe(e,pt,Ds,"decimals",_));if(!Number.isSafeInteger(jt)||jt!==c)throw new Error("signer: live Anvil payment token decimals mismatch");let mt=_e(await qe(e,Ke,yo,"ownerOf",_,[m]),"live Anvil token owner"),Ge=null,Ye=null,Xe=null,Ze=null,q;if(f==="buy"){let[Me,wt,E]=await Promise.all([qe(e,i,Le,"inventory",_,[m]),qe(e,pt,Ds,"allowance",_,[d,i]),e.send("eth_call",[{to:i,data:Le.encodeFunctionData("quoteSpecificBuy",[m])},_])]);Ge=!!Me,Ye=BigInt(wt).toString();let I=Le.decodeFunctionResult("quoteSpecificBuy",E);if(q=Object.freeze({totalCostRaw:BigInt(I[0]).toString(),baseCostRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString(),available:!!I[4]}),JSON.stringify(q)!==JSON.stringify(p))throw new Error("signer: exact Anvil buy quote changed after preparation");if(mt!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!Ge)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt(Ye)!==BigInt(t.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(Ye)<w)throw new Error("signer: live Anvil ERC20 allowance is insufficient");if(!q.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(q.totalCostRaw)!==w)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(q.totalCostRaw)!==BigInt(q.baseCostRaw)+BigInt(q.feeRaw)+BigInt(q.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[Me,wt,E]=await Promise.all([qe(e,Ke,yo,"getApproved",_,[m]),qe(e,Ke,yo,"isApprovedForAll",_,[d,i]),e.send("eth_call",[{to:i,data:Le.encodeFunctionData("quoteSellNFT")},_])]);Xe=_e(Me,"live Anvil token approval"),Ze=!!wt;let I=Le.decodeFunctionResult("quoteSellNFT",E);if(q=Object.freeze({netPayoutRaw:BigInt(I[0]).toString(),grossPayoutRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString()}),JSON.stringify(q)!==JSON.stringify(p))throw new Error("signer: exact Anvil sell quote changed after preparation");if(mt!==d)throw new Error("signer: exact Anvil token owner does not match signer");if(Xe!==i&&!Ze)throw new Error("signer: live Anvil NFT approval is insufficient");if(Xe!==_e(t.preconditions?.approvedAddress,"prepared Anvil token approval")||Ze!==!!t.preconditions?.approvedForAll)throw new Error("signer: live Anvil NFT approval changed after preparation");if(BigInt(q.netPayoutRaw)!==w)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(q.netPayoutRaw)+BigInt(q.feeRaw)+BigInt(q.protocolFeeRaw)!==BigInt(q.grossPayoutRaw))throw new Error("signer: exact Anvil sell quote fee arithmetic mismatch")}return Object.freeze({source:"local-signer-trusted-rpc",chainId:4663,market:i,collection:Ke,paymentToken:pt,paymentTokenDecimals:jt,nativeSwapFeeWei:Ft,signerAddress:d,nftAction:f,tokenId:m.toString(),tokenOwner:mt,inventoryMember:Ge,allowanceRaw:Ye,approvedAddress:Xe,approvedForAll:Ze,quote:q,blockNumber:A.toString(),blockHash:v,runtimeCodeHash:z,verifiedAtMs:Number(n)})}function qs(e,t,r="execution"){if(!e||!t)throw new Error("signer: complete Anvil revalidation evidence required");for(let n of["runtimeCodeHash","market","collection","paymentToken","paymentTokenDecimals","nativeSwapFeeWei","signerAddress","nftAction","tokenId","tokenOwner","inventoryMember","allowanceRaw","approvedAddress","approvedForAll"])if(String(t[n]).toLowerCase()!==String(e[n]).toLowerCase())throw new Error(`signer: Anvil ${n} changed after simulation at ${r}`);if(JSON.stringify(t.quote)!==JSON.stringify(e.quote))throw new Error(`signer: Anvil quote changed after simulation at ${r}`);return!0}function km(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:a}={}){let u=gm(new URL("./anvil-attestation-worker.mjs",import.meta.url)),s={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},c;try{c=hm(process.execPath,[u],{input:JSON.stringify({rpcUrl:e,chainId:t,envelope:r,policy:s,nowMs:Number(o),signerAddress:a}),encoding:"utf8",timeout:i,maxBuffer:64e3,env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_OPTIONS:""},stdio:["pipe","pipe","pipe"]})}catch{throw new Error("signer: fresh independent Anvil attestation failed before reservation")}let d;try{d=JSON.parse(c)}catch{throw new Error("signer: invalid Anvil reservation attestation result")}if(!d||d.source!=="local-signer-trusted-rpc"||!/^0x[0-9a-f]{64}$/.test(String(d.blockHash||"")))throw new Error("signer: invalid Anvil reservation attestation result");return Object.freeze(d)}function Om(e,t,r,n=null){let o=e?.version===1&&e?.surface?e:null,i=o?.artifact||e||{},a=[`surface=${o?.surface||"evm"} action=${o?.action||"evm"}`,`chain=${i.chainId??i.network??i.cluster??"n/a"} owner=${o?.owner||i.from||"n/a"}`,`to=${i.to||o?.destination||"n/a"} calldata=${String(i.data||"0x")} value=${i.value??"n/a"}`,`gas=${i.gasLimit??"n/a"} maxFeePerGas=${i.maxFeePerGas??i.gasPrice??"n/a"} maxPriorityFeePerGas=${i.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${i.l1FeeWei??"n/a"} operatorFeeWei=${i.operatorFeeWei??"n/a"}`,`nonce=${i.nonce??"n/a"} type=${i.type??"n/a"} accessList=${Array.isArray(i.accessList)?i.accessList.length:0}`,`slippageBps=${o?.slippageBps??i.slippageBps??"n/a"} expiresAtMs=${o?.expiresAtMs??i.expiresAtMs??"n/a"}`],u=(c,d)=>{if(a.push(`LEG ${d} chain=${c.chainId??"n/a"} from=${c.from??"n/a"} to=${c.to??"n/a"}`),a.push(`LEG ${d} calldata=${String(c.data||"0x")} value=${c.value??"n/a"}`),a.push(`LEG ${d} gas=${c.gasLimit??"n/a"} maxFeePerGas=${c.maxFeePerGas??c.gasPrice??"n/a"} maxPriorityFeePerGas=${c.maxPriorityFeePerGas??"n/a"}`),a.push(`LEG ${d} l1FeeWei=${c.l1FeeWei??"n/a"} operatorFeeWei=${c.operatorFeeWei??"n/a"} nonce=${c.nonce??"n/a"} type=${c.type??"n/a"}`),oe(String(c.data||"0x")))try{let l=Re(String(c.data||"0x"));a.push(`LEG ${d} APPROVAL token=${l.token||c.to||"n/a"} spender=${l.spender} amount=${l.amount}`)}catch{a.push(`LEG ${d} APPROVAL spender=undecodable amount=undecodable`)}},s=String(i.data||"0x");if(oe(s))try{let c=Re(s);a.push(`APPROVAL token=${c.token||i.to||"n/a"} spender=${c.spender} amount=${c.amount}`)}catch{a.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(i.transactions)&&(a.push(`batchLegs=${i.transactions.length}`),i.transactions.forEach((c,d)=>u(c,d))),o?.surface==="btc"){let c=rn(o,r);a.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(o?.surface==="sol"){let c=cn(o,r);a.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(o?.surface==="hl"){let c=We(o,r);a.push(`hlKind=${c.kind} actionType=${c.actionType} coin=${c.coin||"n/a"} amount=${c.amount} notionalUsd=${c.notional} submitTo=${c.submitTo}`)}if(o?.surface==="poly"){let c=Ue(o,r);a.push(`polyKind=${c.kind} tokenId=${c.tokenId} side=${c.side} price=${c.price} quantity=${c.quantity} notionalUsdc=${c.notionalUsdc} submitTo=${c.submitTo}`)}if(o?.surface==="evm-nft"&&o?.provider==="anvil-nft"&&(a.push(`anvilAction=${o.nftAction} collection=${o.contract} tokenId=${o.tokenId} market=${o.destination}`),a.push(`paymentToken=${o.paymentToken} paymentTokenDecimals=${o.paymentTokenDecimals} maxPaymentTokenAmountRaw=${o.maxPaymentTokenAmountRaw??"n/a"} minPayoutRaw=${o.minPayoutRaw??"n/a"} nativeSwapFeeWei=${o.nativeSwapFeeWei}`),n&&(a.push(`SIGNER VERIFIED block=${n.blockNumber} blockHash=${n.blockHash} runtimeCodeHash=${n.runtimeCodeHash} signer=${n.signerAddress} collection=${n.collection} paymentToken=${n.paymentToken} paymentTokenDecimals=${n.paymentTokenDecimals} nativeSwapFeeWei=${n.nativeSwapFeeWei}`),a.push(`SIGNER DYNAMIC tokenId=${n.tokenId} owner=${n.tokenOwner} inventory=${n.inventoryMember} allowanceRaw=${n.allowanceRaw} approved=${n.approvedAddress} approvedForAll=${n.approvedForAll} quote=${JSON.stringify(n.quote)}`))),o?.surface==="lighter"){let c=Ve(o,r);a.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
19
+ `),t}function TE(e,t,r){let n=String(e||"").toLowerCase();if(n!==String(t||"").toLowerCase())throw new Error("signer: wallet does not match vault metadata");if(!Array.isArray(r)||!r.some(o=>String(o).toLowerCase()===n))throw new Error("signer: wallet is not an allowed policy owner");return!0}function bo(e,t,r){if(!t)throw new Error(`signer: ${e} key is required by policy`);let n=new Set((r||[]).map(o=>String(o).toLowerCase()));if(!t.addresses.some(o=>n.has(String(o).toLowerCase())))throw new Error(`signer: ${e} vault address is not an allowed policy owner`);return!0}function Fs(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function K(e,t){return e.surfaces.includes(t)}function _e(e,t){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`signer: invalid ${t}`);return r}function js(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function Am(e,t){let r=e?.anvilQuote;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("signer: exact prepared Anvil quote is required");if(!e?.artifact?.anvilQuote||JSON.stringify(e.artifact.anvilQuote)!==JSON.stringify(r))throw new Error("signer: exact prepared Anvil quote artifact mismatch");return Object.freeze(t==="buy"?{totalCostRaw:BigInt(r.totalCostRaw).toString(),baseCostRaw:BigInt(r.baseCostRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString(),available:r.available===!0}:{netPayoutRaw:BigInt(r.netPayoutRaw).toString(),grossPayoutRaw:BigInt(r.grossPayoutRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString()})}function vm(e,t,r){if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("signer: exact prepared Anvil quote confirmation required");let n=e.artifact,o=t==="buy"?[r.totalCostRaw,e.maxPaymentTokenAmountRaw,n?.maxPaymentTokenAmountRaw,e.exactQuoteTotalCostRaw,n?.exactQuoteTotalCostRaw,e.preconditions?.confirmedTotalCostRaw]:[r.netPayoutRaw,e.minPayoutRaw,n?.minPayoutRaw,e.exactQuoteNetPayoutRaw,n?.exactQuoteNetPayoutRaw,e.preconditions?.confirmedNetPayoutRaw],i;try{i=BigInt(o[0]);for(let c of o.slice(1))if(BigInt(c)!==i)throw new Error("mismatch")}catch{throw new Error(`signer: exact Anvil ${t} settlement limit mismatch`)}let a=n?.transactions;if(!Array.isArray(a)||a.length!==1)throw new Error("signer: exact Anvil action transaction required");let u=t==="buy"?"buySpecificNFT":"sellNFT",s;try{if(s=Le.decodeFunctionData(u,a[0].data),Le.encodeFunctionData(u,[s[0],s[1]]).toLowerCase()!==String(a[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${t} calldata required`)}if(BigInt(s[0])!==BigInt(e.tokenId)||BigInt(s[1])!==i)throw new Error(`signer: exact Anvil ${t} calldata limit mismatch`);return i}async function qe(e,t,r,n,o,i=[]){let a=await e.send("eth_call",[{to:t,data:r.encodeFunctionData(n,i)},o]);return r.decodeFunctionResult(n,a)[0]}async function Im(e,t,r,{nowMs:n=Date.now(),signerAddress:o}={}){if(t?.surface!=="evm-nft"||String(t?.provider).toLowerCase()!=="anvil-nft")return null;if(!e||typeof e.send!="function")throw new Error("signer: trusted RPC cannot attest Anvil market");let i=_e(t.destination,"Anvil market"),a=_e(t.contract,"Anvil collection"),u=_e(t.paymentToken,"Anvil payment token"),s=BigInt(t.nativeSwapFeeWei),c=Number(t.paymentTokenDecimals),d=_e(o,"Anvil signer identity"),l=_e(t.owner,"Anvil envelope owner");if(d!==l)throw new Error("signer: Anvil signer identity mismatch");let m=BigInt(t.tokenId);if(m<0n)throw new Error("signer: invalid Anvil tokenId");let f=String(t.nftAction||"").toLowerCase();if(f!=="buy"&&f!=="sell")throw new Error("signer: unsupported Anvil NFT action");let p=Am(t,f),w=vm(t,f,p),g=t.anvilAttestation;if(!g||typeof g!="object"||Number(g.snapshotExpiresAtMs)<=Number(n))throw new Error("signer: fresh provider Anvil attestation required");let h=String(js(r.anvilRuntimeCodeHashes,i)||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(h)||h!==String(g.runtimeCodeHash||"").toLowerCase())throw new Error("signer: Anvil runtime is not reviewed by policy");let y=js(r.nftPaymentTokenCaps,u);if(!y||Number(y.decimals)!==c)throw new Error("signer: Anvil payment token decimals are not reviewed by policy");let b=String(await e.send("eth_chainId",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(b)||BigInt(b)!==4663n)throw new Error("signer: trusted RPC Anvil chain mismatch");let S=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(S))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let A=BigInt(S),k=await e.send("eth_getBlockByNumber",[S,!1]),v=String(k?.hash||"").toLowerCase();if(String(k?.number||"").toLowerCase()!==S||!/^0x[0-9a-f]{64}$/.test(v))throw new Error("signer: trusted RPC returned an invalid Anvil block attestation");let _=Object.freeze({blockHash:v,requireCanonical:!0}),C=String(await e.send("eth_getCode",[i,_])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(C)||C==="0x")throw new Error("signer: Anvil market runtime is empty");let z=ym(C).toLowerCase();if(z!==h)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[W,L,$]=await Promise.all([qe(e,i,Le,"collection",_),qe(e,i,Le,"token",_),qe(e,i,Le,"robinhoodSwapFeeWei",_)]),Ke=_e(W,"live Anvil collection"),pt=_e(L,"live Anvil payment token"),Ft=BigInt($).toString();if(Ke!==a)throw new Error("signer: live Anvil collection mismatch");if(pt!==u)throw new Error("signer: live Anvil payment token mismatch");if(Ft!==s.toString())throw new Error("signer: live Anvil native swap fee mismatch");let jt=Number(await qe(e,pt,Ds,"decimals",_));if(!Number.isSafeInteger(jt)||jt!==c)throw new Error("signer: live Anvil payment token decimals mismatch");let mt=_e(await qe(e,Ke,yo,"ownerOf",_,[m]),"live Anvil token owner"),Ge=null,Ye=null,Xe=null,Ze=null,q;if(f==="buy"){let[Me,wt,E]=await Promise.all([qe(e,i,Le,"inventory",_,[m]),qe(e,pt,Ds,"allowance",_,[d,i]),e.send("eth_call",[{to:i,data:Le.encodeFunctionData("quoteSpecificBuy",[m])},_])]);Ge=!!Me,Ye=BigInt(wt).toString();let I=Le.decodeFunctionResult("quoteSpecificBuy",E);if(q=Object.freeze({totalCostRaw:BigInt(I[0]).toString(),baseCostRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString(),available:!!I[4]}),JSON.stringify(q)!==JSON.stringify(p))throw new Error("signer: exact Anvil buy quote changed after preparation");if(mt!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!Ge)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt(Ye)!==BigInt(t.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(Ye)<w)throw new Error("signer: live Anvil ERC20 allowance is insufficient");if(!q.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(q.totalCostRaw)!==w)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(q.totalCostRaw)!==BigInt(q.baseCostRaw)+BigInt(q.feeRaw)+BigInt(q.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[Me,wt,E]=await Promise.all([qe(e,Ke,yo,"getApproved",_,[m]),qe(e,Ke,yo,"isApprovedForAll",_,[d,i]),e.send("eth_call",[{to:i,data:Le.encodeFunctionData("quoteSellNFT")},_])]);Xe=_e(Me,"live Anvil token approval"),Ze=!!wt;let I=Le.decodeFunctionResult("quoteSellNFT",E);if(q=Object.freeze({netPayoutRaw:BigInt(I[0]).toString(),grossPayoutRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString()}),JSON.stringify(q)!==JSON.stringify(p))throw new Error("signer: exact Anvil sell quote changed after preparation");if(mt!==d)throw new Error("signer: exact Anvil token owner does not match signer");if(Xe!==i&&!Ze)throw new Error("signer: live Anvil NFT approval is insufficient");if(Xe!==_e(t.preconditions?.approvedAddress,"prepared Anvil token approval")||Ze!==!!t.preconditions?.approvedForAll)throw new Error("signer: live Anvil NFT approval changed after preparation");if(BigInt(q.netPayoutRaw)!==w)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(q.netPayoutRaw)+BigInt(q.feeRaw)+BigInt(q.protocolFeeRaw)!==BigInt(q.grossPayoutRaw))throw new Error("signer: exact Anvil sell quote fee arithmetic mismatch")}return Object.freeze({source:"local-signer-trusted-rpc",chainId:4663,market:i,collection:Ke,paymentToken:pt,paymentTokenDecimals:jt,nativeSwapFeeWei:Ft,signerAddress:d,nftAction:f,tokenId:m.toString(),tokenOwner:mt,inventoryMember:Ge,allowanceRaw:Ye,approvedAddress:Xe,approvedForAll:Ze,quote:q,blockNumber:A.toString(),blockHash:v,runtimeCodeHash:z,verifiedAtMs:Number(n)})}function qs(e,t,r="execution"){if(!e||!t)throw new Error("signer: complete Anvil revalidation evidence required");for(let n of["runtimeCodeHash","market","collection","paymentToken","paymentTokenDecimals","nativeSwapFeeWei","signerAddress","nftAction","tokenId","tokenOwner","inventoryMember","allowanceRaw","approvedAddress","approvedForAll"])if(String(t[n]).toLowerCase()!==String(e[n]).toLowerCase())throw new Error(`signer: Anvil ${n} changed after simulation at ${r}`);if(JSON.stringify(t.quote)!==JSON.stringify(e.quote))throw new Error(`signer: Anvil quote changed after simulation at ${r}`);return!0}function km(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:a}={}){let u=gm(new URL("./anvil-attestation-worker.mjs",import.meta.url)),s={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},c;try{c=hm(process.execPath,[u],{input:JSON.stringify({rpcUrl:e,chainId:t,envelope:r,policy:s,nowMs:Number(o),signerAddress:a}),encoding:"utf8",timeout:i,maxBuffer:64e3,env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_OPTIONS:""},stdio:["pipe","pipe","pipe"]})}catch{throw new Error("signer: fresh independent Anvil attestation failed before reservation")}let d;try{d=JSON.parse(c)}catch{throw new Error("signer: invalid Anvil reservation attestation result")}if(!d||d.source!=="local-signer-trusted-rpc"||!/^0x[0-9a-f]{64}$/.test(String(d.blockHash||"")))throw new Error("signer: invalid Anvil reservation attestation result");return Object.freeze(d)}function Om(e,t,r,n=null){let o=e?.version===1&&e?.surface?e:null,i=o?.artifact||e||{},a=[`surface=${o?.surface||"evm"} action=${o?.action||"evm"}`,`chain=${i.chainId??i.network??i.cluster??"n/a"} owner=${o?.owner||i.from||"n/a"}`,`to=${i.to||o?.destination||"n/a"} calldata=${String(i.data||"0x")} value=${i.value??"n/a"}`,`gas=${i.gasLimit??"n/a"} maxFeePerGas=${i.maxFeePerGas??i.gasPrice??"n/a"} maxPriorityFeePerGas=${i.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${i.l1FeeWei??"n/a"} operatorFeeWei=${i.operatorFeeWei??"n/a"}`,`nonce=${i.nonce??"n/a"} type=${i.type??"n/a"} accessList=${Array.isArray(i.accessList)?i.accessList.length:0}`,`slippageBps=${o?.slippageBps??i.slippageBps??"n/a"} expiresAtMs=${o?.expiresAtMs??i.expiresAtMs??"n/a"}`],u=(c,d)=>{if(a.push(`LEG ${d} chain=${c.chainId??"n/a"} from=${c.from??"n/a"} to=${c.to??"n/a"}`),a.push(`LEG ${d} calldata=${String(c.data||"0x")} value=${c.value??"n/a"}`),a.push(`LEG ${d} gas=${c.gasLimit??"n/a"} maxFeePerGas=${c.maxFeePerGas??c.gasPrice??"n/a"} maxPriorityFeePerGas=${c.maxPriorityFeePerGas??"n/a"}`),a.push(`LEG ${d} l1FeeWei=${c.l1FeeWei??"n/a"} operatorFeeWei=${c.operatorFeeWei??"n/a"} nonce=${c.nonce??"n/a"} type=${c.type??"n/a"}`),oe(String(c.data||"0x")))try{let l=Re(String(c.data||"0x"));a.push(`LEG ${d} APPROVAL token=${l.token||c.to||"n/a"} spender=${l.spender} amount=${l.amount}`)}catch{a.push(`LEG ${d} APPROVAL spender=undecodable amount=undecodable`)}},s=String(i.data||"0x");if(oe(s))try{let c=Re(s);a.push(`APPROVAL token=${c.token||i.to||"n/a"} spender=${c.spender} amount=${c.amount}`)}catch{a.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(i.transactions)&&(a.push(`batchLegs=${i.transactions.length}`),i.transactions.forEach((c,d)=>u(c,d))),o?.surface==="btc"){let c=rn(o,r);a.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(o?.surface==="sol"){let c=cn(o,r);a.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(o?.surface==="hl"){let c=We(o,r);a.push(`hlKind=${c.kind} actionType=${c.actionType} coin=${c.coin||"n/a"} amount=${c.amount} notionalUsd=${c.notional} submitTo=${c.submitTo}`)}if(o?.surface==="poly"){let c=Ue(o,r);a.push(`polyKind=${c.kind} tokenId=${c.tokenId} side=${c.side} price=${c.price} quantity=${c.quantity} notionalUsdc=${c.notionalUsdc} submitTo=${c.submitTo}`)}if(o?.surface==="evm-nft"&&o?.provider==="anvil-nft"&&(a.push(`anvilAction=${o.nftAction} collection=${o.contract} tokenId=${o.tokenId} market=${o.destination}`),a.push(`paymentToken=${o.paymentToken} paymentTokenDecimals=${o.paymentTokenDecimals} maxPaymentTokenAmountRaw=${o.maxPaymentTokenAmountRaw??"n/a"} minPayoutRaw=${o.minPayoutRaw??"n/a"} nativeSwapFeeWei=${o.nativeSwapFeeWei}`),n&&(a.push(`SIGNER VERIFIED block=${n.blockNumber} blockHash=${n.blockHash} runtimeCodeHash=${n.runtimeCodeHash} signer=${n.signerAddress} collection=${n.collection} paymentToken=${n.paymentToken} paymentTokenDecimals=${n.paymentTokenDecimals} nativeSwapFeeWei=${n.nativeSwapFeeWei}`),a.push(`SIGNER DYNAMIC tokenId=${n.tokenId} owner=${n.tokenOwner} inventory=${n.inventoryMember} allowanceRaw=${n.allowanceRaw} approved=${n.approvedAddress} approvedForAll=${n.approvedForAll} quote=${JSON.stringify(n.quote)}`))),o?.surface==="lighter"){let c=Ve(o,r);a.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
20
20
  Confirm exact action
21
21
  ${[...a,...ds(e,t,r)].join(`
22
22
  `)}
23
- Type digest ${t}: `}async function cr(e,t){let r=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),n=await r.text();if(!r.ok)throw new Error(`rpc: HTTP ${r.status}`);let o=JSON.parse(n||"{}");if(o.error)throw new Error(`rpc: ${o.error.message||"request failed"}`);return o.result}function xo(e){let t=Buffer.from(e),r=t[0]===128?t[1]:t[0];if(!Number.isInteger(r)||r<1||r>8)throw new Error(`signer: Solana message declares an implausible signature count (${r})`);return r}function Eo(e,t){let r=Array.isArray(t)?t:[t],n=xo(e);if(r.length!==n)throw new Error(`signer: Solana message needs ${n} signature(s), got ${r.length}`);for(let o of r)if(Buffer.from(o).length!==64)throw new Error("signer: Solana signature must be 64 bytes");return Buffer.concat([Buffer.from([n]),...r.map(o=>Buffer.from(o)),Buffer.from(e)]).toString("base64")}function Tm({provider:e=null,readPolicy:t,rpc:r=cr,fetchImpl:n=fetch}={}){if(typeof t!="function")throw new TypeError("signer: execution observer requires readPolicy");return async o=>{let i=String(o?.surface||""),a=String(o?.signedTransactionId||"");if(!a)throw new Error("signer: execution observer requires signed transaction identity");if(i==="evm"||i==="evm-swap"||i==="evm-bridge"||i==="evm-nft"){if(!e||typeof e.getTransactionReceipt!="function")return null;let s=await e.getTransactionReceipt(a);return s?{transactionHash:a,status:s.status}:null}let u=t();if(i==="sol"){let s=String(u.solRpcUrl||u.solanaRpcUrl||"");if(!s)return null;let d=(await r(s,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];return d?d.err?{transactionHash:a,status:0}:d.confirmationStatus==="confirmed"||d.confirmationStatus==="finalized"||d.confirmations===null?{transactionHash:a,status:1}:null:null}if(i==="btc"){let s=String(u.btcRpcUrl||u.bitcoinRpcUrl||"").replace(/\/$/,"");if(!s)return null;try{let c=s.endsWith("/tx")?s.slice(0,-3):s,d=await n(`${c}/tx/${a}/status`);if(d.ok)return(await d.json())?.confirmed===!0?{transactionHash:a,status:1}:null}catch{}try{let c=await r(s,{jsonrpc:"1.0",id:"oracle",method:"getrawtransaction",params:[a,!0]});return Number(c?.confirmations||0)>0?{transactionHash:a,status:1}:null}catch{return null}}return null}}async function Hs(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation and broadcast");return cr(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function Nm(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let a=await fetch(`${o}/tx/${t}/outspend/${r}`);if(a.ok){let u=await a.json();if(u?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(u?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await Hs(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Cm(e){if(!e||typeof e!="object"||!e.value||typeof e.value!="object"||!Object.prototype.hasOwnProperty.call(e.value,"err"))throw new Error("signer: Solana simulation result missing");if(e.value.err!==null)throw new Error("signer: Solana simulation failed");return!0}function _m(e,t){return{simulate:async(r,n)=>(We(n,e()),!0),sign:async(r,n)=>{We(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return r?.typedData?(Si(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Ai({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{We(o,e());let{Signature:i,keccak256:a}=await import("ethers"),u=i.from(r);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:u.r,s:u.s,v:u.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(r),status:1}}}}function Lm(e){return{simulate:async(t,r)=>(Ve(r,e()),!0),sign:async(t,r)=>{Ve(r,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(t,r);return Gt(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=Ve(n,e()),i=Gt(r,t),a=ki(i),u=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),s=await u.json().catch(()=>({}));if(!u.ok||Number(s?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(s?.tx_hash||s?.txHash||"lighter"),status:1}}}}function Rm(e,t){return{simulate:async(r,n)=>(tt(n,e()),!0),sign:async(r,n)=>{tt(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(c=>String(c).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: order wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: order wallet must match envelope owner");let a=r.domain||r.typedData.domain,u=r.types||r.typedData.types,s=r.message||r.typedData.message;return t.signTypedData(a,u,s)},broadcast:async(r,n,o)=>{let i=tt(o,e()),{keccak256:a}=await import("ethers"),u=n.message||n.typedData.message,s=i.kind==="cow"?{sellToken:u.sellToken,buyToken:u.buyToken,receiver:u.receiver,sellAmount:u.sellAmount,buyAmount:u.buyAmount,validTo:u.validTo,appData:u.appData,feeAmount:u.feeAmount,kind:u.kind,partiallyFillable:u.partiallyFillable,sellTokenBalance:u.sellTokenBalance,buyTokenBalance:u.buyTokenBalance,from:o.owner,signature:r,signingScheme:"eip712",quoteId:n.quoteId??void 0}:{orderHash:i.digest,signature:r,data:u},c=await fetch(i.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}),d=await c.json().catch(()=>({}));if(!c.ok||d?.error||d?.success===!1)throw new Error(i.kind==="cow"?"signer: CoW orderbook rejected the order":"signer: 1inch orderbook rejected the order");return{hash:a(r),status:1,orderHash:i.digest,uid:typeof d=="string"?d:d?.uid||null}}}}function $m(e,t){return{simulate:async(r,n)=>(Ue(n,e()),!0),sign:async(r,n)=>{Ue(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),a=Ue(o,i),u=fn(i),{keccak256:s}=await import("ethers"),c=Go({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:u.key}),d=JSON.stringify(c),l=Jo({creds:u,address:o.owner,method:"POST",path:"/order",body:d}),m=await fetch(a.submitTo,{method:"POST",headers:l,body:d}),f=await m.json().catch(()=>({}));if(!m.ok||f?.success===!1||f?.error||f?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:s(r),status:1}}}}function Pm(e,t){let r=co(t);return{simulate:async n=>{let o=e(),i=go.fromPSBT(Buffer.from(n.psbt,"base64"));return await Promise.all(Array.from({length:i.inputsLength},(a,u)=>{let s=i.getInput(u),c=Buffer.from(s.txid||[]).toString("hex");return Nm(o,c,s.index)})),!0},sign:n=>{let o=go.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(r),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let a=go.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let u;try{let c=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(u=(await c.text()).trim(),!c.ok)throw new Error(`signer: Bitcoin broadcast failed ${c.status}`)}catch(c){if(!/Bitcoin broadcast failed 404/.test(String(c?.message||c)))throw c;u=await Hs(o,"sendrawtransaction",[a.hex])}if(u&&String(u).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let s=null;try{let c=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${c}/tx/${a.id}/status`);d.ok&&(s=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:s}}}}function Bm(e,t){let r=co(t);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let a=Buffer.from(n.messageBase64,"base64"),u=xo(a),s=Eo(a,Array.from({length:u},()=>new Uint8Array(64))),c=await cr(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[s,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Cm(c)},sign:n=>{let o=Buffer.from(n.messageBase64,"base64"),i=xo(o),a=bm.sign(o,r);if(i===1)return Eo(o,[a]);let u=Array.isArray(n.cosignatures)?n.cosignatures:[];if(u.length!==i-1)throw new Error(`signer: Solana message needs ${i-1} cosignature(s), got ${u.length}`);return Eo(o,[a,...u.map(s=>Buffer.from(String(s),"base64"))])},broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let a=await cr(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),s=(await cr(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(s?.err)return{hash:a,status:0};let c=s?.confirmationStatus==="confirmed"||s?.confirmationStatus==="finalized"||s?.confirmations===null;return{hash:a,status:c?1:null}}}}function Dm(e,t={}){for(let r of Object.keys(t||{}))if(Object.prototype.hasOwnProperty.call(e,r))throw new Error(`signer: cannot replace built-in ${r} transport`)}async function Fm(e,t,r,n,{submitPrivate:o}={}){if((await e.getNetwork()).chainId!==BigInt(r.chainId))throw new Error("signer: RPC chain mismatch");let a={native:(await e.getBalance(r.from)).toString()},u=n&&n.privateRelay;if(u&&typeof o=="function"){let l=u==="require"||u?.mode==="require";try{let m=await o(t,{chainId:Number(r.chainId),requirePrivate:l,allowPublicFallback:!l});if(!m.fellBack&&m.hash){let f=await e.waitForTransaction(m.hash),p={native:(await e.getBalance(r.from)).toString()};return{hash:m.hash,status:f?.status??null,verifiedBefore:a,verifiedAfter:p,submission:{path:"private",mode:m.mode,endpoint:m.endpoint}}}}catch(m){if(l)throw m}}let s=await e.broadcastTransaction(t),c=await s.wait(),d={native:(await e.getBalance(r.from)).toString()};return{hash:c?.hash??s.hash,status:c?.status??null,verifiedBefore:a,verifiedAfter:d,submission:{path:"public"}}}async function CE({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:u,Wallet:s}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(a<1e3||a>12e4)throw new Error("signer: session must be at most 120 seconds");let c=xm(e),d=()=>Object.freeze(Wr(c.policy,c.policyKey,{sequenceAnchorFile:c.policyAnchor})),l=d(),m=String(process.env.ORACLE_OWNER_TELEGRAM||"").split(",").map(E=>E.trim()).filter(Boolean),f=m.length?Ps({keyFile:c.policyKey,approvedTelegramOwners:m}):null;if(K(l,"cex")&&!f)throw new Error("signer: cex requires an approved Telegram owner context");if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let p=["surfaces","actions","destinations","owners"];l.surfaces.some(E=>String(E).startsWith("evm"))&&p.push("chains","spenders");for(let E of p)if(!Array.isArray(l[E])||l[E].length===0)throw new Error(`signer: ${E} allowlist is empty`);if(l.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-nft"||E==="evm-order")){for(let E of["providers"])if(!Array.isArray(l[E])||l[E].length===0)throw new Error(`signer: ${E} allowlist is empty`)}if(l.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-order")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(E=>String(E).startsWith("evm")&&E!=="evm-order")&&(!Array.isArray(l.selectors)||l.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(l.surfaces.includes("sol")&&(!Array.isArray(l.programs)||l.programs.length===0))throw new Error("signer: programs allowlist is empty");if(K(l,"poly")&&(fn(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(K(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(K(l,"cex")&&(!l.cexAccounts||Object.keys(l.cexAccounts).length===0))throw new Error("signer: cexAccounts allowlist is empty");if(K(l,"hl")){let E=Array.isArray(l.coins)?l.coins.map(String):[],I=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(E.filter(j=>j!=="*"&&j!=="#*").length&&!E.includes("*")&&I.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let w=r?ns(r):R(t),g=Va(c.vault),h=Ua(g,w),y;try{y=bs(h,g.meta)}finally{h.fill(0)}if((Fs(l)||K(l,"hl")||K(l,"poly"))&&bo("evm",y.evm,l.owners),K(l,"btc")&&bo("btc",y.btc,l.owners),K(l,"sol")&&bo("sol",y.sol,l.owners),K(l,"cex")){if(!y.cex||Object.keys(y.cex).length===0)throw new Error("signer: local CEX credential records required");for(let[E,I]of Object.entries(l.cexAccounts)){let T=y.cex[E];if(!T||T.accountId!==I.accountId||!I.venues.includes(T.venue)||I.credentialRecordRef!==E)throw new Error("signer: CEX credential venue/account binding refused")}}let b=Array.isArray(l.chains)?l.chains.filter(E=>Number.isInteger(Number(E))&&String(E).trim()!==""):[],S=Fs(l);if(S&&(b.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(K(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(K(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let A=S?new u(l.rpcUrl,Number(b[0])):null,k=y.evm&&(S||K(l,"hl")||K(l,"poly"))?A?new s(y.evm.secret).connect(A):new s(y.evm.secret):null,v=A?{simulate:async E=>{if((await A.getNetwork()).chainId!==BigInt(E.chainId))throw new Error("signer: RPC chain mismatch");return await A.call(E),!0},sign:E=>k.signTransaction(E),broadcast:(E,I,T)=>Fm(A,E,I,T,{submitPrivate:Ka})}:null,_=A?async E=>jm(A,E):void 0,C=new Map,z=E=>E?.surface==="evm-nft"&&String(E?.provider).toLowerCase()==="anvil-nft",W=async(E,I=d(),T="execution")=>{if(!z(E))return null;let j=await Im(A,E,I,{nowMs:Date.now(),signerAddress:k.address}),G=C.get(Q(E));return G&&qs(G,j,T),j},L={...v?{evm:v,"evm-swap":v,"evm-bridge":v,"evm-nft":v}:{},...k&&K(l,"evm-order")?{"evm-order":Rm(d,k)}:{},...y.btc?{btc:Pm(d,y.btc)}:{},...y.sol?{sol:Bm(d,y.sol)}:{},...k&&K(l,"hl")?{hl:_m(d,k)}:{},...k&&K(l,"poly")?{poly:$m(d,k)}:{},...K(l,"lighter")?{lighter:Lm(d)}:{}};Dm(L,n);let $=Ei({...L,...n}),Ke=new Set(Object.keys(L)),pt=new Set(Object.keys(n||{})),Ft=l.surfaces.filter(E=>E!=="cex"&&!Ke.has(E)&&!pt.has(E));if(Ft.length)throw new Error(`signer: ${Ft.join(",")} require local keys or injected surface transports`);let jt=Date.now(),mt=jt+a,Ge=!1,Ye=!1,Xe=()=>{if(!Ye){Ye=!0;for(let E of Object.values(y.cex||{}))for(let I of["apiKeyBytes","apiSecretBytes","passphraseBytes"])E[I]?.fill?.(0)}},Ze=()=>Ge?!1:Bs.existsSync(c.lock)?(Ge=!0,!1):Bs.existsSync(c.vault)&&Date.now()<mt,q=Em({isArmed:Ze,disarmNow:()=>{Ge=!0,Xe(),Ae(c.lock,`disarmed ${new Date().toISOString()}
24
- `)}}),Me=ji({host:o,port:i,token:Sm(c.token),policy:l,readPolicy:d,isArmed:Ze,disarm:q.disarm,armGeneration:q.armGeneration,broadcastWithArmFence:q.broadcastWithArmFence,sessionExpiresAtMs:mt,executionOutbox:ea({path:c.executionOutbox,now:Date.now}),observeExecutionTransaction:Tm({provider:A,readPolicy:d}),nowMs:Date.now,simulate:async(E,I)=>(await W(I,d(),"before simulation"),gr(I,$).simulate(E,I)),estimateNetworkFees:_,sign:async(E,I)=>(await W(I,d(),"before signing"),gr(I,$).sign(E,I)),verifySigned:(E,I,T)=>_i(T?.surface||"evm",E,I,T),broadcast:async(E,I,T)=>(await W(T,d(),"before broadcast"),gr(T,$).broadcast(E,I,T)),confirmArtifact:async(E,I,T)=>{let j=await W(E,T),G=await Mm(E,I,T,j);return G===!0&&j&&C.set(I,j),G},decodeEconomics:(E,I)=>En(E,I),reserveLedger:(E,I,T={})=>{let j=E?.version===1&&E?.surface?E:null,G=j?.artifact||E;if(z(j)){let Qe=Q(j),He=C.get(Qe);if(!He||Date.now()-Number(He.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let qt=km(I.rpcUrl,G.chainId,j,I,{nowMs:Date.now(),signerAddress:k.address});qs(He,qt,"before reservation"),C.set(Qe,qt)}let ur=j?.tradeId||G?.tradeId;if(!ur)throw new Error("ledger: executable artifact requires a tradeId");let ye;if(j)ye=En(j,I);else{if(G?.value===void 0)throw new Error("ledger: executable artifact value required");let Qe=BigInt(G.value),He=BigInt(G.gasLimit??0),qt=BigInt(G.maxFeePerGas??G.gasPrice??0);if(He<=0n||qt<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let Ao=He*qt+BigInt(G.l1FeeWei??0)+BigInt(G.operatorFeeWei??0);ye={unit:"wei",value:Qe.toString(),notional:(Qe+Ao).toString(),fee:Ao.toString()}}if(Array.isArray(ye.units))return rr({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ur,units:ye.units,policy:I,retryReleasedTradeId:T.retryReleasedTradeId});if(ye.value===void 0||ye.notional===void 0)throw new Error("ledger: decoded value and notional required");return rr({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ur,...ye,policy:I,retryReleasedTradeId:T.retryReleasedTradeId})},commitLedger:E=>Xa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),releaseLedger:E=>Za({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),settleFailedLedger:E=>es({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),validateReservation:(E,I,T)=>Ya({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,reservation:E,policy:I,economics:T}),verifyFeeWaiver:(E,I)=>rs(E,I,c.policyKey),verifyTriggerAttestation:(E,I,T)=>ts(E,I,c.policyKey,T),inspectCex:Jr,verifyOwnerProof:f?(E,I)=>f.verify(E,I):void 0,verifyCexOwnerProof:f?(E,I)=>f.verify(E,I):void 0,cexExecute:K(l,"cex")?async E=>{let I=d(),T=Jr(E,I,Date.now()),j=T.kind==="spot-limit-create"?"create":T.kind==="spot-limit-cancel"?"cancel":"status";j==="create"&&xs({envelope:E,paths:c,nowMs:Date.now()});let G=j==="create"?{operation:j,symbol:T.symbol,side:T.side,baseSize:T.baseSize,limitPrice:T.limitPrice,clientOrderId:T.clientOrderId}:{operation:j,symbol:T.symbol,venueOrderId:T.venueOrderId};return _s({credential:ye=>y.cex[ye],settleLedger:({tradeId:ye,disposition:Qe,filledQuote:He})=>Qa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ye,expectedUnit:T.unit,filledQuote:He,disposition:Qe})}).execute({venue:T.venue,accountId:T.accountId,credentialRef:T.credentialRef,tradeId:T.tradeId,reservedNotional:T.notional,order:G,store:vs({file:c.cexOrders,keyFile:c.policyKey,anchorFile:c.cexOrdersAnchor})})}:void 0,ledgerObserver:Ma(process.env)?Ha({path:c.workflowLedger,telemetry:Wa(process.env),onError:E=>{try{console.error(`signer: ${E}`)}catch{}}}):null,autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),wt=setTimeout(()=>Me.close(),a);return wt.unref(),Me.on("close",()=>{clearTimeout(wt),Xe()}),Me.listen(i,o),Me}var Yr="0x420000000000000000000000000000000000000F";function Ms(e){let t=e?.code;if(t==="CALL_EXCEPTION"||t==="BAD_DATA")return!0;let r=String(e?.shortMessage||e?.message||e);return/network|timeout|ECONN|ENOTFOUND|EAI_AGAIN|server error|fetch failed|socket/i.test(r)?!1:/execution reverted|revert|invalid opcode|function selector|could not decode/i.test(r)}async function jm(e,t){if(!ve(t?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:r,Transaction:n}=await import("ethers"),o=new r(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce??0,type:t.type,accessList:t.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let a;try{let u=await e.call({to:Yr,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",u)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await qm(e,o,t.gasLimit)}}async function qm(e,t,r){let n;try{n=BigInt(r)}catch{throw new Error("policy: rollup fee estimate required")}if(n<0n)throw new Error("policy: rollup fee estimate required");try{let o=await e.call({to:Yr,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Ms(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:Yr,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:Yr,data:t.encodeFunctionData("operatorFeeConstant")}),a=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),u=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+u).toString()}catch(o){if(!Ms(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function Mm(e,t,r,n=null){return process.stdin.isTTY?(process.stderr.write(Om(e,t,r,n)),process.stdin.resume(),new Promise(o=>{let i=a=>{process.stdin.off("data",i),process.stdin.pause(),o(String(a).trim()===t)};process.stdin.once("data",i)})):!1}export{qs as assertAnvilAttestationUnchanged,Dm as assertNoBuiltinTransportOverride,NE as assertSignerIdentity,Im as attestAnvilMarket,km as attestAnvilMarketSync,Fm as broadcastEvmSigned,Tm as createExecutionTransactionObserver,Em as createSerializedArmFence,Sm as ensureSignerToken,jm as estimateProviderNetworkFees,Om as renderConfirmationArtifact,xm as signerPaths,CE as startLocalSigner};
23
+ Type digest ${t}: `}async function cr(e,t){let r=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),n=await r.text();if(!r.ok)throw new Error(`rpc: HTTP ${r.status}`);let o=JSON.parse(n||"{}");if(o.error)throw new Error(`rpc: ${o.error.message||"request failed"}`);return o.result}function xo(e){let t=Buffer.from(e),r=t[0]===128?t[1]:t[0];if(!Number.isInteger(r)||r<1||r>8)throw new Error(`signer: Solana message declares an implausible signature count (${r})`);return r}function Eo(e,t){let r=Array.isArray(t)?t:[t],n=xo(e);if(r.length!==n)throw new Error(`signer: Solana message needs ${n} signature(s), got ${r.length}`);for(let o of r)if(Buffer.from(o).length!==64)throw new Error("signer: Solana signature must be 64 bytes");return Buffer.concat([Buffer.from([n]),...r.map(o=>Buffer.from(o)),Buffer.from(e)]).toString("base64")}function Tm({provider:e=null,readPolicy:t,rpc:r=cr,fetchImpl:n=fetch}={}){if(typeof t!="function")throw new TypeError("signer: execution observer requires readPolicy");return async o=>{let i=String(o?.surface||""),a=String(o?.signedTransactionId||"");if(!a)throw new Error("signer: execution observer requires signed transaction identity");if(i==="evm"||i==="evm-swap"||i==="evm-bridge"||i==="evm-nft"){if(!e||typeof e.getTransactionReceipt!="function")return null;let s=await e.getTransactionReceipt(a);return s?{transactionHash:a,status:s.status}:null}let u=t();if(i==="sol"){let s=String(u.solRpcUrl||u.solanaRpcUrl||"");if(!s)return null;let d=(await r(s,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];return d?d.err?{transactionHash:a,status:0}:d.confirmationStatus==="confirmed"||d.confirmationStatus==="finalized"||d.confirmations===null?{transactionHash:a,status:1}:null:null}if(i==="btc"){let s=String(u.btcRpcUrl||u.bitcoinRpcUrl||"").replace(/\/$/,"");if(!s)return null;try{let c=s.endsWith("/tx")?s.slice(0,-3):s,d=await n(`${c}/tx/${a}/status`);if(d.ok)return(await d.json())?.confirmed===!0?{transactionHash:a,status:1}:null}catch{}try{let c=await r(s,{jsonrpc:"1.0",id:"oracle",method:"getrawtransaction",params:[a,!0]});return Number(c?.confirmations||0)>0?{transactionHash:a,status:1}:null}catch{return null}}return null}}async function Hs(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation and broadcast");return cr(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function Nm(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let a=await fetch(`${o}/tx/${t}/outspend/${r}`);if(a.ok){let u=await a.json();if(u?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(u?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await Hs(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Cm(e){if(!e||typeof e!="object"||!e.value||typeof e.value!="object"||!Object.prototype.hasOwnProperty.call(e.value,"err"))throw new Error("signer: Solana simulation result missing");if(e.value.err!==null)throw new Error("signer: Solana simulation failed");return!0}function _m(e,t){return{simulate:async(r,n)=>(We(n,e()),!0),sign:async(r,n)=>{We(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return r?.typedData?(Si(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Ai({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{We(o,e());let{Signature:i,keccak256:a}=await import("ethers"),u=i.from(r);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:u.r,s:u.s,v:u.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(r),status:1}}}}function Lm(e){return{simulate:async(t,r)=>(Ve(r,e()),!0),sign:async(t,r)=>{Ve(r,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(t,r);return Gt(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=Ve(n,e()),i=Gt(r,t),a=ki(i),u=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),s=await u.json().catch(()=>({}));if(!u.ok||Number(s?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(s?.tx_hash||s?.txHash||"lighter"),status:1}}}}function Rm(e,t){return{simulate:async(r,n)=>(tt(n,e()),!0),sign:async(r,n)=>{tt(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(c=>String(c).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: order wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: order wallet must match envelope owner");let a=r.domain||r.typedData.domain,u=r.types||r.typedData.types,s=r.message||r.typedData.message;return t.signTypedData(a,u,s)},broadcast:async(r,n,o)=>{let i=tt(o,e()),{keccak256:a}=await import("ethers"),u=n.message||n.typedData.message,s=i.kind==="cow"?{sellToken:u.sellToken,buyToken:u.buyToken,receiver:u.receiver,sellAmount:u.sellAmount,buyAmount:u.buyAmount,validTo:u.validTo,appData:u.appData,feeAmount:u.feeAmount,kind:u.kind,partiallyFillable:u.partiallyFillable,sellTokenBalance:u.sellTokenBalance,buyTokenBalance:u.buyTokenBalance,from:o.owner,signature:r,signingScheme:"eip712",quoteId:n.quoteId??void 0}:{orderHash:i.digest,signature:r,data:u},c=await fetch(i.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}),d=await c.json().catch(()=>({}));if(!c.ok||d?.error||d?.success===!1)throw new Error(i.kind==="cow"?"signer: CoW orderbook rejected the order":"signer: 1inch orderbook rejected the order");return{hash:a(r),status:1,orderHash:i.digest,uid:typeof d=="string"?d:d?.uid||null}}}}function $m(e,t){return{simulate:async(r,n)=>(Ue(n,e()),!0),sign:async(r,n)=>{Ue(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),a=Ue(o,i),u=fn(i),{keccak256:s}=await import("ethers"),c=Go({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:u.key}),d=JSON.stringify(c),l=Jo({creds:u,address:o.owner,method:"POST",path:"/order",body:d}),m=await fetch(a.submitTo,{method:"POST",headers:l,body:d}),f=await m.json().catch(()=>({}));if(!m.ok||f?.success===!1||f?.error||f?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:s(r),status:1}}}}function Pm(e,t){let r=co(t);return{simulate:async n=>{let o=e(),i=go.fromPSBT(Buffer.from(n.psbt,"base64"));return await Promise.all(Array.from({length:i.inputsLength},(a,u)=>{let s=i.getInput(u),c=Buffer.from(s.txid||[]).toString("hex");return Nm(o,c,s.index)})),!0},sign:n=>{let o=go.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(r),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let a=go.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let u;try{let c=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(u=(await c.text()).trim(),!c.ok)throw new Error(`signer: Bitcoin broadcast failed ${c.status}`)}catch(c){if(!/Bitcoin broadcast failed 404/.test(String(c?.message||c)))throw c;u=await Hs(o,"sendrawtransaction",[a.hex])}if(u&&String(u).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let s=null;try{let c=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${c}/tx/${a.id}/status`);d.ok&&(s=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:s}}}}function Bm(e,t){let r=co(t);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let a=Buffer.from(n.messageBase64,"base64"),u=xo(a),s=Eo(a,Array.from({length:u},()=>new Uint8Array(64))),c=await cr(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[s,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Cm(c)},sign:n=>{let o=Buffer.from(n.messageBase64,"base64"),i=xo(o),a=bm.sign(o,r);if(i===1)return Eo(o,[a]);let u=Array.isArray(n.cosignatures)?n.cosignatures:[];if(u.length!==i-1)throw new Error(`signer: Solana message needs ${i-1} cosignature(s), got ${u.length}`);return Eo(o,[a,...u.map(s=>Buffer.from(String(s),"base64"))])},broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let a=await cr(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),s=(await cr(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(s?.err)return{hash:a,status:0};let c=s?.confirmationStatus==="confirmed"||s?.confirmationStatus==="finalized"||s?.confirmations===null;return{hash:a,status:c?1:null}}}}function Dm(e,t={}){for(let r of Object.keys(t||{}))if(Object.prototype.hasOwnProperty.call(e,r))throw new Error(`signer: cannot replace built-in ${r} transport`)}async function Fm(e,t,r,n,{submitPrivate:o}={}){if((await e.getNetwork()).chainId!==BigInt(r.chainId))throw new Error("signer: RPC chain mismatch");let a={native:(await e.getBalance(r.from)).toString()},u=n&&n.privateRelay;if(u&&typeof o=="function"){let l=u==="require"||u?.mode==="require";try{let m=await o(t,{chainId:Number(r.chainId),requirePrivate:l,allowPublicFallback:!l});if(!m.fellBack&&m.hash){let f=await e.waitForTransaction(m.hash),p={native:(await e.getBalance(r.from)).toString()};return{hash:m.hash,status:f?.status??null,verifiedBefore:a,verifiedAfter:p,submission:{path:"private",mode:m.mode,endpoint:m.endpoint}}}}catch(m){if(l)throw m}}let s=await e.broadcastTransaction(t),c=await s.wait(),d={native:(await e.getBalance(r.from)).toString()};return{hash:c?.hash??s.hash,status:c?.status??null,verifiedBefore:a,verifiedAfter:d,submission:{path:"public"}}}async function NE({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:u,Wallet:s}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(a<1e3||a>12e4)throw new Error("signer: session must be at most 120 seconds");let c=xm(e),d=()=>Object.freeze(Wr(c.policy,c.policyKey,{sequenceAnchorFile:c.policyAnchor})),l=d(),m=String(process.env.ORACLE_OWNER_TELEGRAM||"").split(",").map(E=>E.trim()).filter(Boolean),f=m.length?Ps({keyFile:c.policyKey,approvedTelegramOwners:m}):null;if(K(l,"cex")&&!f)throw new Error("signer: cex requires an approved Telegram owner context");if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let p=["surfaces","actions","destinations","owners"];l.surfaces.some(E=>String(E).startsWith("evm"))&&p.push("chains","spenders");for(let E of p)if(!Array.isArray(l[E])||l[E].length===0)throw new Error(`signer: ${E} allowlist is empty`);if(l.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-nft"||E==="evm-order")){for(let E of["providers"])if(!Array.isArray(l[E])||l[E].length===0)throw new Error(`signer: ${E} allowlist is empty`)}if(l.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-order")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(E=>String(E).startsWith("evm")&&E!=="evm-order")&&(!Array.isArray(l.selectors)||l.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(l.surfaces.includes("sol")&&(!Array.isArray(l.programs)||l.programs.length===0))throw new Error("signer: programs allowlist is empty");if(K(l,"poly")&&(fn(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(K(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(K(l,"cex")&&(!l.cexAccounts||Object.keys(l.cexAccounts).length===0))throw new Error("signer: cexAccounts allowlist is empty");if(K(l,"hl")){let E=Array.isArray(l.coins)?l.coins.map(String):[],I=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(E.filter(j=>j!=="*"&&j!=="#*").length&&!E.includes("*")&&I.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let w=r?ns(r):R(t),g=Va(c.vault),h=Ua(g,w),y;try{y=bs(h,g.meta)}finally{h.fill(0)}if((Fs(l)||K(l,"hl")||K(l,"poly"))&&bo("evm",y.evm,l.owners),K(l,"btc")&&bo("btc",y.btc,l.owners),K(l,"sol")&&bo("sol",y.sol,l.owners),K(l,"cex")){if(!y.cex||Object.keys(y.cex).length===0)throw new Error("signer: local CEX credential records required");for(let[E,I]of Object.entries(l.cexAccounts)){let T=y.cex[E];if(!T||T.accountId!==I.accountId||!I.venues.includes(T.venue)||I.credentialRecordRef!==E)throw new Error("signer: CEX credential venue/account binding refused")}}let b=Array.isArray(l.chains)?l.chains.filter(E=>Number.isInteger(Number(E))&&String(E).trim()!==""):[],S=Fs(l);if(S&&(b.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(K(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(K(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let A=S?new u(l.rpcUrl,Number(b[0])):null,k=y.evm&&(S||K(l,"hl")||K(l,"poly"))?A?new s(y.evm.secret).connect(A):new s(y.evm.secret):null,v=A?{simulate:async E=>{if((await A.getNetwork()).chainId!==BigInt(E.chainId))throw new Error("signer: RPC chain mismatch");return await A.call(E),!0},sign:E=>k.signTransaction(E),broadcast:(E,I,T)=>Fm(A,E,I,T,{submitPrivate:Ka})}:null,_=A?async E=>jm(A,E):void 0,C=new Map,z=E=>E?.surface==="evm-nft"&&String(E?.provider).toLowerCase()==="anvil-nft",W=async(E,I=d(),T="execution")=>{if(!z(E))return null;let j=await Im(A,E,I,{nowMs:Date.now(),signerAddress:k.address}),G=C.get(Q(E));return G&&qs(G,j,T),j},L={...v?{evm:v,"evm-swap":v,"evm-bridge":v,"evm-nft":v}:{},...k&&K(l,"evm-order")?{"evm-order":Rm(d,k)}:{},...y.btc?{btc:Pm(d,y.btc)}:{},...y.sol?{sol:Bm(d,y.sol)}:{},...k&&K(l,"hl")?{hl:_m(d,k)}:{},...k&&K(l,"poly")?{poly:$m(d,k)}:{},...K(l,"lighter")?{lighter:Lm(d)}:{}};Dm(L,n);let $=Ei({...L,...n}),Ke=new Set(Object.keys(L)),pt=new Set(Object.keys(n||{})),Ft=l.surfaces.filter(E=>E!=="cex"&&!Ke.has(E)&&!pt.has(E));if(Ft.length)throw new Error(`signer: ${Ft.join(",")} require local keys or injected surface transports`);let jt=Date.now(),mt=jt+a,Ge=!1,Ye=!1,Xe=()=>{if(!Ye){Ye=!0;for(let E of Object.values(y.cex||{}))for(let I of["apiKeyBytes","apiSecretBytes","passphraseBytes"])E[I]?.fill?.(0)}},Ze=()=>Ge?!1:Bs.existsSync(c.lock)?(Ge=!0,!1):Bs.existsSync(c.vault)&&Date.now()<mt,q=Em({isArmed:Ze,disarmNow:()=>{Ge=!0,Xe(),Ae(c.lock,`disarmed ${new Date().toISOString()}
24
+ `)}}),Me=ji({host:o,port:i,token:Sm(c.token),policy:l,readPolicy:d,isArmed:Ze,disarm:q.disarm,armGeneration:q.armGeneration,broadcastWithArmFence:q.broadcastWithArmFence,sessionExpiresAtMs:mt,executionOutbox:ea({path:c.executionOutbox,now:Date.now}),observeExecutionTransaction:Tm({provider:A,readPolicy:d}),nowMs:Date.now,simulate:async(E,I)=>(await W(I,d(),"before simulation"),gr(I,$).simulate(E,I)),estimateNetworkFees:_,sign:async(E,I)=>(await W(I,d(),"before signing"),gr(I,$).sign(E,I)),verifySigned:(E,I,T)=>_i(T?.surface||"evm",E,I,T),broadcast:async(E,I,T)=>(await W(T,d(),"before broadcast"),gr(T,$).broadcast(E,I,T)),confirmArtifact:async(E,I,T)=>{let j=await W(E,T),G=await Mm(E,I,T,j);return G===!0&&j&&C.set(I,j),G},decodeEconomics:(E,I)=>En(E,I),reserveLedger:(E,I,T={})=>{let j=E?.version===1&&E?.surface?E:null,G=j?.artifact||E;if(z(j)){let Qe=Q(j),He=C.get(Qe);if(!He||Date.now()-Number(He.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let qt=km(I.rpcUrl,G.chainId,j,I,{nowMs:Date.now(),signerAddress:k.address});qs(He,qt,"before reservation"),C.set(Qe,qt)}let ur=j?.tradeId||G?.tradeId;if(!ur)throw new Error("ledger: executable artifact requires a tradeId");let ye;if(j)ye=En(j,I);else{if(G?.value===void 0)throw new Error("ledger: executable artifact value required");let Qe=BigInt(G.value),He=BigInt(G.gasLimit??0),qt=BigInt(G.maxFeePerGas??G.gasPrice??0);if(He<=0n||qt<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let Ao=He*qt+BigInt(G.l1FeeWei??0)+BigInt(G.operatorFeeWei??0);ye={unit:"wei",value:Qe.toString(),notional:(Qe+Ao).toString(),fee:Ao.toString()}}if(Array.isArray(ye.units))return rr({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ur,units:ye.units,policy:I,retryReleasedTradeId:T.retryReleasedTradeId});if(ye.value===void 0||ye.notional===void 0)throw new Error("ledger: decoded value and notional required");return rr({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ur,...ye,policy:I,retryReleasedTradeId:T.retryReleasedTradeId})},commitLedger:E=>Xa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),releaseLedger:E=>Za({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),settleFailedLedger:E=>es({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),validateReservation:(E,I,T)=>Ya({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,reservation:E,policy:I,economics:T}),verifyFeeWaiver:(E,I)=>rs(E,I,c.policyKey),verifyTriggerAttestation:(E,I,T)=>ts(E,I,c.policyKey,T),inspectCex:Jr,verifyOwnerProof:f?(E,I)=>f.verify(E,I):void 0,verifyCexOwnerProof:f?(E,I)=>f.verify(E,I):void 0,cexExecute:K(l,"cex")?async E=>{let I=d(),T=Jr(E,I,Date.now()),j=T.kind==="spot-limit-create"?"create":T.kind==="spot-limit-cancel"?"cancel":"status";j==="create"&&xs({envelope:E,paths:c,nowMs:Date.now()});let G=j==="create"?{operation:j,symbol:T.symbol,side:T.side,baseSize:T.baseSize,limitPrice:T.limitPrice,clientOrderId:T.clientOrderId}:{operation:j,symbol:T.symbol,venueOrderId:T.venueOrderId};return _s({credential:ye=>y.cex[ye],settleLedger:({tradeId:ye,disposition:Qe,filledQuote:He})=>Qa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ye,expectedUnit:T.unit,filledQuote:He,disposition:Qe})}).execute({venue:T.venue,accountId:T.accountId,credentialRef:T.credentialRef,tradeId:T.tradeId,reservedNotional:T.notional,order:G,store:vs({file:c.cexOrders,keyFile:c.policyKey,anchorFile:c.cexOrdersAnchor})})}:void 0,ledgerObserver:Ma(process.env)?Ha({path:c.workflowLedger,telemetry:Wa(process.env),onError:E=>{try{console.error(`signer: ${E}`)}catch{}}}):null,autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),wt=setTimeout(()=>Me.close(),a);return wt.unref(),Me.on("close",()=>{clearTimeout(wt),Xe()}),Me.listen(i,o),Me}var Yr="0x420000000000000000000000000000000000000F";function Ms(e){let t=e?.code;if(t==="CALL_EXCEPTION"||t==="BAD_DATA")return!0;let r=String(e?.shortMessage||e?.message||e);return/network|timeout|ECONN|ENOTFOUND|EAI_AGAIN|server error|fetch failed|socket/i.test(r)?!1:/execution reverted|revert|invalid opcode|function selector|could not decode/i.test(r)}async function jm(e,t){if(!ve(t?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:r,Transaction:n}=await import("ethers"),o=new r(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce??0,type:t.type,accessList:t.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let a;try{let u=await e.call({to:Yr,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",u)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await qm(e,o,t.gasLimit)}}async function qm(e,t,r){let n;try{n=BigInt(r)}catch{throw new Error("policy: rollup fee estimate required")}if(n<0n)throw new Error("policy: rollup fee estimate required");try{let o=await e.call({to:Yr,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Ms(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:Yr,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:Yr,data:t.encodeFunctionData("operatorFeeConstant")}),a=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),u=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+u).toString()}catch(o){if(!Ms(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function Mm(e,t,r,n=null){return process.stdin.isTTY?(process.stderr.write(Om(e,t,r,n)),process.stdin.resume(),new Promise(o=>{let i=a=>{process.stdin.off("data",i),process.stdin.pause(),o(String(a).trim()===t)};process.stdin.once("data",i)})):!1}export{qs as assertAnvilAttestationUnchanged,Dm as assertNoBuiltinTransportOverride,TE as assertSignerIdentity,Im as attestAnvilMarket,km as attestAnvilMarketSync,Fm as broadcastEvmSigned,Tm as createExecutionTransactionObserver,Em as createSerializedArmFence,Sm as ensureSignerToken,jm as estimateProviderNetworkFees,Om as renderConfirmationArtifact,xm as signerPaths,NE as startLocalSigner};