@oracle-agent/oracle 0.35.6 → 0.35.7

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.
@@ -1,17 +1,17 @@
1
- import{parseArgs as k}from"node:util";import{spawn as m}from"node:child_process";var v=["SIGINT","SIGTERM","SIGHUP"];function h(t,a=[],r={},n=t){return new Promise(s=>{let e=m(t,a,r),o=!1,c=null,i=new Map(v.map(l=>[l,()=>{c||=l,e.exitCode===null&&e.signalCode===null&&e.kill(l)}]));for(let[l,p]of i)process.on(l,p);let d=()=>{for(let[l,p]of i)process.off(l,p)};e.once("error",l=>{o||(o=!0,d(),process.stderr.write(`oracle: could not start ${n}: ${l.message}
2
- `),s(1))}),e.once("exit",(l,p)=>{if(o)return;o=!0,d();let f=c||p;if(f){process.kill(process.pid,f);return}s(l??1)})})}var w="http://127.0.0.1:8787";function g(){process.stderr.write(`usage: oracle data <serve|call|catalog|health> [args]
1
+ import{parseArgs as m}from"node:util";import{spawn as v}from"node:child_process";var k=["SIGINT","SIGTERM","SIGHUP"];function h(r,a=[],t={},n=r){return new Promise(s=>{let e=v(r,a,t),o=!1,c=null,i=new Map(k.map(l=>[l,()=>{c||=l,e.exitCode===null&&e.signalCode===null&&e.kill(l)}]));for(let[l,d]of i)process.on(l,d);let u=()=>{for(let[l,d]of i)process.off(l,d)};e.once("error",l=>{o||(o=!0,u(),process.stderr.write(`oracle: could not start ${n}: ${l.message}
2
+ `),s(1))}),e.once("exit",(l,d)=>{if(o)return;o=!0,u();let f=c||d;if(f){process.kill(process.pid,f);return}s(l??1)})})}var w="http://127.0.0.1:8787";function g(){process.stderr.write(`usage: oracle data <serve|call|catalog|health> [args]
3
3
  oracle data serve [--port N]
4
4
  oracle data call <provider> <op> [key=value ...] [--key value ...] [--args '<json>']
5
5
  oracle data catalog
6
- oracle data health
6
+ oracle data health [--cached [--max-age-ms N]]
7
7
 
8
8
  examples:
9
9
  oracle data call bitcoin-esplora tipHeight
10
10
  oracle data call poly-public markets slug=will-oscar-piastri-be-the-2026-f1-drivers-champion
11
11
  oracle data call hl-markets coin coin=HYPE
12
- `)}function y(t){let a=t[0],r=t[1];if(!a||!r)return{ok:!1,error:"provider and op are required"};let n={};for(let s=2;s<t.length;s+=1){let e=t[s];if(e==="--args"){try{Object.assign(n,JSON.parse(t[++s]||"{}"))}catch(c){return{ok:!1,error:`invalid --args JSON: ${c.message}`}}continue}if(e.startsWith("--")){let c=e.slice(2),i=t[s+1];if(i==null||i.startsWith("--")){n[c]=!0;continue}n[c]=i,s+=1;continue}let o=e.indexOf("=");if(o>0){n[e.slice(0,o)]=e.slice(o+1);continue}return{ok:!1,error:`unexpected positional argument '${e}'. Pass parameters as key=value (e.g. slug=${e}), as --key value, or as --args '{"slug":"${e}"}'.`}}return{ok:!0,provider:a,op:r,args:n}}function S(){return"/data/health"}async function u(t,{method:a="GET",body:r}={}){let s=(process.env.ORACLE_DATA_URL||w).replace(/\/$/,"")+t;try{let e=await fetch(s,{method:a,headers:r?{"content-type":"application/json"}:void 0,body:r?JSON.stringify(r):void 0}),o=await e.text();return process.stdout.write(o.endsWith(`
12
+ `)}function y(r){let a=r[0],t=r[1];if(!a||!t)return{ok:!1,error:"provider and op are required"};let n={};for(let s=2;s<r.length;s+=1){let e=r[s];if(e==="--args"){try{Object.assign(n,JSON.parse(r[++s]||"{}"))}catch(c){return{ok:!1,error:`invalid --args JSON: ${c.message}`}}continue}if(e.startsWith("--")){let c=e.slice(2),i=r[s+1];if(i==null||i.startsWith("--")){n[c]=!0;continue}n[c]=i,s+=1;continue}let o=e.indexOf("=");if(o>0){n[e.slice(0,o)]=e.slice(o+1);continue}return{ok:!1,error:`unexpected positional argument '${e}'. Pass parameters as key=value (e.g. slug=${e}), as --key value, or as --args '{"slug":"${e}"}'.`}}return{ok:!0,provider:a,op:t,args:n}}function A(r=[]){if(!r.includes("--cached"))return"/data/health";let a=null;try{let{values:t}=m({args:r,options:{cached:{type:"boolean"},"max-age-ms":{type:"string"}},allowPositionals:!0,strict:!1});a=t["max-age-ms"]||null}catch{}return`/data/health?cached=1${a?`&maxAgeMs=${encodeURIComponent(a)}`:""}`}async function p(r,{method:a="GET",body:t}={}){let s=(process.env.ORACLE_DATA_URL||w).replace(/\/$/,"")+r;try{let e=await fetch(s,{method:a,headers:t?{"content-type":"application/json"}:void 0,body:t?JSON.stringify(t):void 0}),o=await e.text();return process.stdout.write(o.endsWith(`
13
13
  `)?o:o+`
14
14
  `),e.ok?0:1}catch(e){return e&&(e.code==="ECONNREFUSED"||/fetch failed|ECONNREFUSED/i.test(String(e)))?(process.stderr.write(`oracle: data server not running \u2014 start it with 'oracle data serve'
15
15
  `),4):(process.stderr.write(`oracle data: ${e.message||e}
16
- `),1)}}var N={name:"data",summary:"desk data plane",group:"read",usage:"oracle data serve|call|catalog|health",async run(t){let a=t.argv[0];if(!a||a==="--help"||a==="-h")return g(),a?0:1;if(a==="serve"){let r=null;try{let{values:e}=k({args:t.argv.slice(1),options:{port:{type:"string"}},allowPositionals:!0,strict:!1});r=e.port||null}catch{}let n={...process.env};r&&(n.ORACLE_DATA_PORT=String(r));let s=t.bin("desk-server.mjs");return h(process.execPath,[s],{stdio:"inherit",env:n},"desk-server")}if(a==="health")return u(S());if(a==="catalog")return u("/data/catalog");if(a==="call"){let r=y(t.argv.slice(1));return r.ok?u("/data/call",{method:"POST",body:{provider:r.provider,op:r.op,args:r.args}}):(process.stderr.write(`oracle data call: ${r.error}
17
- `),1)}return g(),1}};export{S as dataHealthRoute,N as default,y as parseDataCallArgs};
16
+ `),1)}}var R={name:"data",summary:"desk data plane",group:"read",usage:"oracle data serve|call|catalog|health",async run(r){let a=r.argv[0];if(!a||a==="--help"||a==="-h")return g(),a?0:1;if(a==="serve"){let t=null;try{let{values:e}=m({args:r.argv.slice(1),options:{port:{type:"string"}},allowPositionals:!0,strict:!1});t=e.port||null}catch{}let n={...process.env};t&&(n.ORACLE_DATA_PORT=String(t));let s=r.bin("desk-server.mjs");return h(process.execPath,[s],{stdio:"inherit",env:n},"desk-server")}if(a==="health")return p(A(r.argv.slice(1)));if(a==="catalog")return p("/data/catalog");if(a==="call"){let t=y(r.argv.slice(1));return t.ok?p("/data/call",{method:"POST",body:{provider:t.provider,op:t.op,args:t.args}}):(process.stderr.write(`oracle data call: ${t.error}
17
+ `),1)}return g(),1}};export{A as dataHealthRoute,R as default,y as parseDataCallArgs};
@@ -0,0 +1 @@
1
+ var B=1,C=/^0x[0-9a-f]{40}$/,v=/^0x(?:[0-9a-f]{2})*$/,O=/^(?:0x)?[0-9a-f]{64}$/,N=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,_=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,z=new Set([12,15,18,21,24]),w=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 h(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let n=e.trim().split(/\s+/);if(_.test(e)||z.has(n.length)&&n.every(i=>/^[a-z]+$/i.test(i)))throw new w(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((n,i)=>h(n,`${t}[${i}]`,r));a(e,t);let s={};for(let n of Object.keys(e).sort()){let i=n.replace(/[^a-z0-9]/gi,"");if(N.test(i))throw new w(`${t}.${n}`);e[n]!==void 0&&(s[n]=h(e[n],`${t}.${n}`,n))}return s}function a(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 g(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function f(e,t){let r=String(g(e,t)).toLowerCase();if(!C.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function o(e,t,{positive:r=!1}={}){try{let s=BigInt(g(e,t));if(s<0n||r&&s===0n)throw new Error;return s.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function E(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 D(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))D(t);Object.freeze(e)}return e}function j(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};a(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 s=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:E(String(s),`${t}.reason`)}}function H(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((s,n)=>j(s,`policyChecks[${n}]`)),r=t.filter(s=>!s.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(s=>s.reason)}}function V(e){if(e==null)return null;if(a(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:E(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=o(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=o(e.gasLimit,"simulation.gasLimit")),t}function q(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)=>{a(t,`assetDeltas[${r}]`);let s=o(t.before,`assetDeltas[${r}].before`),n=o(t.after,`assetDeltas[${r}].after`),i=(BigInt(n)-BigInt(s)).toString(),l;try{l=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(l!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:E(String(g(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:s,after:n,delta:l}})}function x(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)=>{a(t,`approvalDeltas[${r}]`);let s=o(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:f(t.token,`approvalDeltas[${r}].token`),spender:f(t.spender,`approvalDeltas[${r}].spender`),owner:f(t.owner,`approvalDeltas[${r}].owner`),amount:s,revokeLike:t.revokeLike??BigInt(s)===0n}})}function K(e={}){a(e,"input");let t=h(e),r=t.tx==null?t:a(t.tx,"tx"),s=o(t.chainId??r.chainId,"chainId",{positive:!0}),n=f(t.account??t.from??r.from,"account/from"),i=f(t.destination??t.to??r.to,"destination/to"),l=String(g(t.prepareHash,"prepareHash")).toLowerCase();if(!O.test(l))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let c=t.route??t.venue;if(c==null)throw new TypeError("sign-time review: route/venue required");let d=t.decodedCalldata??t.decodedAction;if(d==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let u=String(g(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!v.test(u))throw new TypeError("sign-time review: calldata/data must be even-length hex");let $=t.policyChecks!==void 0&&t.policyChecks!==null,m=H($?t.policyChecks:[]),p=V(t.simulation),y=q(t.assetDeltas),S=x(t.approvalDeltas),b=t.allowlistHits??[];if(!Array.isArray(b))throw new TypeError("sign-time review: allowlistHits must be an array");let k=p?.willRevert===!0||["failed","error"].includes(p?.status),A=p!=null&&p.willRevert===!1&&["ok","success"].includes(p.status),T=k||m.failed>0?"BLOCKED":A&&$&&m.checks.length>0&&y!=null?"READY":"UNKNOWN",L=typeof d=="string"?d:d.method??d.action??d.type??"transaction",I=`${T}: review ${L} on chain ${s}; policy ${m.passed} passed, ${m.failed} failed; ${y?.length??0} asset delta${y?.length===1?"":"s"}; local signature required`,R={reviewVersion:1,status:T,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:s,account:n,from:n,route:c,venue:t.venue??(typeof c=="string"?c:c.venue??c.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:f(t.spender,"spender")},prepareHash:l,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:u,data:u,selector:u.length>=10?u.slice(0,10):null,value:o(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:o(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:o(t.gasLimit??r.gasLimit,"gasLimit")},simulation:p,policyChecks:m,allowlistHits:b,assetDeltas:y,approvalDeltas:S,summary:I};return D(R)}export{B as SIGN_TIME_REVIEW_VERSION,w as SignTimeReviewSecretError,K as createSignTimeReview};
@@ -0,0 +1 @@
1
+ import{wordlists as B}from"ethers";var Y=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),q=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],J=new Set([12,15,18,21,24]);function X(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return J.has(t.length)&&t.every(r=>B.en.getWordIndex(r)>=0)}var Z=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,Q=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,v=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function ee(e){let t=L(e);return v.has(t)||Q.test(t)}var y=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function L(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function te(e){let t=L(e);return[...Y].some(r=>t.includes(r))}function ne(e,t,r){if(typeof t=="string"){if(q.some(o=>o.test(t))||X(t))throw new y(r);if(Z.test(t)&&!ee(e))throw new y(r)}}function x(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return ne(r,e,t),e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`action receipt: non-finite number at ${t}`);return e}if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return e.map((n,i)=>x(n,`${t}[${i}]`,r));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${t}`);let o={};for(let n of Object.keys(e).sort()){let i=`${t}.${n}`;if(te(n))throw new y(i);e[n]!==void 0&&(o[n]=x(e[n],i,n))}return o}function j(e){return x(e)}var ge=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),Ee=Object.freeze(["read","simulate"]);var Ae=1440*60;var u=class extends Error{constructor(t,r){super(`secret material must never appear in a public API object (at ${t}, rule: ${r})`),this.name="SecretLeakError",this.path=t,this.rule=r}},re=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,oe=Object.freeze(["privkey","wif","xprv","seed"]);function w(e){let t=String(e),r=t.toLowerCase().replace(/[\s._-]+/g,"");return re.test(t)||oe.includes(r)}var F=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}]),D=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function ie(e){return e.replace(/"([A-Za-z0-9_-]+)"\s*:\s*"(?:0x)?([0-9a-fA-F]{64})"/g,(t,r)=>D.includes(String(r).toLowerCase().replace(/[_-]/g,""))?`"${r}":"<hex64>"`:t)}function U(e){let t;try{t=JSON.stringify(e)}catch(n){throw new u("$",`unserializable-payload: ${String(n?.message||n)}`)}if(t===void 0)return"null";let r=ie(t);for(let{rule:n,re:i}of F)if(i.test(r))throw new u("$<serialized>",n);if(/(?:^|[^0-9a-fA-Fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/.test(r))throw new u("$<serialized>","raw-32-byte-hex-embedded");return JSON.parse(t,(n,i)=>{if(n&&w(n))throw new u(`$<serialized>.${n}`,"forbidden-key-name");return i}),t}function d(e,t="$",r=new Set,o=""){if(e==null)return e;if(typeof e=="string"){let n=D.includes(String(o).toLowerCase().replace(/[_-]/g,""));for(let{rule:i,re:l}of F)if(!(n&&i.startsWith("raw-32-byte-hex"))&&l.test(e))throw new u(t,i);return e}if(typeof e!="object"||r.has(e)||(r.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[n,i]of e.entries()){if(typeof n=="string"&&w(n))throw new u(`${t}[${JSON.stringify(n)}]`,"forbidden-key-name");d(n,`${t}[key]`,r),d(i,`${t}[${String(n)}]`,r)}return e}if(e instanceof Set){let n=0;for(let i of e.values())d(i,`${t}[${n++}]`,r);return e}if(Array.isArray(e))return e.forEach((n,i)=>d(n,`${t}[${i}]`,r)),e;for(let[n,i]of Object.entries(e)){if(w(n))throw new u(`${t}.${n}`,"forbidden-key-name");d(i,`${t}.${n}`,r,n)}return e}var se=/[\u0000-\u001f\u007f]/;function S(e,t){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`${t} must be a plain object`);return e}function N(e,t="control input"){try{d(e,t),U(e)}catch(r){throw new TypeError(`${t} contains secret or custody material: ${r.message}`)}return e}function m(e,{required:t=[],optional:r=[]}={},o="object"){S(e,o);let n=new Set([...t,...r]),i=Object.keys(e).filter(l=>!n.has(l));if(i.length)throw new TypeError(`${o} has unknown field ${i[0]}`);for(let l of t)if(!Object.hasOwn(e,l))throw new TypeError(`${o}.${l} is required`);return e}function I(e,t,r=200,{lower:o=!1}={}){if(typeof e!="string"||!e.trim()||e.length>r||se.test(e))throw new TypeError(`${t} must be non-empty control-free text up to ${r} characters`);let n=e.trim();return o?n.toLowerCase():n}function h(e,t,r=80){let o=I(e,t,r,{lower:!0});if(!/^[a-z0-9][a-z0-9._:-]*$/.test(o))throw new TypeError(`${t} must be a lowercase identifier`);return o}function A(e,t,{positive:r=!1}={}){if(!Number.isSafeInteger(e)||e<0||r&&e===0)throw new TypeError(`${t} must be a ${r?"positive":"non-negative"} safe integer`);return e}function f(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))f(t);Object.freeze(e)}return e}var ae=Object.freeze(["confirmations","finalizedTag","checkpoint"]),p=Object.freeze({UNKNOWN:"UNKNOWN",INCLUDED:"INCLUDED",FINAL:"FINAL"}),ce=Object.freeze(["LIVE","STALE","UNKNOWN","UNAVAILABLE"]);function H({family:e,chainId:t},r="chain"){let o=h(e,`${r}.family`,40),n;if(o==="evm"){if(typeof t=="number")n=String(A(t,`${r}.chainId`,{positive:!0}));else if(n=I(t,`${r}.chainId`,40),!/^[1-9][0-9]*$/.test(n))throw new TypeError(`${r}.chainId must be a positive decimal EVM chain id`)}else n=h(t,`${r}.chainId`,80);return{family:o,chainId:n}}function fe(e,t="chain"){return m(e,{required:["family","chainId"]},t),f(H(e,t))}function K(e,t="finality rule"){N(e,t),S(e,t);let r=e.rule;if(!ae.includes(r))throw new TypeError(`${t}.rule must be confirmations, finalizedTag, or checkpoint`);let o=r==="confirmations"?"confirmations":r;m(e,{required:["family","chainId","rule",o]},t);let n=H(e,t);return r==="confirmations"?{...n,rule:r,confirmations:A(e.confirmations,`${t}.confirmations`,{positive:!0})}:{...n,rule:r,[o]:h(e[o],`${t}.${o}`,80)}}function $(e){if(!Array.isArray(e))throw new TypeError("finality policy rules must be an array");let t=e.map((o,n)=>K(o,`finality policy rule ${n}`)),r=new Set;for(let o of t){let n=`${o.family}\0${o.chainId}`;if(r.has(n))throw new TypeError(`duplicate finality rule for ${o.family}:${o.chainId}`);r.add(n)}return f({policyVersion:1,rules:t})}function le(e){if(m(e,{required:["policyVersion","rules"]},"finality policy"),e.policyVersion!==1||!Array.isArray(e.rules))throw new TypeError("unsupported finality policy");return $(e.rules)}function V(e,t){let r=fe(t,"finality query"),n=le(e).rules.find(i=>i.family===r.family&&i.chainId===r.chainId);return n?f({status:"KNOWN",...r,rule:n}):f({status:p.UNKNOWN,reason:"MISSING_FINALITY_RULE",...r,rule:null})}function ue(e,t){if(e==null)return null;N(e,"finality evidence");let r=t.rule==="confirmations"?"confirmations":t.rule;if(m(e,{required:["status"],optional:[r]},"finality evidence"),!ce.includes(e.status))throw new TypeError("finality evidence.status is unknown");let o={status:e.status};return e[r]!=null&&(o[r]=t.rule==="confirmations"?A(e.confirmations,"finality evidence.confirmations",{positive:!0}):h(e[r],`finality evidence.${r}`,80)),o}function P(e,t){if(!e||e.status===p.UNKNOWN||e.rule==null)return f({status:p.UNKNOWN,final:!1,reason:"MISSING_FINALITY_RULE"});let r=K(e.rule??e,"resolved finality rule"),o=ue(t,r);if(o==null)return f({status:p.UNKNOWN,final:!1,reason:"MISSING_FINALITY_EVIDENCE"});if(o.status!=="LIVE")return f({status:p.UNKNOWN,final:!1,reason:`${o.status}_EVIDENCE`});let n=!1;return r.rule==="confirmations"?n=o.confirmations!=null&&o.confirmations>=r.confirmations:r.rule==="finalizedTag"?n=o.finalizedTag===r.finalizedTag:n=o.checkpoint===r.checkpoint,f({status:n?p.FINAL:p.INCLUDED,final:n,reason:n?"PINNED_RULE_SATISFIED":"PINNED_RULE_NOT_SATISFIED",rule:r})}var de=1,He=Object.freeze(["SUCCESS","FAIL","UNKNOWN"]),s=(...e)=>e.find(t=>t!=null),b=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype;function pe(e){if(e===!0||e===1||e==="1")return"SUCCESS";if(e===!1||e===0||e==="0")return"FAIL";if(typeof e!="string")return"UNKNOWN";let t=e.trim().toUpperCase();return["SUCCESS","SUCCEEDED","OK","EXECUTED"].includes(t)?"SUCCESS":["FAIL","FAILED","FAILURE","REVERTED","REJECTED"].includes(t)?"FAIL":"UNKNOWN"}function G(e){return typeof e=="string"&&["FAIL","FAILED","FAILURE","ORPHAN","ORPHANED","REVERTED"].includes(e.trim().toUpperCase())}function O(e){return e==null?e:Array.isArray(e)?e.map(O):b(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,O(e[t])])):String(e)}function ye(e,t,r,o){let n=s(e.finalityEvidence,o?.finality,e.evidence),i=s(e.finalityPolicy,e.policy);try{return i==null&&b(e.finalityRule)&&(i=$([{family:t,chainId:r,...e.finalityRule}])),i==null||t==null||r==null?{status:"UNKNOWN",final:!1,reason:"MISSING_FINALITY_RULE"}:P(V(i,{family:t,chainId:r}),n)}catch{return{status:"UNKNOWN",final:!1,reason:"MALFORMED_FINALITY_EVIDENCE"}}}function c(e,t,r){r!=null&&(e[t]=r)}function me(e){return e==null?null:String(e).trim().toLowerCase()}function _(...e){let t=e.map(me).filter(Boolean);return t.length<=1||t.every(r=>r===t[0])}function Ke(e={}){if(!b(e))throw new TypeError("verified receipt: input object required");let t=j(e),r=s(t.actionReceipt,t.receipt),o=b(r)?r:t,n=s(t.observation,t.chainObservation,t.observedReceipt),i=b(n),l=s(t.txHash,o.txHash,o.transactionHash,n?.txHash,n?.transactionHash),T=s(t.family,o.family,o.chain?.family,n?.family,n?.chain?.family),R=s(t.chainId,o.chainId,o.chain?.chainId,n?.chainId,n?.chain?.chainId),g=!_(t.txHash,o.txHash,o.transactionHash,n?.txHash,n?.transactionHash)||!_(t.family,o.family,o.chain?.family,n?.family,n?.chain?.family)||!_(t.chainId,o.chainId,o.chain?.chainId,n?.chainId,n?.chain?.chainId),C=ye(t,T,R,i&&!g?n:null),z=pe(s(n?.receiptStatus,n?.executionStatus,n?.status)),W=s(t.reconciliationStatus,t.reconciliation?.status,n?.reconciliationStatus),M=s(t.finalityState,t.finalityEvidence?.status,t.evidence?.status,n?.finalityState),E="UNKNOWN";G(W)||!g&&(i&&z==="FAIL"||G(M))?E="FAIL":!g&&l&&i&&z==="SUCCESS"&&["INCLUDED","FINAL"].includes(C.status)&&(E="SUCCESS");let a={verifiedReceiptVersion:de,status:E};g&&(a.reason="REFERENCE_MISMATCH"),c(a,"txHash",l),c(a,"chain",s(t.chain,o.chain,n?.chain)),c(a,"family",T),c(a,"chainId",R),c(a,"block",s(n?.block,t.block)),c(a,"blockState",s(n?.blockState,n?.inclusionState)),a.finalityState=C.status,c(a,"confirmations",s(n?.confirmations,n?.finality?.confirmations,t.finalityEvidence?.confirmations,t.evidence?.confirmations)),c(a,"observedAt",s(n?.observedAt,t.observedAt)),c(a,"route",s(t.route,o.route)),c(a,"prepareHash",s(t.prepareHash,o.prepareHash)),c(a,"policyOutcome",s(t.policyOutcome,o.policyOutcome,o.policyChecks));let k=s(t.balanceChanges,n?.balanceChanges,n?.balances,o.balanceChanges,o.balances);return k!=null&&(a.balanceChanges=O(k)),c(a,"createdAt",s(t.createdAt,o.createdAt)),c(a,"submittedAt",s(t.submittedAt,o.submittedAt)),c(a,"finalizedAt",s(t.finalizedAt,n?.finalizedAt)),c(a,"timestamps",s(t.timestamps,o.timestamps,n?.timestamps)),f(a)}export{He as VERIFIED_RECEIPT_STATUSES,de as VERIFIED_RECEIPT_VERSION,Ke as stampVerifiedReceipt};