@oracle-agent/oracle 0.35.53 → 0.35.55

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,27 +1,27 @@
1
- var on=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};import fr from"node:fs";import rc from"node:os";import gt from"node:path";import{fileURLToPath as nc}from"node:url";function Ro(){return process.env.ORACLE_FAKE_HOME||rc.homedir()}function ic(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function pr(){return ic()?process.env.ORACLE_CONFIG_DIR||gt.join(Ro(),".config","oracle"):gt.join(Ro(),".config","oracle")}function sc(){return gt.join(pr(),"desk.json")}function ac(){return gt.join(pr(),"env")}function ht({force:e=!1}={}){if(ht._done&&!e)return ht._result||null;ht._done=!0;let t={},r=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=ac();if(fr.existsSync(o))for(let i of fr.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let u=s[2];(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),r(s[1],u)}}catch{}try{let o=sc();if(fr.existsSync(o)){let i=JSON.parse(fr.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),ht._result=Object.keys(t).length?t:null,ht._result}var oc,mw,Lo=on(()=>{oc=gt.dirname(nc(import.meta.url)),mw=gt.resolve(oc,"../..");try{ht()}catch{}});function cn(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Rc.test(e)||Lc.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new wr(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)=>cn(o,`${t}[${i}]`,r));et(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(_c.test(i))throw new wr(`${t}.${o}`);e[o]!==void 0&&(n[o]=cn(e[o],`${t}.${o}`,o))}return n}function et(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 Ut(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function bt(e,t){let r=String(Ut(e,t)).toLowerCase();if(!Tc.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function $e(e,t,{positive:r=!1}={}){try{let n=BigInt(Ut(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 un(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 Do(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Do(t);Object.freeze(e)}return e}function $c(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};et(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:un(String(n),`${t}.reason`)}}function Pc(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>$c(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 Bc(e){if(e==null)return null;if(et(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:un(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=$e(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=$e(e.gasLimit,"simulation.gasLimit")),t}function Dc(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)=>{et(t,`assetDeltas[${r}]`);let n=$e(t.before,`assetDeltas[${r}].before`),o=$e(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),s;try{s=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(s!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:un(String(Ut(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:s}})}function Fc(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)=>{et(t,`approvalDeltas[${r}]`);let n=$e(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:bt(t.token,`approvalDeltas[${r}].token`),spender:bt(t.spender,`approvalDeltas[${r}].spender`),owner:bt(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function Fo(e={}){et(e,"input");let t=cn(e),r=t.tx==null?t:et(t.tx,"tx"),n=$e(t.chainId??r.chainId,"chainId",{positive:!0}),o=bt(t.account??t.from??r.from,"account/from"),i=bt(t.destination??t.to??r.to,"destination/to"),s=String(Ut(t.prepareHash,"prepareHash")).toLowerCase();if(!Cc.test(s))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 a=t.decodedCalldata??t.decodedAction;if(a==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let c=String(Ut(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Nc.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=Pc(d?t.policyChecks:[]),m=Bc(t.simulation),f=Dc(t.assetDeltas),p=Fc(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 a=="string"?a:a.method??a.action??a.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:bt(t.spender,"spender")},prepareHash:s,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:c,data:c,selector:c.length>=10?c.slice(0,10):null,value:$e(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:$e(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:$e(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:l,allowlistHits:w,assetDeltas:f,approvalDeltas:p,summary:S};return Do(A)}var Tc,Nc,Cc,_c,Rc,Lc,wr,jo=on(()=>{Tc=/^0x[0-9a-f]{40}$/,Nc=/^0x(?:[0-9a-f]{2})*$/,Cc=/^(?:0x)?[0-9a-f]{64}$/,_c=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Rc=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,Lc=new Set([12,15,18,21,24]),wr=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}}});import{createHash as dl,createHmac as xg,timingSafeEqual as Sg}from"node:crypto";function pl(e){let t=e==null||e===""?An:Number(e);return!Number.isFinite(t)||t<0?An:Math.min(t,hi)}function vn(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(vn).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${vn(e[r])}`).join(",")}}`}function ml(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function wl(e){let t=ml(e);return dl("sha256").update(vn(t)).digest("hex")}function gi(e,{maxAgeMs:t=An,nowMs:r=Date.now(),providers:n=null,kinds:o=null,label:i="operator"}={}){if(!e||typeof e!="object")throw new Error(`${i}: prepared envelope object required`);if(e.oraclePrepared!==!0)throw new Error(`${i}: prepared integrity envelope missing \u2014 use an @oracle-agent/oracle prepare result`);if(Number(e.prepareVersion)!==fl)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=wl(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let u=Number(e.preparedAt),a=Number(e.expiresAt),c=pl(t),d=r-u,l=a-u;if(!Number.isFinite(d)||!Number.isFinite(a)||!Number.isFinite(l)||d<0||l<=0||l>hi||d>c||r>=a)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${c})`);if(n&&!new Set(n).has(e.provider))throw new Error(`${i}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${i}: kind ${e.kind} not allowed here`);return!0}var fl,An,hi,Er=on(()=>{fl=2,An=300*1e3,hi=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});Lo();import aw from"node:path";import Ka from"node:fs";import re from"node:path";import Lm from"node:os";import{createHash as $m,randomBytes as Pm}from"node:crypto";import{execFileSync as Bm}from"node:child_process";import{fileURLToPath as Dm}from"node:url";import{Interface as Co,keccak256 as Fm}from"ethers";import{Transaction as Io}from"@scure/btc-signer";import{ed25519 as jm}from"@noble/curves/ed25519.js";import fd from"node:http";import{timingSafeEqual as pd}from"node:crypto";import{Interface as Ac,MaxUint256 as vc,isAddress as Ic,keccak256 as Zw,toUtf8Bytes as Qw}from"ethers";import{Interface as xc,isAddress as Lw}from"ethers";import{isAddress as Ow}from"ethers";import{createHash as fc,createHmac as pc,timingSafeEqual as mc}from"node:crypto";import{readFileSync as cc}from"node:fs";import{homedir as uc}from"node:os";import{join as mr}from"node:path";function lc(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let r=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return r?[r]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),t=uc();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||mr(t,".config","oracle")).trim();return[e,mr(r,"exec.env")].filter(Boolean)}return[e,mr(t,".config","oracle","exec.env"),mr(t,".config","mad-desk","exec.env")].filter(Boolean)}function zt(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of lc())try{let i=cc(o,"utf8"),s=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(s&&(n=s[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}function yt(e,t,r="guard"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${r}: current time must be a finite number (got ${dc(t)})`);let n=t,o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${r} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function dc(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var $o=100;function sn(e){return Array.isArray(e)?`[${e.map(sn).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${sn(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function wc(e,{required:t=!1}={}){try{return zt(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function hc(e){let{signature:t,...r}=e;return r}function gc(e){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<10||t.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return fc("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function yc(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:mc(r,n)}function bc(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=t.length;i+=64)n.push(t.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(r){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function an(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:i,requireSigned:s=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let u=wc(o,{required:s});if(s&&!u)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(u){let p=pc("sha256",u).update(sn(hc(e))).digest("hex");if(!yc(e.signature,p))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let a=Number(e.selectedBps),c=Number(e.capBps);if(!Number.isInteger(a)||a<0||a>$o)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(c)||c<0||c>$o||a>c)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{yt({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},t,"auto-slippage quote")}catch(p){throw new Error(`${p.message}; re-quote before signing`)}if(r!=null&&Number(e.chainId)!==Number(r))throw new Error("auto-slippage guard chain mismatch");if(n&&String(e.venue).toLowerCase()!==String(n).toLowerCase())throw new Error("auto-slippage guard venue mismatch");let d=BigInt(e.quoteAmountOut??0),l=BigInt(e.minAmountOut??0);if(d<=0n||l<=0n)throw new Error("auto-slippage guard amounts must be positive");let m=d*BigInt(1e4-a),f=m/10000n;if(m%10000n!==0n&&(f+=1n),l<f)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let p=bc(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==gc(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(p!=null&&p!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is hash-bound but the calldata encodes ${p}, not the guard floor ${e.minAmountOut}`)}else{if(p==null){let w=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${w}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(p!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${p}`)}}return!0}var Dw=new xc(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Sc,isAddress as Mw}from"ethers";var Uw=new Sc(["function approve(address spender,uint256 amount) returns (bool)"]),Ww=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function W(e,t="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${t} must be a number or decimal string`);return e}throw new Error(`${t} must be a number or decimal string`)}function ne(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function ae(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let r=W(e,t);if(r==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(r)}`)}}function de(e,t="amount"){let r=ae(e,t);if(r<=0n)throw new Error(`${t} must be positive`);return r}function q(e,t,r="amount"){let n=W(e,r);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${r} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[s="0",u=""]=i.split(".");if(u.length>t)throw new Error(`${r} has more than ${t} decimal places, which would lose precision`);let a=BigInt((s||"0")+u.padEnd(t,"0"));return o?-a:a}var ih=new Ac(["function approve(address spender,uint256 amount) returns (bool)"]);function Po(e,t){let r=String(e||"").trim();if(!Ic(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function kc(e,t="approval amount",{allowZero:r=!1}={}){let n=ae(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=vc)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var Bo=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),Oc=new Set(["0x39509351","0xf9255c1f"]);function oe(e){let t=String(e||"").toLowerCase();return t.length<10?!1:Bo.has(t.slice(0,10))}function Le(e){if(!oe(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=c=>n[c]?"0x"+n[c].slice(24):null,i=c=>n[c]?BigInt("0x"+n[c]):null,s=null,u=null,a=null;switch(r){case"0x095ea7b3":case"0x39509351":s=o(0),u=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":a=o(0),s=o(1),u=i(2);break;case"0xd505accf":s=o(1),u=i(2);break;case"0x8fcbaf0c":{s=o(1),u=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":a=o(0),s=o(1),u=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(s==null||u==null)throw new Error("invalid approve calldata");return{spender:Po(s,"approval spender"),token:a==null?null:Po(a,"approval token"),amount:kc(u,"approval amount",{allowZero:!0}),selector:r,additive:Oc.has(r)}}jo();import{readFileSync as jc,readdirSync as Mc,existsSync as Ho}from"node:fs";import{dirname as qc,join as Et}from"node:path";import{fileURLToPath as Hc}from"node:url";var Wt=qc(Hc(import.meta.url));function zc(){let e=[Et(Wt,"descriptors"),Et(Wt,"clear-sign","descriptors"),Et(Wt,"..","clear-sign","descriptors"),Et(Wt,"..","..","clear-sign","descriptors"),Et(Wt,"..","..","..","clear-sign","descriptors")];for(let t of e)if(Ho(t))return t;return e[0]}var Uc=zc(),Wc=/^0x[0-9a-f]{8}/,Vc=/^0x[0-9a-fA-F]{40}$/;function Kc(e=Uc){if(!Ho(e))return[];let t=[];for(let r of Mc(e).filter(n=>n.endsWith(".json")).sort()){let n=jc(Et(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 Jc(e,{to:t=null,chainId:r=null}={},n=Kc()){let o=String(e||"").toLowerCase(),i=Wc.test(o)?o.slice(0,10):null;if(!i)return null;let s=t&&Vc.test(String(t))?String(t).toLowerCase():null;for(let{file:u,doc:a}of n){let c=a?.display?.formats||{};for(let[d,l]of Object.entries(c)){if(String(l?.$selector||"").toLowerCase()!==i)continue;let m=a?.context?.contract?.deployments||[],f=m.length===0,p=m.some(w=>(r==null||Number(w.chainId)===Number(r))&&s&&String(w.address||"").toLowerCase()===s);if(f||p)return{file:u,signature:d,format:l,doc:a,selector:i,generic:f}}}return null}function zo(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function Gc(e,t){let r=zo(e,t);return r?`0x${r.slice(24)}`:null}function Mo(e,t){let r=zo(e,t);return r?BigInt(`0x${r}`).toString():null}var Yc=(1n<<256n)-1n;function qo(e){if(e==null)return"unknown";let t=BigInt(e);return t>=Yc/2n?"UNLIMITED":t.toString()}function Uo(e,{to:t=null,chainId:r=null}={},n=void 0){let o=Jc(e,{to:t,chainId:r},n);if(!o)return null;let i=String(e||"").toLowerCase(),s=i.slice(10),u=[],a=[];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"?Gc(s,d):c.format==="amount"||c.format==="tokenAmount"?qo(Mo(s,d)):Mo(s,d)),l!=null&&(a.push({label:c.label,value:l}),u.push(`${c.label}: ${l}`))}if(oe(i)){let c=null,d=null;try{c=Le(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=a.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=a.find(p=>/amount|allowance/i.test(p.label))?.value,f=qo(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:a,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:a,lines:u}}var Xc=/^0x[0-9a-f]{40}$/;function Vt(e){let t=String(e??"").toLowerCase();return Xc.test(t)?t:null}function Zc(e,{token:t,owner:r}){if(!oe(e))return[];let n;try{n=Le(e)}catch{return[]}let o={token:Vt(n.token??t),spender:Vt(n.spender),owner:Vt(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Qc(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||{},s=Vt(n?.owner??i.from),u=Vt(i.to??n?.destination),a=String(i.data??"0x").toLowerCase();if(!s||!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 Fo({chainId:i.chainId,account:s,destination:u,calldata:a,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:Zc(a,{token:u,owner:s})})}catch{return null}}function Wo(e,t,r={}){let n=Qc(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||{},s=Uo(String(i.data??"0x"),{to:i.to??null,chainId:i.chainId??null});if(s?.ok){o.push(`CLEAR-SIGN intent=${s.intent} [${s.descriptor}]`);for(let u of s.lines)o.push(`CLEAR-SIGN ${u}`)}else s&&s.refused&&o.push(`CLEAR-SIGN REFUSED: ${s.refused}`)}catch{}return o}import{createHash as Vo}from"node:crypto";import{Address as eu,NETWORK as tu,OutScript as Ko,RawTx as ru,SigHash as Jo,TEST_NETWORK as nu,Transaction as ou}from"@scure/btc-signer";var Go=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},iu=(e,t)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${t}`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`envelope: invalid ${t}`);return r},su=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,au=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),tt=e=>au(e)?String(e).toLowerCase():String(e),ln=(e,t)=>Array.isArray(t)&&t.some(r=>tt(r)===tt(e)),cu=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function uu(e){let t=Buffer.from(ru.encode(e)),r=Vo("sha256").update(t).digest();return Buffer.from(Vo("sha256").update(r).digest()).reverse().toString("hex")}function lu(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(uu(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))throw new Error("envelope: Bitcoin prevout txid mismatch");let t=e.nonWitnessUtxo.outputs?.[e.index];if(!t)throw new Error("envelope: Bitcoin prevout output missing");if(!e.witnessUtxo)throw new Error("envelope: PSBT input witness UTXO required");if(BigInt(e.witnessUtxo.amount)!==BigInt(t.amount)||!cu(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function dn(e,t){if(e.action!=="transfer")throw new Error("envelope: BTC decoder requires transfer action");let r=e?.artifact;if(Object.keys(r).some(l=>!["network","psbt"].includes(l)))throw new Error("envelope: unexpected BTC artifact field");if(!ln(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?tu:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?nu:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=ou.fromPSBT(iu(r.psbt,"PSBT"))}catch(l){throw new Error(`envelope: invalid PSBT: ${l?.message||l}`)}if(o.inputsLength===0||o.outputsLength===0)throw new Error("envelope: PSBT inputs and outputs required");let i=eu(n);for(let l=0;l<o.inputsLength;l++){let m=o.getInput(l);for(let w of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(su(m[w]))throw new Error("envelope: signed or finalized PSBT refused");if(m.sighashType!==void 0&&m.sighashType!==Jo.DEFAULT&&m.sighashType!==Jo.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let f=lu(m),p;try{let w=Ko.decode(f.script);if(!["wpkh"].includes(w.type))throw new Error("unsupported input");p=i.encode(w)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!ln(p,t.owners)||tt(p)!==tt(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let s=new Set([e.owner,...t.changeAddresses||[]].map(l=>tt(l))),u=0n,a=!1,c=[];for(let l=0;l<o.outputsLength;l++){let m=o.getOutput(l),f;try{f=i.encode(Ko.decode(m.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let p=tt(f);if(c.push(`${f}:${m.amount}`),p===tt(e.destination)){a=!0,u+=m.amount;continue}if(ln(f,t.destinations)){u+=m.amount;continue}if(!s.has(p))throw new Error("policy: Bitcoin output destination not allowed")}if(!a)throw new Error("envelope: Bitcoin destination mismatch");let d;try{d=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(d<0n||d>Go(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(u>Go(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:u.toString(),notional:(u+d).toString(),fee:d.toString(),outputs:Object.freeze(c)})}function fn(e,t){let{unit:r,value:n,notional:o,fee:i}=dn(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as mn}from"node:crypto";import{base58 as ti}from"@scure/base";import{getCompiledTransactionMessageDecoder as du}from"@solana/transaction-messages";var yr="11111111111111111111111111111111",ri="ComputeBudget111111111111111111111111111111",fu="So11111111111111111111111111111111111111112",ni="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var oi="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",pu=5000n,mu=2039280n,wu=37095705934669439343138083508754565189542113879843219016388785533085940283555n,Z=57896044618658097711785492504343953926634992332820282019728792003956564819949n,Yo=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Xo=e=>mn("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),hu=new Map([[Xo("route"),{name:"route",prefixBytes:0}],[Xo("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),ie=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},gu=(e,t)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${t}`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`envelope: invalid ${t}`);return r},me=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),H=e=>String(e||""),yu=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,gr=e=>mn("sha256").update(e).digest("hex");function hr(e,t){try{let r=Buffer.from(ti.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function fe(e){let t=e%Z;return t>=0n?t:Z+t}function ve(e,t){let r=e;for(;t-- >0n;)r=r*r%Z;return r}function bu(e){let r=e*e%Z*e%Z,n=ve(r,2n)*r%Z,o=ve(n,1n)*e%Z,i=ve(o,5n)*o%Z,s=ve(i,10n)*i%Z,u=ve(s,20n)*s%Z,a=ve(u,40n)*u%Z,c=ve(a,80n)*a%Z,d=ve(c,80n)*a%Z,l=ve(d,10n)*i%Z;return ve(l,2n)*e%Z}function Eu(e,t){let r=fe(t*t*t),n=fe(r*r*t),o=bu(e*n),i=fe(e*r*o),s=fe(t*i*i),u=i,a=fe(i*Yo),c=s===e,d=s===fe(-e),l=s===fe(-e*Yo);return c&&(i=u),(d||l)&&(i=a),(fe(i)&1n)===1n&&(i=fe(-i)),!c&&!d?null:i}function xu(e){if(!e||e.length!==32)return!1;let t=0n;for(let o=31;o>=0;o--)t=(t<<8n)+BigInt(o===31?e[o]&127:e[o]);let r=fe(t*t),n=Eu(fe(r-1n),fe(wu*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function Su(e,t){let r=Buffer.concat([...e,hr(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=mn("sha256").update(r).digest();if(xu(n))throw new Error("envelope: derived Solana program address is on curve");return ti.encode(n)}function wn(e,t,r=ni){let n=[hr(e,"owner"),hr(r,"token program"),hr(t,"mint")];for(let o=255;o>=0;o--)try{return Su([...n,Buffer.from([o])],oi)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function Au(e,t){return(t.accountIndices||[]).map(r=>H(e.staticAccounts[r]))}function Kt(e){return Buffer.from(e.data||[])}function vu(e,t){return H(e.staticAccounts[t.programAddressIndex])}function ii(e,t){return Number(t)<e.header.numSignerAccounts}function Iu(e,t){let r=e.header.numSignerAccounts,n=e.header.numReadonlySignerAccounts,o=e.header.numReadonlyNonSignerAccounts,i=e.staticAccounts.length;return Number(t)<r?Number(t)<r-n:Number(t)<i-o}function Jt(e){return e.accountIndices||[]}function pn(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function Zo(e,t){let r=Jt(t).map(n=>{let o=ii(e,n)?"s":"n",i=Iu(e,n)?"w":"r";return`${n}:${H(e.staticAccounts[n])}:${o}:${i}`});return gr(Buffer.from(r.join(`
2
- `)))}function Qo(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function ku(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function Ou(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function Tu(e,t,r){let n=r.maxJupiterRoutePlanSteps===void 0?1:Number(r.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(t<1||t>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(r.jupiterRouteVariants)?r.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=r.jupiterRouteVariantPayloadBytes||{},s=0,u=0,a=[];for(let c=0;c<t;c++){if(s>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e[s++];if(!o.includes(d))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(d)))throw new Error("policy: Jupiter route variant payload size required");let l=Number(i[String(d)]);if(!Number.isSafeInteger(l)||l<0||l>16)throw new Error("policy: Jupiter route variant payload size invalid");if(s+l+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let m=e.subarray(s,s+l);s+=l;let f=m.toString("hex"),p=r.jupiterRouteVariantPayloads?.[String(d)];if(!Array.isArray(p)||!p.map(String).includes(f))throw new Error("policy: Jupiter route variant payload not allowed");let w=e[s++],g=e[s++],h=e[s++];if(w<1||w>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(g!==c||h!==c+1)throw new Error("envelope: unsupported Jupiter route-plan token index");u+=w,a.push(Object.freeze({swapVariant:d,variantPayloadHex:f,percent:w,inputIndex:g,outputIndex:h}))}if(s!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(u!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(a)}function Nu(e,t){let r=Kt({data:e}),n=r.subarray(0,8).toString("hex"),o=hu.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,s=o.prefixBytes===1?r[8]:null;if(o.prefixBytes===1&&r.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let u=8+o.prefixBytes,a=u+4,c=r.length-i;if(c<=a)throw new Error("envelope: malformed Jupiter route payload");let d=Ou(r,u,"route plan length"),l=r.subarray(a,c),m=Tu(l,d,t);return Object.freeze({instruction:o.name,routeId:s,routePlanSteps:d,routePlan:m,routePlanHash:gr(l),inAmount:Qo(r,c,"in_amount"),quotedOutAmount:Qo(r,c+8,"quoted_out_amount"),slippageBps:ku(r,c+16,"slippage_bps"),platformFeeBps:r[c+18],instructionHash:gr(r)})}function Cu(e,t,r){let n=Au(e,t),o=(i,s)=>{let u=n[i];if(!u)throw new Error(`envelope: Jupiter ${s} account missing`);return u};if(r.instruction==="route"){if(n.length<9)throw new Error("envelope: Jupiter route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),userTransferAuthority:o(1,"userTransferAuthority"),userSourceTokenAccount:o(2,"userSourceTokenAccount"),userDestinationTokenAccount:o(3,"userDestinationTokenAccount"),destinationTokenAccount:o(4,"destinationTokenAccount"),destinationMint:o(5,"destinationMint"),platformFeeAccount:o(6,"platformFeeAccount"),eventAuthority:o(7,"eventAuthority"),program:o(8,"program")}}if(r.instruction==="shared_accounts_route"){if(n.length<13)throw new Error("envelope: Jupiter shared route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),programAuthority:o(1,"programAuthority"),userTransferAuthority:o(2,"userTransferAuthority"),userSourceTokenAccount:o(3,"sourceTokenAccount"),programSourceTokenAccount:o(4,"programSourceTokenAccount"),programDestinationTokenAccount:o(5,"programDestinationTokenAccount"),userDestinationTokenAccount:o(6,"destinationTokenAccount"),sourceMint:o(7,"sourceMint"),destinationMint:o(8,"destinationMint"),platformFeeAccount:o(9,"platformFeeAccount"),token2022Program:o(10,"token2022Program"),eventAuthority:o(11,"eventAuthority"),program:o(12,"program")}}throw new Error("envelope: unsupported Jupiter account layout")}function ei(e,t){return e&&e!==t?e:null}function pe(e,t,r){let n=H(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function _u(e,t){let r=Kt(e);if(r.length===5&&r[0]===2){let n=r.readUInt32LE(1),o=t.maxComputeUnits===void 0?14e5:Number(t.maxComputeUnits);if(!Number.isSafeInteger(o)||o<=0)throw new Error("policy: maxComputeUnits must be positive");if(n>o)throw new Error("policy: Jupiter compute unit limit exceeds cap");return 0n}throw r.length===9&&r[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function Ru(e,t,r,n,o,i){let s=Kt(t);if(s.length!==1||s[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let u=Jt(t);if(u.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let a=pe(e,u[0],"ATA payer"),c=pe(e,u[1],"ATA account"),d=pe(e,u[2],"ATA owner"),l=pe(e,u[3],"ATA mint"),m=pe(e,u[4],"ATA system program"),f=pe(e,u[5],"ATA token program");if(a!==r.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(d!==r.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(m!==yr)throw new Error("envelope: Jupiter ATA system program mismatch");if(f!==o)throw new Error("envelope: Jupiter ATA token program mismatch");if(l!==n.inputMint&&l!==n.outputMint)throw new Error("envelope: Jupiter ATA mint mismatch");if(c!==wn(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:c,debit:i}}function Lu(e,t,r,n,o){let i=Jt(t),s=Kt(t);if(i.length!==2||s.length!==12||s.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let u=pe(e,i[0],"wrap payer"),a=pe(e,i[1],"wrap target"),c=s.readBigUInt64LE(4);if(u!==r.owner||a!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(c!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return c}function $u(e,t,r,n){let o=Jt(t),i=Kt(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||pe(e,o[0],"syncNative account")!==n)throw new Error("envelope: Jupiter syncNative account mismatch");return{kind:"syncNative"}}if(i[0]===9){if(o.length!==3)throw new Error("envelope: malformed Jupiter closeAccount helper");let s=pe(e,o[0],"closeAccount source"),u=pe(e,o[1],"closeAccount destination"),a=pe(e,o[2],"closeAccount authority");if(s!==n||u!==r.owner||a!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function Pu(e,t,r,n,o,i,s){let u=wn(t.owner,t.artifact.inputMint,s);if(o.userSourceTokenAccount!==u)throw new Error("envelope: Jupiter source token account is not owner ATA");let a=ie(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(a<mu)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let c=new Map,d=0n,l=!1,m=!1;for(let f of e.instructions){if(f===n)continue;let p=vu(e,f);if(p===ri)_u(f,r);else if(p===oi){let{ata:w,debit:g}=Ru(e,f,t,t.artifact,s,a);c.set(w,g)}else if(p===yr)d+=Lu(e,f,t,u,i);else if(p===s){let w=$u(e,f,t,u);w.kind==="syncNative"&&(l=!0),w.kind==="closeAccount"&&(m=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(d>0n&&(!l||!m))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(d!==0n&&d!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...c.values()].reduce((f,p)=>f+p,0n)}function Bu(e){let t;try{t=du().decode(gu(e.messageBase64,"Solana message"))}catch(r){throw new Error(`envelope: invalid Solana message: ${r?.message||r}`)}if(t.version!=="legacy"&&Array.isArray(t.addressTableLookups)&&t.addressTableLookups.length)throw new Error("envelope: unresolved Solana address tables refused");return t}function Du(e,t,r,n=1){if(e.header.numSignerAccounts!==n||H(e.staticAccounts[0])!==t.owner||!me(t.owner,r.owners))throw new Error("envelope: Solana owner mismatch");if(!Array.isArray(e.instructions)||e.instructions.length===0)throw new Error("envelope: Solana instructions required");let o=[];for(let i of e.instructions){let s=H(e.staticAccounts[i.programAddressIndex]);if(!s||!me(s,r.programs))throw new Error("policy: Solana program not allowed");o.push(s)}return o}function Fu(e,t,r){let n=ie(r.lamportsPerSignature,"lamportsPerSignature");if(n<pu)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:ie(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),s=i*n,u=i*o;if(t.exactFeeLamports!==void 0){let c=ie(t.exactFeeLamports,"exactFeeLamports");if(c<s)throw new Error("policy: Solana exact fee below the base signature fee");if(c>u)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let a=u;if(a>ie(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return a}function ju(e,t,r,n){let o=0n,i=!1;for(let s of e.instructions){if(H(e.staticAccounts[s.programAddressIndex])!==yr)throw new Error("envelope: unsupported Solana program decoder");let a=s.accountIndices||[];if(a.length!==2||H(e.staticAccounts[a[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let c=H(e.staticAccounts[a[1]]);if(c!==t.destination||!me(c,r.destinations))throw new Error("envelope: Solana destination mismatch");let d=Buffer.from(s.data||[]);if(d.length!==12||d.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=d.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>ie(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function Mu(e,t,r,n){let o=t.artifact,i=H(o.mintProgram);if(!me(i,r.solMintPrograms))throw new Error("policy: Solana mint program not allowed");let s=e.header.numSignerAccounts;if(s!==2&&s!==3)throw new Error("envelope: Solana mint requires the payer, asset, and at most one distinct minter");let u=H(e.staticAccounts[s-1]);if(u!==H(o.assetSigner))throw new Error("envelope: Solana mint asset signer mismatch");if(s===3){let l=H(e.staticAccounts[1]);if(!o.minter||l!==H(o.minter))throw new Error("envelope: Solana mint minter mismatch");if(l===u)throw new Error("envelope: Solana mint minter must not be the asset signer")}else if(o.minter&&H(o.minter)!==t.owner)throw new Error("envelope: Solana mint declares a minter the message does not sign");if(me(u,r.owners))throw new Error("envelope: Solana mint asset signer must not be a policy owner");let a=ie(o.maxSpendLamports,"maxSpendLamports");if(a>ie(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana mint spend exceeds cap");let c=0n,d=!1;for(let l of e.instructions){let m=H(e.staticAccounts[l.programAddressIndex]);if(m!==ri){if(m===yr){let f=l.accountIndices||[];if(f.length!==2||H(e.staticAccounts[f[0]])!==t.owner)throw new Error("envelope: Solana mint transfer owner mismatch");let p=H(e.staticAccounts[f[1]]);if(!me(p,r.destinations))throw new Error("envelope: Solana mint destination mismatch");let w=Buffer.from(l.data||[]);if(w.length!==12||w.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");c+=w.readBigUInt64LE(4);continue}if(m!==i)throw new Error("envelope: unsupported Solana program decoder");d=!0}}if(!d)throw new Error("envelope: Solana mint instruction required");if(c>a)throw new Error("policy: Solana mint visible spend exceeds the declared maximum");return{value:a,programs:n,unverifiableProgramSpend:!0,visibleSpendLamports:c.toString()}}function qu(e,t,r,n){let o=t.artifact;if(o.provider!=="jupiter")throw new Error("envelope: Solana swap provider must be jupiter");if(o.inputMint!==fu)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!me(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=yu(r);if(!me(o.inputMint,i)||!me(o.outputMint,i))throw new Error("policy: Solana token not allowed");let s=ie(o.inAmount,"inAmount"),u=ie(o.outAmount,"outAmount"),a=ie(o.otherAmountThreshold,"otherAmountThreshold");if(s<=0n||s>ie(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(s>ie(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(u<=0n||a<=0n||a>u)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let c=H(o.jupiterProgram);if(!c||!me(c,r.programs)||!n.includes(c))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(v=>H(e.staticAccounts[v.programAddressIndex])===c);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=d[0],m=Nu(l.data,r);if(m.instruction==="shared_accounts_route"){let v=Array.isArray(r.jupiterSharedRouteIds)?r.jupiterSharedRouteIds.map(Number):[];if(!v.length)throw new Error("policy: Jupiter shared route id allowlist required");if(!v.includes(Number(m.routeId)))throw new Error("policy: Jupiter shared route id not allowed")}else if(m.routeId!=null)throw new Error("envelope: unexpected Jupiter shared route id");if(!pn(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(m.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(m.inAmount!==s)throw new Error("envelope: Jupiter route in_amount mismatch");if(m.quotedOutAmount!==u)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(m.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let f=m.quotedOutAmount-m.quotedOutAmount*BigInt(m.slippageBps)/10000n;if(a!==f)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(m.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let p=Cu(e,l,m),w=Jt(l),g=m.instruction==="shared_accounts_route"?2:1;if(!ii(e,w[g]))throw new Error("envelope: Jupiter transfer authority must be signer");if(p.program!==c)throw new Error("envelope: Jupiter program account mismatch");if(p.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(p.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(p.sourceMint!==void 0&&p.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let h=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[ni];if(!me(p.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let y=wn(t.owner,o.outputMint,p.tokenProgram);if(p.userDestinationTokenAccount!==y)throw new Error("envelope: Jupiter destination token account is not owner ATA");let b=ei(p.destinationTokenAccount,c);if(b&&b!==y)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(ei(p.platformFeeAccount,c))throw new Error("policy: Jupiter platform fee account not allowed");if(!pn(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(Zo(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let S=gr(Buffer.from([m.instruction,m.routeId??"",m.routePlanHash,Zo(e,l)].join(`
3
- `)));if(!pn(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(S))throw new Error("policy: Jupiter route review hash not allowed");let A=Pu(e,t,r,l,p,s,p.tokenProgram),k=s+A;if(k>ie(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:k,programs:n}}function hn(e,t){if(e.action!=="transfer"&&e.action!=="swap"&&e.action!=="mint")throw new Error("envelope: Solana decoder requires transfer, swap, or mint action");let r=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:e.action==="mint"?["cluster","messageBase64","exactFeeLamports","mintProgram","assetSigner","maxSpendLamports","minter","cosignatures"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(r||{}).some(a=>!n.includes(a)))throw new Error("envelope: unexpected Solana artifact field");if(!me(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=Bu(r),i=Du(o,e,t,e.action==="mint"?o.header.numSignerAccounts:1),s=e.action==="transfer"?ju(o,e,t,i):e.action==="mint"?Mu(o,e,t,i):qu(o,e,t,i),u=Fu(o,r,t);return Object.freeze({unit:"lamports",value:s.value.toString(),notional:(s.value+u).toString(),fee:u.toString(),programs:Object.freeze(s.programs),...s.unverifiableProgramSpend?{unverifiableProgramSpend:!0,visibleSpendLamports:s.visibleSpendLamports}:{}})}function gn(e,t){let{unit:r,value:n,notional:o,fee:i,unverifiableProgramSpend:s,visibleSpendLamports:u}=hn(e,t);return Object.freeze(s?{unit:r,value:n,notional:o,fee:i,unverifiableProgramSpend:s,visibleSpendLamports:u}:{unit:r,value:n,notional:o,fee:i})}import{AsyncLocalStorage as Hu}from"node:async_hooks";var Ih=new Hu;var Ph=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Bh=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Dh=AbortSignal.prototype.throwIfAborted,Fh=EventTarget.prototype.addEventListener,jh=EventTarget.prototype.removeEventListener,Mh=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null;var qh=64*1024,Hh=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});var Uu=1e8;var Zh=Object.freeze({tradexyz:"xyz",ventuals:"vntl",hypernova:"hyna",paradex:"para",entropy:"io",entropyio:"io"});function yn(e){if(typeof e!="string"||!/^#(?:0|[1-9]\d*)$/.test(e))return null;let t=Number(e.slice(1));if(!Number.isSafeInteger(t)||t<0)return null;let r=t%10;if(r!==0&&r!==1)return null;let n=Math.floor(t/10),o=Uu+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var Wu=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),Vu=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),Ku=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),Ju=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"}),Ve=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function Gu(e,t){let r=e.toString().padStart(t+1,"0");if(t===0)return r;let n=r.slice(0,-t),o=r.slice(-t).replace(/0+$/,"");return o?`${n}.${o}`:n}function si(e,t){let r=W(e,`hl: ${t}`);if(!/^\d+(?:\.\d+)?$/.test(r))throw new Error(`hl: ${t} must be a positive decimal`);let[n,o=""]=r.split("."),i=BigInt(n+o);if(i<=0n)throw new Error(`hl: ${t} must be positive`);return{raw:i,decimals:o.length}}function Ie(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`hl: ${t} must be finite JSON`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(n=>Ie(n,t)).join(",")}]`;if(!e||typeof e!="object")throw new Error(`hl: ${t} must be structured JSON`);return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Ie(e[n],t)}`).join(",")}}`}function Yu(e){if(typeof e.orderType!="string"||!e.orderType)throw new Error("hl: order type must be a string");let t=e.orderType,r=e.orderWire;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: declared order wire required");if(t==="limit"){let i=r.limit?.tif;if(!["Gtc","Ioc","Alo"].includes(i)||Ie(r,"declared order type")!==Ie({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(Ie(r,"declared order type")!==Ie({limit:{tif:"Ioc"}},"expected order type"))throw new Error("hl: market order type must match its IOC wire shape");return}let n={stopMarket:{isMarket:!0,tpsl:"sl"},stopLimit:{isMarket:!1,tpsl:"sl"},takeProfitMarket:{isMarket:!0,tpsl:"tp"},takeProfitLimit:{isMarket:!1,tpsl:"tp"}}[t];if(!n)throw new Error("hl: unsupported declared order type");let o=r.trigger?.triggerPx;if(o==null||Ie(r,"declared order type")!==Ie({trigger:{isMarket:n.isMarket,triggerPx:o,tpsl:n.tpsl}},"expected order type"))throw new Error("hl: trigger order type must match its wire shape")}function Xu(e,t,r){let n=si(e.s,"signed size"),o=si(e.p,"signed price"),i=n.decimals+o.decimals,s=n.raw*o.raw,u=q(t.notionalUsd,i,"hl: notionalUsd");if(u<=0n||s!==u)throw new Error("hl: signed notional must match");let a=q(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>a)throw new Error("hl: notional exceeds cap")}function Zu(e,t){let r=e.action.builder;if(r==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: signed order builder must be structured");let n=Ve(r.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(ne(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(u=>String(u).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=ae(r.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let s=q(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function ai(e,t,r){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(t.side==="buy"))throw new Error("hl: signed side must match exactly");if(W(e.s,"hl: signed size")!==W(t.size,"hl: size"))throw new Error("hl: signed size must match");if(W(e.p,"hl: signed price")!==W(t.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof t.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==t.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(Ie(e.t,"signed order type")!==Ie(t.orderWire,"declared order type"))throw new Error("hl: signed order type must match declared order type");let n=Object.prototype.hasOwnProperty.call(e,"c");if(t.clientOrderId==null){if(n)throw new Error("hl: undeclared signed client order id")}else if(!n||typeof e.c!="string"||e.c!==t.clientOrderId)throw new Error("hl: signed client order id must match")}function ci(e,t,r,n,o){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(t.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(W(e.s,"hl: bracket protection size")!==W(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(W(e.p,"hl: bracket protection price")!==W(n,"hl: protection price"))throw new Error("hl: bracket protection price must match");if(e.r!==!0)throw new Error("hl: bracket protection must be reduce-only");let i=e.t?.trigger;if(!i||i.isMarket!==!0||i.tpsl!==o)throw new Error("hl: bracket protection trigger must match");if(W(i.triggerPx,"hl: triggerPx")!==W(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function Qu(e){let t=String(e||"").replace(/\/$/,"");if(!Wu.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function bn(e){return yn(e)!=null}function el(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(bn(r)){if(t.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(n.includes(r)||n.includes("#*")||n.includes("*")||n.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(n.length&&!n.includes(r)&&!n.includes("*"))throw new Error("hl: coin not allowed");return!0}function tl(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(s=>{if(typeof s=="string"){let[u,a]=String(s).split(":");return u===e&&Number(a)===t}return String(s?.coin)===e&&Number(s?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(bn(e)){let i=Array.isArray(r.coins)?r.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0)return!0;throw new Error("hl: restricted coin policy requires hlMarkets pairs")}let o=Array.isArray(r.coins)?r.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function Pe(e,t){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: structured artifact required");let n=Ve(r.kind,"kind",48),o=Ku[n];if(!o)throw new Error("hl: unsupported Hyperliquid kind");if(e.action!==o)throw new Error("hl: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="hyperliquid")throw new Error("hl: destination must be hyperliquid");if(!/^0x[0-9a-fA-F]{40}$/.test(String(e.owner||"")))throw new Error("hl: owner required");let i=Qu(r.submitTo);if(Object.prototype.hasOwnProperty.call(r,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let s=Number(r.nonce);if(!Number.isSafeInteger(s)||s<=0)throw new Error("hl: nonce must be a positive integer");if(!r.action||typeof r.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(r.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(r.action.type!==Ju[n])throw new Error("hl: action type must match kind");let u=r.notionalUsd??0;if(Vu.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let a=Ve(r.coin,"coin",64),c=r.assetId??r.assetIndex;if(!Number.isSafeInteger(c)||c<0)throw new Error("hl: assetId required");if(n==="hip4-order"||c>=1e8){let d=yn(a);if(!d||d.coin!==a)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==c)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(el(a,t),tl(a,c,t),n==="hip4-order"&&!bn(a))throw new Error("hl: HIP-4 orders must use an outcome coin");if(n==="perp-order"||n==="hip3-order"||n==="hip4-order"||n==="perp-bracket"){if(r.side!=="buy"&&r.side!=="sell")throw new Error("hl: side must be buy or sell");if(r.action.type!=="order"||!Array.isArray(r.action.orders))throw new Error("hl: signed orders are required");Yu(r);let d=r.action.orders;if(n==="perp-bracket"){let l=r.takeProfitPx,m=r.stopLossPx,f=1+(l==null?0:1)+(m==null?0:1);if(f<2||d.length!==f||r.grouping!=="normalTpsl"||r.action.grouping!==r.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");ai(d[0],r,c);let p=1;l!=null&&ci(d[p++],r,c,l,"tp"),m!=null&&ci(d[p],r,c,m,"sl")}else{if(d.length!==1)throw new Error("hl: exactly one signed order is required");if(r.grouping!=="na"||r.action.grouping!==r.grouping)throw new Error("hl: signed grouping must match declared grouping");ai(d[0],r,c)}Xu(d[0],r,t),Zu(r,t),u=W(r.notionalUsd,"hl: notionalUsd")}if(n==="perp-leverage"){let d=r.leverage;if(!Number.isSafeInteger(d)||d<1)throw new Error("hl: leverage must be a positive integer");let l=t.maxLeverage==null?50:t.maxLeverage;if(typeof l!="number"||!Number.isSafeInteger(l)||l<1)throw new Error("hl: maxLeverage must be a positive integer");if(d>l)throw new Error("hl: leverage exceeds cap")}if(n==="perp-cancel"){let d=r.action.cancels;if(!Array.isArray(d)||d.length!==1)throw new Error("hl: exactly one cancel is required");if(!Number.isSafeInteger(d[0].a)||d[0].a!==c)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(r.orderId)||r.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(d[0].o)||d[0].o!==r.orderId)throw new Error("hl: signed cancel order id must match")}if(n==="perp-leverage"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==c)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(r.action.leverage)||r.action.leverage!==r.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(r.marginMode))throw new Error("hl: declared margin mode required");let d=r.marginMode==="cross";if(typeof r.action.isCross!="boolean"||r.action.isCross!==d)throw new Error("hl: signed isCross must match declared margin mode")}if(n==="perp-isolated-margin"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==c)throw new Error("hl: signed margin asset must match assetId");let d=Ve(r.usd,"margin usd",64),l=q(d,6,"hl: margin usd");if(ae(r.action.ntli,"hl: signed margin ntli")!==l)throw new Error("hl: signed margin amount must match usd");if(typeof r.isBuy!="boolean"||r.action.isBuy!==r.isBuy)throw new Error("hl: signed margin isBuy must match");let f=q(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),p=l<0n?-l:l;if(p>f)throw new Error("hl: margin notional exceeds cap");u=Gu(p,6)}}if(n==="builder-fee-approval"){let a=Ve(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(a))throw new Error("hl: builder address required");if(Ve(r.action.builder,"signed builder",42).toLowerCase()!==a)throw new Error("hl: signed builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(p=>String(p).toLowerCase()):[]).includes(a))throw new Error("hl: builder not allowed");let d=Ve(r.maxFeeRate,"maxFeeRate",32);if(Ve(r.action.maxFeeRate,"signed maxFeeRate",32)!==d)throw new Error("hl: signed builder fee must match");if(!/^\d+(?:\.\d+)?%$/.test(d))throw new Error("hl: builder fee rate must be a percent");let l=q(d.slice(0,-1),12,"hl: builder fee percent"),m=q(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(m<0n||l*100n>m)throw new Error("hl: builder fee exceeds cap");if(Number(r.action.nonce)!==s)throw new Error("hl: signed builder nonce must match");let f=i.includes("testnet")?"Testnet":"Mainnet";if(r.hyperliquidChain!==f||r.action.hyperliquidChain!==r.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(r.signatureChainId!=="0x66eee"||r.action.signatureChainId!==r.signatureChainId)throw new Error("hl: signed signature chain id must match")}if(n.startsWith("hype-stake")||n==="hype-delegate"||n==="hype-undelegate"){if(n==="hype-delegate"||n==="hype-undelegate"){let a=n==="hype-undelegate";if(typeof r.action.isUndelegate!="boolean"||r.action.isUndelegate!==a)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(t.maxHypeWei!=null&&BigInt(String(r.action.wei??r.caps?.amountHype??"0"))>BigInt(t.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(u??r.action.wei??0),notional:String(u??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??u??0),coin:r.coin||null,submitTo:i})}import{createHmac as rl}from"node:crypto";var xt="0x"+"00".repeat(32);function En(e={}){let t=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,r=e.polyApiSecret||process.env.POLYMARKET_API_SECRET||process.env.POLY_API_SECRET,n=e.polyPassphrase||process.env.POLYMARKET_API_PASSPHRASE||process.env.POLY_API_PASSPHRASE;if(!t||!r||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(t),secret:String(r),passphrase:String(n)}}function ui({creds:e,address:t,method:r,path:n,body:o="",nowSec:i}={}){if(!e?.key||!e?.secret||!e?.passphrase)throw new Error("poly: L2 credentials required");if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("poly: L2 address required");let s=String(i??Math.floor(Date.now()/1e3)),u=String(r||"").toUpperCase(),a=String(n||"");if(u!=="POST"||a!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let c=s+u+a+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),m=rl("sha256",l).update(c).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:m,POLY_TIMESTAMP:s,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function nl(e,t){if(e.side!==0&&e.side!==1)throw new Error("poly: side must be BUY or SELL");let r=e.side===0?"BUY":"SELL";if(t&&t!==r)throw new Error("poly: side mismatch");return r}function ol(e){let t=typeof e=="bigint"?e:de(e,"poly: atomicUsdc");if(t<=0n)throw new Error("poly: order amounts must be positive integer micro-units");let r=t/1000000n,n=(t%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return n?`${r.toString()}.${n}`:r.toString()}function li(e,t){let r=de(e.makerAmount,"poly: makerAmount"),n=de(e.takerAmount,"poly: takerAmount");return ol(t==="BUY"?r:n)}function il(e){let t=typeof e=="bigint"?e.toString(10):W(e,"poly: salt");if(!/^[1-9][0-9]*$/.test(t))throw new Error("poly: salt must be a positive integer");let r=BigInt(t);if(r>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("poly: salt exceeds safe integer");return Number(r)}function di({message:e,side:t,signature:r,orderType:n="GTC",apiKey:o}={}){if(!e||typeof e!="object")throw new Error("poly: CLOB v2 message required");if(!String(r||"").startsWith("0x"))throw new Error("poly: EIP-712 signature required");if(n!=="GTC")throw new Error("poly: only GTC is public");if(!o)throw new Error("poly: CLOB owner must be the L2 API key");let i=nl(e,t);if(ne(e.metadata||xt,"poly: metadata").toLowerCase()!==xt)throw new Error("poly: metadata must be zero");if(ne(e.builder||xt,"poly: builder").toLowerCase()!==xt)throw new Error("poly: builder must be zero");let s=il(e.salt);return{deferExec:!1,order:{builder:xt,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:xt,salt:String(s),side:i,signature:r,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var sl=new Set(["https://clob.polymarket.com/order"]),Gt=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),cg=Object.freeze(Gt.map(e=>e[0])),al=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),cl="0xe111180000d2663c0091e4f400237545b87b996b",ul="0xe2222d279d744050d28e00520010520000310f59",fi=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function pi(e){let t=String(e||"").replace(/\/$/,"");if(!sl.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function mi(e){let t=ne(e,"poly: exchange").toLowerCase();if(!al.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function Be(e,t){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("poly: structured artifact required");let n=fi(r.kind,"kind",48);if(n!=="poly-order")throw new Error("poly: unsupported Polymarket kind");if(e.action!=="order")throw new Error("poly: surface/action/kind mismatch");if(ne(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(pi(r.submitTo),r.chainId!==137)throw new Error("poly: chainId must be Polygon 137");let o=r.domain;if(!o||typeof o!="object")throw new Error("poly: EIP-712 domain required");if(o.name!=="Polymarket CTF Exchange"||o.version!=="2"||o.chainId!==137)throw new Error("poly: EIP-712 domain must be official CTF Exchange v2 on Polygon");if(mi(o.verifyingContract),mi(r.exchange),ne(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==ne(r.exchange,"poly: exchange").toLowerCase())throw new Error("poly: exchange/domain mismatch");if(typeof r.negRisk!="boolean")throw new Error("poly: negRisk must be a boolean");let i=r.negRisk?ul:cl;if(ne(r.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let s=r.message||r.value;if(!s||typeof s!="object")throw new Error("poly: signed order message required");let u=r.types?.Order;if(!Array.isArray(u)||u.length!==Gt.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let v=0;v<Gt.length;v+=1)if(u[v]?.name!==Gt[v][0]||u[v]?.type!==Gt[v][1])throw new Error("poly: EIP-712 Order type must be official CLOB v2");if((r.orderType||"GTC")!=="GTC")throw new Error("poly: only GTC is public");let a=String(e.owner||"").toLowerCase();if(ne(s.maker,"poly: maker").toLowerCase()!==a)throw new Error("poly: maker must equal owner");if(ne(s.signer,"poly: signer").toLowerCase()!==a)throw new Error("poly: signer must equal owner");if(s.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof s.builder!="string"||s.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(s.side!==0&&s.side!==1)throw new Error("poly: side must be BUY or SELL");let c=fi(r.tokenId,"tokenId",80);if(ne(s.tokenId,"poly: tokenId")!==c)throw new Error("poly: tokenId mismatch");let d=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(d.length&&!d.includes(c)&&!d.includes("*"))throw new Error("poly: tokenId not allowed");let l=Number(s.side)===0?"BUY":"SELL";if(r.side&&r.side!==l)throw new Error("poly: side mismatch");let m=de(s.makerAmount,"poly: makerAmount"),f=de(s.takerAmount,"poly: takerAmount"),p=de(r.makerAmount,"poly: prepared makerAmount"),w=de(r.takerAmount,"poly: prepared takerAmount");if(m!==p)throw new Error("poly: signed makerAmount differs from prepared envelope");if(f!==w)throw new Error("poly: signed takerAmount differs from prepared envelope");let g=l==="BUY"?m:f,h=l==="BUY"?f:m,y=q(r.quantity,6,"poly: quantity");if(y<=0n||y!==h)throw new Error("poly: quantity must match CLOB v2 amounts");let b=q(r.price,6,"poly: price");if(b<=0n||b>=1000000n)throw new Error("poly: price must be within (0,1)");if(h*b!==g*1000000n)throw new Error("poly: price must match CLOB v2 amounts");if(q(r.notionalUsdc,6,"poly: notionalUsdc")!==g)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let A=li(s,l);if(q(A,6,"poly: displayed notionalUsdc")!==g)throw new Error("poly: displayed notionalUsdc must match CLOB v2 amounts");let k=t.maxNotionalUsd??t.maxNotionalUsdc;if(k!=null){let v=q(k,6,"poly: maxNotionalUsd");if(g>v)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:g.toString(),notional:g.toString(),fee:"0",kind:n,tokenId:c,side:l,makerAmount:m.toString(),takerAmount:f.toString(),price:String(r.price),quantity:String(r.quantity),notionalUsdc:A,submitTo:pi(r.submitTo)})}var ll=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),xn=14,wi=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function St(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function Sn(e){let t=String(e||"").replace(/\/$/,"");if(!ll.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function De(e,t={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("lighter: structured artifact required");let n=wi(r.kind,"kind",48);if(n!=="lighter-order")throw new Error("lighter: unsupported Lighter kind");if(e.action!=="order")throw new Error("lighter: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="lighter")throw new Error("lighter: destination must be lighter");let o=Sn(r.submitTo),i=r.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let s=Number(ae(r.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(s)||s<0)throw new Error("lighter: accountIndex required");let u=Number(ae(r.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(u)||u<0)throw new Error("lighter: clientOrderIndex required");St(r.orderType,0,"orderType"),St(r.timeInForce,1,"timeInForce"),St(r.reduceOnly,0,"reduceOnly"),St(r.triggerPrice,0,"triggerPrice"),St(r.orderExpiry,-1,"orderExpiry");let a=wi(r.symbol||r.coin,"symbol",32),c=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(c.length&&!c.includes(a)&&!c.includes(String(i))&&!c.includes("*"))throw new Error("lighter: market not allowed");if(r.side!=="buy"&&r.side!=="sell")throw new Error("lighter: side must be buy or sell");let d=de(r.baseAmount,"lighter: baseAmount"),l=de(r.price,"lighter: price");if(d>BigInt(Number.MAX_SAFE_INTEGER)||l>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("lighter: baseAmount and price must be safe integers");let m=Number(d),f=Number(l),p=Number(r.sizeDecimals??0),w=Number(r.priceDecimals??0);if(!Number.isInteger(p)||p<0||p>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(w)||w<0||w>12)throw new Error("lighter: priceDecimals required");let g=p+w,h=d*l,y=q(r.notionalUsd,g,"lighter: notionalUsd");if(y<=0n)throw new Error("lighter: notionalUsd required");if(h!==y)throw new Error("lighter: notionalUsd must match size and price");let b=q(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,g,"lighter: maxNotionalUsd");if(h>b)throw new Error("lighter: notional exceeds cap");let S=W(r.notionalUsd,"lighter: notionalUsd");return St(r.txType,xn,"txType"),Object.freeze({unit:"usd",value:String(S),notional:String(S),fee:"0",kind:n,symbol:a,marketIndex:i,side:r.side,baseAmount:m,price:f,submitTo:o,actionType:"create-order",amount:String(S)})}function br(e,t,r,n=null){let o=e?.version===1&&e?.surface?e:null,i=o?.artifact||e||{},s=[`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(s.push(`LEG ${d} chain=${c.chainId??"n/a"} from=${c.from??"n/a"} to=${c.to??"n/a"}`),s.push(`LEG ${d} calldata=${String(c.data||"0x")} value=${c.value??"n/a"}`),s.push(`LEG ${d} gas=${c.gasLimit??"n/a"} maxFeePerGas=${c.maxFeePerGas??c.gasPrice??"n/a"} maxPriorityFeePerGas=${c.maxPriorityFeePerGas??"n/a"}`),s.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=Le(String(c.data||"0x"));s.push(`LEG ${d} APPROVAL token=${l.token||c.to||"n/a"} spender=${l.spender} amount=${l.amount}`)}catch{s.push(`LEG ${d} APPROVAL spender=undecodable amount=undecodable`)}},a=String(i.data||"0x");if(oe(a))try{let c=Le(a);s.push(`APPROVAL token=${c.token||i.to||"n/a"} spender=${c.spender} amount=${c.amount}`)}catch{s.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(i.transactions)&&(s.push(`batchLegs=${i.transactions.length}`),i.transactions.forEach((c,d)=>u(c,d))),o?.surface==="btc"){let c=dn(o,r);s.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(o?.surface==="sol"){let c=hn(o,r);s.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(o?.surface==="hl"){let c=Pe(o,r);s.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=Be(o,r);s.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"&&(s.push(`anvilAction=${o.nftAction} collection=${o.contract} tokenId=${o.tokenId} market=${o.destination}`),s.push(`paymentToken=${o.paymentToken} paymentTokenDecimals=${o.paymentTokenDecimals} maxPaymentTokenAmountRaw=${o.maxPaymentTokenAmountRaw??"n/a"} minPayoutRaw=${o.minPayoutRaw??"n/a"} nativeSwapFeeWei=${o.nativeSwapFeeWei}`),n&&(s.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}`),s.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=De(o,r);s.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
1
+ var on=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};import fr from"node:fs";import rc from"node:os";import gt from"node:path";import{fileURLToPath as nc}from"node:url";function Ro(){return process.env.ORACLE_FAKE_HOME||rc.homedir()}function ic(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function pr(){return ic()?process.env.ORACLE_CONFIG_DIR||gt.join(Ro(),".config","oracle"):gt.join(Ro(),".config","oracle")}function sc(){return gt.join(pr(),"desk.json")}function ac(){return gt.join(pr(),"env")}function ht({force:e=!1}={}){if(ht._done&&!e)return ht._result||null;ht._done=!0;let t={},r=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=ac();if(fr.existsSync(o))for(let i of fr.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let l=s[2];(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),r(s[1],l)}}catch{}try{let o=sc();if(fr.existsSync(o)){let i=JSON.parse(fr.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),ht._result=Object.keys(t).length?t:null,ht._result}var oc,mw,Lo=on(()=>{oc=gt.dirname(nc(import.meta.url)),mw=gt.resolve(oc,"../..");try{ht()}catch{}});function cn(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Rc.test(e)||Lc.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new wr(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)=>cn(o,`${t}[${i}]`,r));et(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(_c.test(i))throw new wr(`${t}.${o}`);e[o]!==void 0&&(n[o]=cn(e[o],`${t}.${o}`,o))}return n}function et(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 Ut(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function bt(e,t){let r=String(Ut(e,t)).toLowerCase();if(!Tc.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function $e(e,t,{positive:r=!1}={}){try{let n=BigInt(Ut(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 ln(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 Do(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Do(t);Object.freeze(e)}return e}function $c(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};et(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:ln(String(n),`${t}.reason`)}}function Pc(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>$c(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 Bc(e){if(e==null)return null;if(et(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:ln(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=$e(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=$e(e.gasLimit,"simulation.gasLimit")),t}function Dc(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)=>{et(t,`assetDeltas[${r}]`);let n=$e(t.before,`assetDeltas[${r}].before`),o=$e(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),s;try{s=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(s!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:ln(String(Ut(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:s}})}function jc(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)=>{et(t,`approvalDeltas[${r}]`);let n=$e(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:bt(t.token,`approvalDeltas[${r}].token`),spender:bt(t.spender,`approvalDeltas[${r}].spender`),owner:bt(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function jo(e={}){et(e,"input");let t=cn(e),r=t.tx==null?t:et(t.tx,"tx"),n=$e(t.chainId??r.chainId,"chainId",{positive:!0}),o=bt(t.account??t.from??r.from,"account/from"),i=bt(t.destination??t.to??r.to,"destination/to"),s=String(Ut(t.prepareHash,"prepareHash")).toLowerCase();if(!Cc.test(s))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let l=t.route??t.venue;if(l==null)throw new TypeError("sign-time review: route/venue required");let a=t.decodedCalldata??t.decodedAction;if(a==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let c=String(Ut(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Nc.test(c))throw new TypeError("sign-time review: calldata/data must be even-length hex");let d=t.policyChecks!==void 0&&t.policyChecks!==null,u=Pc(d?t.policyChecks:[]),m=Bc(t.simulation),f=Dc(t.assetDeltas),p=jc(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||u.failed>0?"BLOCKED":h&&d&&u.checks.length>0&&f!=null?"READY":"UNKNOWN",b=typeof a=="string"?a:a.method??a.action??a.type??"transaction",x=`${y}: review ${b} on chain ${n}; policy ${u.passed} passed, ${u.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:l,venue:t.venue??(typeof l=="string"?l:l.venue??l.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:bt(t.spender,"spender")},prepareHash:s,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:c,data:c,selector:c.length>=10?c.slice(0,10):null,value:$e(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:$e(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:$e(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:u,allowlistHits:w,assetDeltas:f,approvalDeltas:p,summary:x};return Do(A)}var Tc,Nc,Cc,_c,Rc,Lc,wr,Fo=on(()=>{Tc=/^0x[0-9a-f]{40}$/,Nc=/^0x(?:[0-9a-f]{2})*$/,Cc=/^(?:0x)?[0-9a-f]{64}$/,_c=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Rc=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,Lc=new Set([12,15,18,21,24]),wr=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}}});import{createHash as du,createHmac as xg,timingSafeEqual as Sg}from"node:crypto";function pu(e){let t=e==null||e===""?An:Number(e);return!Number.isFinite(t)||t<0?An:Math.min(t,hi)}function vn(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(vn).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${vn(e[r])}`).join(",")}}`}function mu(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function wu(e){let t=mu(e);return du("sha256").update(vn(t)).digest("hex")}function gi(e,{maxAgeMs:t=An,nowMs:r=Date.now(),providers:n=null,kinds:o=null,label:i="operator"}={}){if(!e||typeof e!="object")throw new Error(`${i}: prepared envelope object required`);if(e.oraclePrepared!==!0)throw new Error(`${i}: prepared integrity envelope missing \u2014 use an @oracle-agent/oracle prepare result`);if(Number(e.prepareVersion)!==fu)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=wu(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let l=Number(e.preparedAt),a=Number(e.expiresAt),c=pu(t),d=r-l,u=a-l;if(!Number.isFinite(d)||!Number.isFinite(a)||!Number.isFinite(u)||d<0||u<=0||u>hi||d>c||r>=a)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${c})`);if(n&&!new Set(n).has(e.provider))throw new Error(`${i}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${i}: kind ${e.kind} not allowed here`);return!0}var fu,An,hi,Er=on(()=>{fu=2,An=300*1e3,hi=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});Lo();import aw from"node:path";import Ja from"node:fs";import re from"node:path";import Lm from"node:os";import{createHash as $m,randomBytes as Pm}from"node:crypto";import{execFileSync as Bm}from"node:child_process";import{fileURLToPath as Dm}from"node:url";import{Interface as Co,keccak256 as jm}from"ethers";import{Transaction as Io}from"@scure/btc-signer";import{ed25519 as Fm}from"@noble/curves/ed25519.js";import fd from"node:http";import{timingSafeEqual as pd}from"node:crypto";import{Interface as Ac,MaxUint256 as vc,isAddress as Ic,keccak256 as Zw,toUtf8Bytes as Qw}from"ethers";import{Interface as xc,isAddress as Lw}from"ethers";import{isAddress as Ow}from"ethers";import{createHash as fc,createHmac as pc,timingSafeEqual as mc}from"node:crypto";import{readFileSync as cc}from"node:fs";import{homedir as lc}from"node:os";import{join as mr}from"node:path";function uc(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let r=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return r?[r]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),t=lc();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||mr(t,".config","oracle")).trim();return[e,mr(r,"exec.env")].filter(Boolean)}return[e,mr(t,".config","oracle","exec.env"),mr(t,".config","mad-desk","exec.env")].filter(Boolean)}function zt(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of uc())try{let i=cc(o,"utf8"),s=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(s&&(n=s[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}function yt(e,t,r="guard"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${r}: current time must be a finite number (got ${dc(t)})`);let n=t,o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${r} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function dc(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var $o=100;function sn(e){return Array.isArray(e)?`[${e.map(sn).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${sn(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function wc(e,{required:t=!1}={}){try{return zt(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function hc(e){let{signature:t,...r}=e;return r}function gc(e){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<10||t.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return fc("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function yc(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:mc(r,n)}function bc(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=t.length;i+=64)n.push(t.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(r){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function an(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:i,requireSigned:s=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let l=wc(o,{required:s});if(s&&!l)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(l){let p=pc("sha256",l).update(sn(hc(e))).digest("hex");if(!yc(e.signature,p))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let a=Number(e.selectedBps),c=Number(e.capBps);if(!Number.isInteger(a)||a<0||a>$o)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(c)||c<0||c>$o||a>c)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{yt({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},t,"auto-slippage quote")}catch(p){throw new Error(`${p.message}; re-quote before signing`)}if(r!=null&&Number(e.chainId)!==Number(r))throw new Error("auto-slippage guard chain mismatch");if(n&&String(e.venue).toLowerCase()!==String(n).toLowerCase())throw new Error("auto-slippage guard venue mismatch");let d=BigInt(e.quoteAmountOut??0),u=BigInt(e.minAmountOut??0);if(d<=0n||u<=0n)throw new Error("auto-slippage guard amounts must be positive");let m=d*BigInt(1e4-a),f=m/10000n;if(m%10000n!==0n&&(f+=1n),u<f)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let p=bc(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==gc(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(p!=null&&p!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is hash-bound but the calldata encodes ${p}, not the guard floor ${e.minAmountOut}`)}else{if(p==null){let w=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${w}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(p!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${p}`)}}return!0}var Dw=new xc(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Sc,isAddress as Mw}from"ethers";var Uw=new Sc(["function approve(address spender,uint256 amount) returns (bool)"]),Ww=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function W(e,t="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${t} must be a number or decimal string`);return e}throw new Error(`${t} must be a number or decimal string`)}function ne(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function ae(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let r=W(e,t);if(r==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(r)}`)}}function de(e,t="amount"){let r=ae(e,t);if(r<=0n)throw new Error(`${t} must be positive`);return r}function q(e,t,r="amount"){let n=W(e,r);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${r} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[s="0",l=""]=i.split(".");if(l.length>t)throw new Error(`${r} has more than ${t} decimal places, which would lose precision`);let a=BigInt((s||"0")+l.padEnd(t,"0"));return o?-a:a}var ih=new Ac(["function approve(address spender,uint256 amount) returns (bool)"]);function Po(e,t){let r=String(e||"").trim();if(!Ic(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function kc(e,t="approval amount",{allowZero:r=!1}={}){let n=ae(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=vc)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var Bo=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),Oc=new Set(["0x39509351","0xf9255c1f"]);function oe(e){let t=String(e||"").toLowerCase();return t.length<10?!1:Bo.has(t.slice(0,10))}function Le(e){if(!oe(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=c=>n[c]?"0x"+n[c].slice(24):null,i=c=>n[c]?BigInt("0x"+n[c]):null,s=null,l=null,a=null;switch(r){case"0x095ea7b3":case"0x39509351":s=o(0),l=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":a=o(0),s=o(1),l=i(2);break;case"0xd505accf":s=o(1),l=i(2);break;case"0x8fcbaf0c":{s=o(1),l=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":a=o(0),s=o(1),l=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(s==null||l==null)throw new Error("invalid approve calldata");return{spender:Po(s,"approval spender"),token:a==null?null:Po(a,"approval token"),amount:kc(l,"approval amount",{allowZero:!0}),selector:r,additive:Oc.has(r)}}Fo();import{readFileSync as Fc,readdirSync as Mc,existsSync as Ho}from"node:fs";import{dirname as qc,join as Et}from"node:path";import{fileURLToPath as Hc}from"node:url";var Wt=qc(Hc(import.meta.url));function zc(){let e=[Et(Wt,"descriptors"),Et(Wt,"clear-sign","descriptors"),Et(Wt,"..","clear-sign","descriptors"),Et(Wt,"..","..","clear-sign","descriptors"),Et(Wt,"..","..","..","clear-sign","descriptors")];for(let t of e)if(Ho(t))return t;return e[0]}var Uc=zc(),Wc=/^0x[0-9a-f]{8}/,Vc=/^0x[0-9a-fA-F]{40}$/;function Jc(e=Uc){if(!Ho(e))return[];let t=[];for(let r of Mc(e).filter(n=>n.endsWith(".json")).sort()){let n=Fc(Et(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 Kc(e,{to:t=null,chainId:r=null}={},n=Jc()){let o=String(e||"").toLowerCase(),i=Wc.test(o)?o.slice(0,10):null;if(!i)return null;let s=t&&Vc.test(String(t))?String(t).toLowerCase():null;for(let{file:l,doc:a}of n){let c=a?.display?.formats||{};for(let[d,u]of Object.entries(c)){if(String(u?.$selector||"").toLowerCase()!==i)continue;let m=a?.context?.contract?.deployments||[],f=m.length===0,p=m.some(w=>(r==null||Number(w.chainId)===Number(r))&&s&&String(w.address||"").toLowerCase()===s);if(f||p)return{file:l,signature:d,format:u,doc:a,selector:i,generic:f}}}return null}function zo(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function Gc(e,t){let r=zo(e,t);return r?`0x${r.slice(24)}`:null}function Mo(e,t){let r=zo(e,t);return r?BigInt(`0x${r}`).toString():null}var Yc=(1n<<256n)-1n;function qo(e){if(e==null)return"unknown";let t=BigInt(e);return t>=Yc/2n?"UNLIMITED":t.toString()}function Uo(e,{to:t=null,chainId:r=null}={},n=void 0){let o=Kc(e,{to:t,chainId:r},n);if(!o)return null;let i=String(e||"").toLowerCase(),s=i.slice(10),l=[],a=[];for(let c of o.format.fields||[]){if(c.visible==="never")continue;let d=c.$wordIndex,u=null;Number.isInteger(d)&&(u=c.format==="addressName"||c.format==="raw-address"?Gc(s,d):c.format==="amount"||c.format==="tokenAmount"?qo(Mo(s,d)):Mo(s,d)),u!=null&&(a.push({label:c.label,value:u}),l.push(`${c.label}: ${u}`))}if(oe(i)){let c=null,d=null;try{c=Le(i)}catch(u){let m=String(u?.message||u);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 u=a.find(p=>/spender/i.test(p.label))?.value?.toLowerCase();if(u&&c.spender&&u!==c.spender.toLowerCase())return{ok:!1,refused:"descriptor spender disagrees with reviewed decoder",intent:o.format.intent};let m=a.find(p=>/amount|allowance/i.test(p.label))?.value,f=qo(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&&l.push(d),{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:a,lines:l,...d?{policyNote:d}:{}}}return{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:a,lines:l}}var Xc=/^0x[0-9a-f]{40}$/;function Vt(e){let t=String(e??"").toLowerCase();return Xc.test(t)?t:null}function Zc(e,{token:t,owner:r}){if(!oe(e))return[];let n;try{n=Le(e)}catch{return[]}let o={token:Vt(n.token??t),spender:Vt(n.spender),owner:Vt(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Qc(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||{},s=Vt(n?.owner??i.from),l=Vt(i.to??n?.destination),a=String(i.data??"0x").toLowerCase();if(!s||!l)return null;let c=[],d=r?.destinationAllowlist;if(Array.isArray(d)&&d.length){let u=d.map(m=>String(m).toLowerCase()).includes(l);c.push({name:"destination-allowlist",passed:u,reason:u?"destination is allowlisted":"destination is not on the allowlist"})}try{return jo({chainId:i.chainId,account:s,destination:l,calldata:a,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:Zc(a,{token:l,owner:s})})}catch{return null}}function Wo(e,t,r={}){let n=Qc(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||{},s=Uo(String(i.data??"0x"),{to:i.to??null,chainId:i.chainId??null});if(s?.ok){o.push(`CLEAR-SIGN intent=${s.intent} [${s.descriptor}]`);for(let l of s.lines)o.push(`CLEAR-SIGN ${l}`)}else s&&s.refused&&o.push(`CLEAR-SIGN REFUSED: ${s.refused}`)}catch{}return o}import{createHash as Vo}from"node:crypto";import{Address as el,NETWORK as tl,OutScript as Jo,RawTx as rl,SigHash as Ko,TEST_NETWORK as nl,Transaction as ol}from"@scure/btc-signer";var Go=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},il=(e,t)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${t}`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`envelope: invalid ${t}`);return r},sl=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,al=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),tt=e=>al(e)?String(e).toLowerCase():String(e),un=(e,t)=>Array.isArray(t)&&t.some(r=>tt(r)===tt(e)),cl=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function ll(e){let t=Buffer.from(rl.encode(e)),r=Vo("sha256").update(t).digest();return Buffer.from(Vo("sha256").update(r).digest()).reverse().toString("hex")}function ul(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(ll(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))throw new Error("envelope: Bitcoin prevout txid mismatch");let t=e.nonWitnessUtxo.outputs?.[e.index];if(!t)throw new Error("envelope: Bitcoin prevout output missing");if(!e.witnessUtxo)throw new Error("envelope: PSBT input witness UTXO required");if(BigInt(e.witnessUtxo.amount)!==BigInt(t.amount)||!cl(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function dn(e,t){if(e.action!=="transfer")throw new Error("envelope: BTC decoder requires transfer action");let r=e?.artifact;if(Object.keys(r).some(u=>!["network","psbt"].includes(u)))throw new Error("envelope: unexpected BTC artifact field");if(!un(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?tl:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?nl:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=ol.fromPSBT(il(r.psbt,"PSBT"))}catch(u){throw new Error(`envelope: invalid PSBT: ${u?.message||u}`)}if(o.inputsLength===0||o.outputsLength===0)throw new Error("envelope: PSBT inputs and outputs required");let i=el(n);for(let u=0;u<o.inputsLength;u++){let m=o.getInput(u);for(let w of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(sl(m[w]))throw new Error("envelope: signed or finalized PSBT refused");if(m.sighashType!==void 0&&m.sighashType!==Ko.DEFAULT&&m.sighashType!==Ko.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let f=ul(m),p;try{let w=Jo.decode(f.script);if(!["wpkh"].includes(w.type))throw new Error("unsupported input");p=i.encode(w)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!un(p,t.owners)||tt(p)!==tt(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let s=new Set([e.owner,...t.changeAddresses||[]].map(u=>tt(u))),l=0n,a=!1,c=[];for(let u=0;u<o.outputsLength;u++){let m=o.getOutput(u),f;try{f=i.encode(Jo.decode(m.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let p=tt(f);if(c.push(`${f}:${m.amount}`),p===tt(e.destination)){a=!0,l+=m.amount;continue}if(un(f,t.destinations)){l+=m.amount;continue}if(!s.has(p))throw new Error("policy: Bitcoin output destination not allowed")}if(!a)throw new Error("envelope: Bitcoin destination mismatch");let d;try{d=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(d<0n||d>Go(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(l>Go(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:l.toString(),notional:(l+d).toString(),fee:d.toString(),outputs:Object.freeze(c)})}function fn(e,t){let{unit:r,value:n,notional:o,fee:i}=dn(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as mn}from"node:crypto";import{base58 as ti}from"@scure/base";import{getCompiledTransactionMessageDecoder as dl}from"@solana/transaction-messages";var yr="11111111111111111111111111111111",ri="ComputeBudget111111111111111111111111111111",fl="So11111111111111111111111111111111111111112",ni="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var oi="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",pl=5000n,ml=2039280n,wl=37095705934669439343138083508754565189542113879843219016388785533085940283555n,Z=57896044618658097711785492504343953926634992332820282019728792003956564819949n,Yo=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Xo=e=>mn("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),hl=new Map([[Xo("route"),{name:"route",prefixBytes:0}],[Xo("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),ie=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},gl=(e,t)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${t}`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`envelope: invalid ${t}`);return r},me=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),H=e=>String(e||""),yl=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,gr=e=>mn("sha256").update(e).digest("hex");function hr(e,t){try{let r=Buffer.from(ti.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function fe(e){let t=e%Z;return t>=0n?t:Z+t}function ve(e,t){let r=e;for(;t-- >0n;)r=r*r%Z;return r}function bl(e){let r=e*e%Z*e%Z,n=ve(r,2n)*r%Z,o=ve(n,1n)*e%Z,i=ve(o,5n)*o%Z,s=ve(i,10n)*i%Z,l=ve(s,20n)*s%Z,a=ve(l,40n)*l%Z,c=ve(a,80n)*a%Z,d=ve(c,80n)*a%Z,u=ve(d,10n)*i%Z;return ve(u,2n)*e%Z}function El(e,t){let r=fe(t*t*t),n=fe(r*r*t),o=bl(e*n),i=fe(e*r*o),s=fe(t*i*i),l=i,a=fe(i*Yo),c=s===e,d=s===fe(-e),u=s===fe(-e*Yo);return c&&(i=l),(d||u)&&(i=a),(fe(i)&1n)===1n&&(i=fe(-i)),!c&&!d?null:i}function xl(e){if(!e||e.length!==32)return!1;let t=0n;for(let o=31;o>=0;o--)t=(t<<8n)+BigInt(o===31?e[o]&127:e[o]);let r=fe(t*t),n=El(fe(r-1n),fe(wl*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function Sl(e,t){let r=Buffer.concat([...e,hr(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=mn("sha256").update(r).digest();if(xl(n))throw new Error("envelope: derived Solana program address is on curve");return ti.encode(n)}function wn(e,t,r=ni){let n=[hr(e,"owner"),hr(r,"token program"),hr(t,"mint")];for(let o=255;o>=0;o--)try{return Sl([...n,Buffer.from([o])],oi)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function Al(e,t){return(t.accountIndices||[]).map(r=>H(e.staticAccounts[r]))}function Jt(e){return Buffer.from(e.data||[])}function vl(e,t){return H(e.staticAccounts[t.programAddressIndex])}function ii(e,t){return Number(t)<e.header.numSignerAccounts}function Il(e,t){let r=e.header.numSignerAccounts,n=e.header.numReadonlySignerAccounts,o=e.header.numReadonlyNonSignerAccounts,i=e.staticAccounts.length;return Number(t)<r?Number(t)<r-n:Number(t)<i-o}function Kt(e){return e.accountIndices||[]}function pn(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function Zo(e,t){let r=Kt(t).map(n=>{let o=ii(e,n)?"s":"n",i=Il(e,n)?"w":"r";return`${n}:${H(e.staticAccounts[n])}:${o}:${i}`});return gr(Buffer.from(r.join(`
2
+ `)))}function Qo(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function kl(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function Ol(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function Tl(e,t,r){let n=r.maxJupiterRoutePlanSteps===void 0?1:Number(r.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(t<1||t>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(r.jupiterRouteVariants)?r.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=r.jupiterRouteVariantPayloadBytes||{},s=0,l=0,a=[];for(let c=0;c<t;c++){if(s>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e[s++];if(!o.includes(d))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(d)))throw new Error("policy: Jupiter route variant payload size required");let u=Number(i[String(d)]);if(!Number.isSafeInteger(u)||u<0||u>16)throw new Error("policy: Jupiter route variant payload size invalid");if(s+u+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let m=e.subarray(s,s+u);s+=u;let f=m.toString("hex"),p=r.jupiterRouteVariantPayloads?.[String(d)];if(!Array.isArray(p)||!p.map(String).includes(f))throw new Error("policy: Jupiter route variant payload not allowed");let w=e[s++],g=e[s++],h=e[s++];if(w<1||w>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(g!==c||h!==c+1)throw new Error("envelope: unsupported Jupiter route-plan token index");l+=w,a.push(Object.freeze({swapVariant:d,variantPayloadHex:f,percent:w,inputIndex:g,outputIndex:h}))}if(s!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(l!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(a)}function Nl(e,t){let r=Jt({data:e}),n=r.subarray(0,8).toString("hex"),o=hl.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,s=o.prefixBytes===1?r[8]:null;if(o.prefixBytes===1&&r.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let l=8+o.prefixBytes,a=l+4,c=r.length-i;if(c<=a)throw new Error("envelope: malformed Jupiter route payload");let d=Ol(r,l,"route plan length"),u=r.subarray(a,c),m=Tl(u,d,t);return Object.freeze({instruction:o.name,routeId:s,routePlanSteps:d,routePlan:m,routePlanHash:gr(u),inAmount:Qo(r,c,"in_amount"),quotedOutAmount:Qo(r,c+8,"quoted_out_amount"),slippageBps:kl(r,c+16,"slippage_bps"),platformFeeBps:r[c+18],instructionHash:gr(r)})}function Cl(e,t,r){let n=Al(e,t),o=(i,s)=>{let l=n[i];if(!l)throw new Error(`envelope: Jupiter ${s} account missing`);return l};if(r.instruction==="route"){if(n.length<9)throw new Error("envelope: Jupiter route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),userTransferAuthority:o(1,"userTransferAuthority"),userSourceTokenAccount:o(2,"userSourceTokenAccount"),userDestinationTokenAccount:o(3,"userDestinationTokenAccount"),destinationTokenAccount:o(4,"destinationTokenAccount"),destinationMint:o(5,"destinationMint"),platformFeeAccount:o(6,"platformFeeAccount"),eventAuthority:o(7,"eventAuthority"),program:o(8,"program")}}if(r.instruction==="shared_accounts_route"){if(n.length<13)throw new Error("envelope: Jupiter shared route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),programAuthority:o(1,"programAuthority"),userTransferAuthority:o(2,"userTransferAuthority"),userSourceTokenAccount:o(3,"sourceTokenAccount"),programSourceTokenAccount:o(4,"programSourceTokenAccount"),programDestinationTokenAccount:o(5,"programDestinationTokenAccount"),userDestinationTokenAccount:o(6,"destinationTokenAccount"),sourceMint:o(7,"sourceMint"),destinationMint:o(8,"destinationMint"),platformFeeAccount:o(9,"platformFeeAccount"),token2022Program:o(10,"token2022Program"),eventAuthority:o(11,"eventAuthority"),program:o(12,"program")}}throw new Error("envelope: unsupported Jupiter account layout")}function ei(e,t){return e&&e!==t?e:null}function pe(e,t,r){let n=H(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function _l(e,t){let r=Jt(e);if(r.length===5&&r[0]===2){let n=r.readUInt32LE(1),o=t.maxComputeUnits===void 0?14e5:Number(t.maxComputeUnits);if(!Number.isSafeInteger(o)||o<=0)throw new Error("policy: maxComputeUnits must be positive");if(n>o)throw new Error("policy: Jupiter compute unit limit exceeds cap");return 0n}throw r.length===9&&r[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function Rl(e,t,r,n,o,i){let s=Jt(t);if(s.length!==1||s[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let l=Kt(t);if(l.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let a=pe(e,l[0],"ATA payer"),c=pe(e,l[1],"ATA account"),d=pe(e,l[2],"ATA owner"),u=pe(e,l[3],"ATA mint"),m=pe(e,l[4],"ATA system program"),f=pe(e,l[5],"ATA token program");if(a!==r.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(d!==r.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(m!==yr)throw new Error("envelope: Jupiter ATA system program mismatch");if(f!==o)throw new Error("envelope: Jupiter ATA token program mismatch");if(u!==n.inputMint&&u!==n.outputMint)throw new Error("envelope: Jupiter ATA mint mismatch");if(c!==wn(r.owner,u,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:c,debit:i}}function Ll(e,t,r,n,o){let i=Kt(t),s=Jt(t);if(i.length!==2||s.length!==12||s.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let l=pe(e,i[0],"wrap payer"),a=pe(e,i[1],"wrap target"),c=s.readBigUInt64LE(4);if(l!==r.owner||a!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(c!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return c}function $l(e,t,r,n){let o=Kt(t),i=Jt(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||pe(e,o[0],"syncNative account")!==n)throw new Error("envelope: Jupiter syncNative account mismatch");return{kind:"syncNative"}}if(i[0]===9){if(o.length!==3)throw new Error("envelope: malformed Jupiter closeAccount helper");let s=pe(e,o[0],"closeAccount source"),l=pe(e,o[1],"closeAccount destination"),a=pe(e,o[2],"closeAccount authority");if(s!==n||l!==r.owner||a!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function Pl(e,t,r,n,o,i,s){let l=wn(t.owner,t.artifact.inputMint,s);if(o.userSourceTokenAccount!==l)throw new Error("envelope: Jupiter source token account is not owner ATA");let a=ie(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(a<ml)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let c=new Map,d=0n,u=!1,m=!1;for(let f of e.instructions){if(f===n)continue;let p=vl(e,f);if(p===ri)_l(f,r);else if(p===oi){let{ata:w,debit:g}=Rl(e,f,t,t.artifact,s,a);c.set(w,g)}else if(p===yr)d+=Ll(e,f,t,l,i);else if(p===s){let w=$l(e,f,t,l);w.kind==="syncNative"&&(u=!0),w.kind==="closeAccount"&&(m=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(d>0n&&(!u||!m))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(d!==0n&&d!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...c.values()].reduce((f,p)=>f+p,0n)}function Bl(e){let t;try{t=dl().decode(gl(e.messageBase64,"Solana message"))}catch(r){throw new Error(`envelope: invalid Solana message: ${r?.message||r}`)}if(t.version!=="legacy"&&Array.isArray(t.addressTableLookups)&&t.addressTableLookups.length)throw new Error("envelope: unresolved Solana address tables refused");return t}function Dl(e,t,r,n=1){if(e.header.numSignerAccounts!==n||H(e.staticAccounts[0])!==t.owner||!me(t.owner,r.owners))throw new Error("envelope: Solana owner mismatch");if(!Array.isArray(e.instructions)||e.instructions.length===0)throw new Error("envelope: Solana instructions required");let o=[];for(let i of e.instructions){let s=H(e.staticAccounts[i.programAddressIndex]);if(!s||!me(s,r.programs))throw new Error("policy: Solana program not allowed");o.push(s)}return o}function jl(e,t,r){let n=ie(r.lamportsPerSignature,"lamportsPerSignature");if(n<pl)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:ie(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),s=i*n,l=i*o;if(t.exactFeeLamports!==void 0){let c=ie(t.exactFeeLamports,"exactFeeLamports");if(c<s)throw new Error("policy: Solana exact fee below the base signature fee");if(c>l)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let a=l;if(a>ie(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return a}function Fl(e,t,r,n){let o=0n,i=!1;for(let s of e.instructions){if(H(e.staticAccounts[s.programAddressIndex])!==yr)throw new Error("envelope: unsupported Solana program decoder");let a=s.accountIndices||[];if(a.length!==2||H(e.staticAccounts[a[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let c=H(e.staticAccounts[a[1]]);if(c!==t.destination||!me(c,r.destinations))throw new Error("envelope: Solana destination mismatch");let d=Buffer.from(s.data||[]);if(d.length!==12||d.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=d.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>ie(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function Ml(e,t,r,n){let o=t.artifact,i=H(o.mintProgram);if(!me(i,r.solMintPrograms))throw new Error("policy: Solana mint program not allowed");let s=e.header.numSignerAccounts;if(s!==2&&s!==3)throw new Error("envelope: Solana mint requires the payer, asset, and at most one distinct minter");let l=H(e.staticAccounts[s-1]);if(l!==H(o.assetSigner))throw new Error("envelope: Solana mint asset signer mismatch");if(s===3){let u=H(e.staticAccounts[1]);if(!o.minter||u!==H(o.minter))throw new Error("envelope: Solana mint minter mismatch");if(u===l)throw new Error("envelope: Solana mint minter must not be the asset signer")}else if(o.minter&&H(o.minter)!==t.owner)throw new Error("envelope: Solana mint declares a minter the message does not sign");if(me(l,r.owners))throw new Error("envelope: Solana mint asset signer must not be a policy owner");let a=ie(o.maxSpendLamports,"maxSpendLamports");if(a>ie(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana mint spend exceeds cap");let c=0n,d=!1;for(let u of e.instructions){let m=H(e.staticAccounts[u.programAddressIndex]);if(m!==ri){if(m===yr){let f=u.accountIndices||[];if(f.length!==2||H(e.staticAccounts[f[0]])!==t.owner)throw new Error("envelope: Solana mint transfer owner mismatch");let p=H(e.staticAccounts[f[1]]);if(!me(p,r.destinations))throw new Error("envelope: Solana mint destination mismatch");let w=Buffer.from(u.data||[]);if(w.length!==12||w.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");c+=w.readBigUInt64LE(4);continue}if(m!==i)throw new Error("envelope: unsupported Solana program decoder");d=!0}}if(!d)throw new Error("envelope: Solana mint instruction required");if(c>a)throw new Error("policy: Solana mint visible spend exceeds the declared maximum");return{value:a,programs:n,unverifiableProgramSpend:!0,visibleSpendLamports:c.toString()}}function ql(e,t,r,n){let o=t.artifact;if(o.provider!=="jupiter")throw new Error("envelope: Solana swap provider must be jupiter");if(o.inputMint!==fl)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!me(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=yl(r);if(!me(o.inputMint,i)||!me(o.outputMint,i))throw new Error("policy: Solana token not allowed");let s=ie(o.inAmount,"inAmount"),l=ie(o.outAmount,"outAmount"),a=ie(o.otherAmountThreshold,"otherAmountThreshold");if(s<=0n||s>ie(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(s>ie(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(l<=0n||a<=0n||a>l)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let c=H(o.jupiterProgram);if(!c||!me(c,r.programs)||!n.includes(c))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(v=>H(e.staticAccounts[v.programAddressIndex])===c);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let u=d[0],m=Nl(u.data,r);if(m.instruction==="shared_accounts_route"){let v=Array.isArray(r.jupiterSharedRouteIds)?r.jupiterSharedRouteIds.map(Number):[];if(!v.length)throw new Error("policy: Jupiter shared route id allowlist required");if(!v.includes(Number(m.routeId)))throw new Error("policy: Jupiter shared route id not allowed")}else if(m.routeId!=null)throw new Error("envelope: unexpected Jupiter shared route id");if(!pn(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(m.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(m.inAmount!==s)throw new Error("envelope: Jupiter route in_amount mismatch");if(m.quotedOutAmount!==l)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(m.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let f=m.quotedOutAmount-m.quotedOutAmount*BigInt(m.slippageBps)/10000n;if(a!==f)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(m.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let p=Cl(e,u,m),w=Kt(u),g=m.instruction==="shared_accounts_route"?2:1;if(!ii(e,w[g]))throw new Error("envelope: Jupiter transfer authority must be signer");if(p.program!==c)throw new Error("envelope: Jupiter program account mismatch");if(p.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(p.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(p.sourceMint!==void 0&&p.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let h=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[ni];if(!me(p.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let y=wn(t.owner,o.outputMint,p.tokenProgram);if(p.userDestinationTokenAccount!==y)throw new Error("envelope: Jupiter destination token account is not owner ATA");let b=ei(p.destinationTokenAccount,c);if(b&&b!==y)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(ei(p.platformFeeAccount,c))throw new Error("policy: Jupiter platform fee account not allowed");if(!pn(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(Zo(e,u)))throw new Error("policy: Jupiter route account hash not allowed");let x=gr(Buffer.from([m.instruction,m.routeId??"",m.routePlanHash,Zo(e,u)].join(`
3
+ `)));if(!pn(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(x))throw new Error("policy: Jupiter route review hash not allowed");let A=Pl(e,t,r,u,p,s,p.tokenProgram),k=s+A;if(k>ie(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:k,programs:n}}function hn(e,t){if(e.action!=="transfer"&&e.action!=="swap"&&e.action!=="mint")throw new Error("envelope: Solana decoder requires transfer, swap, or mint action");let r=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:e.action==="mint"?["cluster","messageBase64","exactFeeLamports","mintProgram","assetSigner","maxSpendLamports","minter","cosignatures"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(r||{}).some(a=>!n.includes(a)))throw new Error("envelope: unexpected Solana artifact field");if(!me(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=Bl(r),i=Dl(o,e,t,e.action==="mint"?o.header.numSignerAccounts:1),s=e.action==="transfer"?Fl(o,e,t,i):e.action==="mint"?Ml(o,e,t,i):ql(o,e,t,i),l=jl(o,r,t);return Object.freeze({unit:"lamports",value:s.value.toString(),notional:(s.value+l).toString(),fee:l.toString(),programs:Object.freeze(s.programs),...s.unverifiableProgramSpend?{unverifiableProgramSpend:!0,visibleSpendLamports:s.visibleSpendLamports}:{}})}function gn(e,t){let{unit:r,value:n,notional:o,fee:i,unverifiableProgramSpend:s,visibleSpendLamports:l}=hn(e,t);return Object.freeze(s?{unit:r,value:n,notional:o,fee:i,unverifiableProgramSpend:s,visibleSpendLamports:l}:{unit:r,value:n,notional:o,fee:i})}import{AsyncLocalStorage as Hl}from"node:async_hooks";var Ih=new Hl;var Ph=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Bh=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Dh=AbortSignal.prototype.throwIfAborted,jh=EventTarget.prototype.addEventListener,Fh=EventTarget.prototype.removeEventListener,Mh=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null;var qh=64*1024,Hh=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});var Ul=1e8;var Zh=Object.freeze({tradexyz:"xyz",ventuals:"vntl",hypernova:"hyna",paradex:"para",entropy:"io",entropyio:"io"});function yn(e){if(typeof e!="string"||!/^#(?:0|[1-9]\d*)$/.test(e))return null;let t=Number(e.slice(1));if(!Number.isSafeInteger(t)||t<0)return null;let r=t%10;if(r!==0&&r!==1)return null;let n=Math.floor(t/10),o=Ul+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var Wl=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),Vl=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),Jl=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),Kl=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"}),Ve=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function Gl(e,t){let r=e.toString().padStart(t+1,"0");if(t===0)return r;let n=r.slice(0,-t),o=r.slice(-t).replace(/0+$/,"");return o?`${n}.${o}`:n}function si(e,t){let r=W(e,`hl: ${t}`);if(!/^\d+(?:\.\d+)?$/.test(r))throw new Error(`hl: ${t} must be a positive decimal`);let[n,o=""]=r.split("."),i=BigInt(n+o);if(i<=0n)throw new Error(`hl: ${t} must be positive`);return{raw:i,decimals:o.length}}function Ie(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`hl: ${t} must be finite JSON`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(n=>Ie(n,t)).join(",")}]`;if(!e||typeof e!="object")throw new Error(`hl: ${t} must be structured JSON`);return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Ie(e[n],t)}`).join(",")}}`}function Yl(e){if(typeof e.orderType!="string"||!e.orderType)throw new Error("hl: order type must be a string");let t=e.orderType,r=e.orderWire;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: declared order wire required");if(t==="limit"){let i=r.limit?.tif;if(!["Gtc","Ioc","Alo"].includes(i)||Ie(r,"declared order type")!==Ie({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(Ie(r,"declared order type")!==Ie({limit:{tif:"Ioc"}},"expected order type"))throw new Error("hl: market order type must match its IOC wire shape");return}let n={stopMarket:{isMarket:!0,tpsl:"sl"},stopLimit:{isMarket:!1,tpsl:"sl"},takeProfitMarket:{isMarket:!0,tpsl:"tp"},takeProfitLimit:{isMarket:!1,tpsl:"tp"}}[t];if(!n)throw new Error("hl: unsupported declared order type");let o=r.trigger?.triggerPx;if(o==null||Ie(r,"declared order type")!==Ie({trigger:{isMarket:n.isMarket,triggerPx:o,tpsl:n.tpsl}},"expected order type"))throw new Error("hl: trigger order type must match its wire shape")}function Xl(e,t,r){let n=si(e.s,"signed size"),o=si(e.p,"signed price"),i=n.decimals+o.decimals,s=n.raw*o.raw,l=q(t.notionalUsd,i,"hl: notionalUsd");if(l<=0n||s!==l)throw new Error("hl: signed notional must match");let a=q(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>a)throw new Error("hl: notional exceeds cap")}function Zl(e,t){let r=e.action.builder;if(r==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: signed order builder must be structured");let n=Ve(r.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(ne(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(l=>String(l).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=ae(r.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let s=q(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function ai(e,t,r){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(t.side==="buy"))throw new Error("hl: signed side must match exactly");if(W(e.s,"hl: signed size")!==W(t.size,"hl: size"))throw new Error("hl: signed size must match");if(W(e.p,"hl: signed price")!==W(t.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof t.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==t.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(Ie(e.t,"signed order type")!==Ie(t.orderWire,"declared order type"))throw new Error("hl: signed order type must match declared order type");let n=Object.prototype.hasOwnProperty.call(e,"c");if(t.clientOrderId==null){if(n)throw new Error("hl: undeclared signed client order id")}else if(!n||typeof e.c!="string"||e.c!==t.clientOrderId)throw new Error("hl: signed client order id must match")}function ci(e,t,r,n,o){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(t.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(W(e.s,"hl: bracket protection size")!==W(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(W(e.p,"hl: bracket protection price")!==W(n,"hl: protection price"))throw new Error("hl: bracket protection price must match");if(e.r!==!0)throw new Error("hl: bracket protection must be reduce-only");let i=e.t?.trigger;if(!i||i.isMarket!==!0||i.tpsl!==o)throw new Error("hl: bracket protection trigger must match");if(W(i.triggerPx,"hl: triggerPx")!==W(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function Ql(e){let t=String(e||"").replace(/\/$/,"");if(!Wl.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function bn(e){return yn(e)!=null}function eu(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(bn(r)){if(t.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(n.includes(r)||n.includes("#*")||n.includes("*")||n.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(n.length&&!n.includes(r)&&!n.includes("*"))throw new Error("hl: coin not allowed");return!0}function tu(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(s=>{if(typeof s=="string"){let[l,a]=String(s).split(":");return l===e&&Number(a)===t}return String(s?.coin)===e&&Number(s?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(bn(e)){let i=Array.isArray(r.coins)?r.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0)return!0;throw new Error("hl: restricted coin policy requires hlMarkets pairs")}let o=Array.isArray(r.coins)?r.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function Pe(e,t){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: structured artifact required");let n=Ve(r.kind,"kind",48),o=Jl[n];if(!o)throw new Error("hl: unsupported Hyperliquid kind");if(e.action!==o)throw new Error("hl: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="hyperliquid")throw new Error("hl: destination must be hyperliquid");if(!/^0x[0-9a-fA-F]{40}$/.test(String(e.owner||"")))throw new Error("hl: owner required");let i=Ql(r.submitTo);if(Object.prototype.hasOwnProperty.call(r,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let s=Number(r.nonce);if(!Number.isSafeInteger(s)||s<=0)throw new Error("hl: nonce must be a positive integer");if(!r.action||typeof r.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(r.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(r.action.type!==Kl[n])throw new Error("hl: action type must match kind");let l=r.notionalUsd??0;if(Vl.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let a=Ve(r.coin,"coin",64),c=r.assetId??r.assetIndex;if(!Number.isSafeInteger(c)||c<0)throw new Error("hl: assetId required");if(n==="hip4-order"||c>=1e8){let d=yn(a);if(!d||d.coin!==a)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==c)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(eu(a,t),tu(a,c,t),n==="hip4-order"&&!bn(a))throw new Error("hl: HIP-4 orders must use an outcome coin");if(n==="perp-order"||n==="hip3-order"||n==="hip4-order"||n==="perp-bracket"){if(r.side!=="buy"&&r.side!=="sell")throw new Error("hl: side must be buy or sell");if(r.action.type!=="order"||!Array.isArray(r.action.orders))throw new Error("hl: signed orders are required");Yl(r);let d=r.action.orders;if(n==="perp-bracket"){let u=r.takeProfitPx,m=r.stopLossPx,f=1+(u==null?0:1)+(m==null?0:1);if(f<2||d.length!==f||r.grouping!=="normalTpsl"||r.action.grouping!==r.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");ai(d[0],r,c);let p=1;u!=null&&ci(d[p++],r,c,u,"tp"),m!=null&&ci(d[p],r,c,m,"sl")}else{if(d.length!==1)throw new Error("hl: exactly one signed order is required");if(r.grouping!=="na"||r.action.grouping!==r.grouping)throw new Error("hl: signed grouping must match declared grouping");ai(d[0],r,c)}Xl(d[0],r,t),Zl(r,t),l=W(r.notionalUsd,"hl: notionalUsd")}if(n==="perp-leverage"){let d=r.leverage;if(!Number.isSafeInteger(d)||d<1)throw new Error("hl: leverage must be a positive integer");let u=t.maxLeverage==null?50:t.maxLeverage;if(typeof u!="number"||!Number.isSafeInteger(u)||u<1)throw new Error("hl: maxLeverage must be a positive integer");if(d>u)throw new Error("hl: leverage exceeds cap")}if(n==="perp-cancel"){let d=r.action.cancels;if(!Array.isArray(d)||d.length!==1)throw new Error("hl: exactly one cancel is required");if(!Number.isSafeInteger(d[0].a)||d[0].a!==c)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(r.orderId)||r.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(d[0].o)||d[0].o!==r.orderId)throw new Error("hl: signed cancel order id must match")}if(n==="perp-leverage"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==c)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(r.action.leverage)||r.action.leverage!==r.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(r.marginMode))throw new Error("hl: declared margin mode required");let d=r.marginMode==="cross";if(typeof r.action.isCross!="boolean"||r.action.isCross!==d)throw new Error("hl: signed isCross must match declared margin mode")}if(n==="perp-isolated-margin"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==c)throw new Error("hl: signed margin asset must match assetId");let d=Ve(r.usd,"margin usd",64),u=q(d,6,"hl: margin usd");if(ae(r.action.ntli,"hl: signed margin ntli")!==u)throw new Error("hl: signed margin amount must match usd");if(typeof r.isBuy!="boolean"||r.action.isBuy!==r.isBuy)throw new Error("hl: signed margin isBuy must match");let f=q(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),p=u<0n?-u:u;if(p>f)throw new Error("hl: margin notional exceeds cap");l=Gl(p,6)}}if(n==="builder-fee-approval"){let a=Ve(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(a))throw new Error("hl: builder address required");if(Ve(r.action.builder,"signed builder",42).toLowerCase()!==a)throw new Error("hl: signed builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(p=>String(p).toLowerCase()):[]).includes(a))throw new Error("hl: builder not allowed");let d=Ve(r.maxFeeRate,"maxFeeRate",32);if(Ve(r.action.maxFeeRate,"signed maxFeeRate",32)!==d)throw new Error("hl: signed builder fee must match");if(!/^\d+(?:\.\d+)?%$/.test(d))throw new Error("hl: builder fee rate must be a percent");let u=q(d.slice(0,-1),12,"hl: builder fee percent"),m=q(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(m<0n||u*100n>m)throw new Error("hl: builder fee exceeds cap");if(Number(r.action.nonce)!==s)throw new Error("hl: signed builder nonce must match");let f=i.includes("testnet")?"Testnet":"Mainnet";if(r.hyperliquidChain!==f||r.action.hyperliquidChain!==r.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(r.signatureChainId!=="0x66eee"||r.action.signatureChainId!==r.signatureChainId)throw new Error("hl: signed signature chain id must match")}if(n.startsWith("hype-stake")||n==="hype-delegate"||n==="hype-undelegate"){if(n==="hype-delegate"||n==="hype-undelegate"){let a=n==="hype-undelegate";if(typeof r.action.isUndelegate!="boolean"||r.action.isUndelegate!==a)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(t.maxHypeWei!=null&&BigInt(String(r.action.wei??r.caps?.amountHype??"0"))>BigInt(t.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(l??r.action.wei??0),notional:String(l??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??l??0),coin:r.coin||null,submitTo:i})}import{createHmac as ru}from"node:crypto";var xt="0x"+"00".repeat(32);function En(e={}){let t=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,r=e.polyApiSecret||process.env.POLYMARKET_API_SECRET||process.env.POLY_API_SECRET,n=e.polyPassphrase||process.env.POLYMARKET_API_PASSPHRASE||process.env.POLY_API_PASSPHRASE;if(!t||!r||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(t),secret:String(r),passphrase:String(n)}}function li({creds:e,address:t,method:r,path:n,body:o="",nowSec:i}={}){if(!e?.key||!e?.secret||!e?.passphrase)throw new Error("poly: L2 credentials required");if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("poly: L2 address required");let s=String(i??Math.floor(Date.now()/1e3)),l=String(r||"").toUpperCase(),a=String(n||"");if(l!=="POST"||a!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let c=s+l+a+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),u=Buffer.from(d,"base64"),m=ru("sha256",u).update(c).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:m,POLY_TIMESTAMP:s,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function nu(e,t){if(e.side!==0&&e.side!==1)throw new Error("poly: side must be BUY or SELL");let r=e.side===0?"BUY":"SELL";if(t&&t!==r)throw new Error("poly: side mismatch");return r}function ou(e){let t=typeof e=="bigint"?e:de(e,"poly: atomicUsdc");if(t<=0n)throw new Error("poly: order amounts must be positive integer micro-units");let r=t/1000000n,n=(t%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return n?`${r.toString()}.${n}`:r.toString()}function ui(e,t){let r=de(e.makerAmount,"poly: makerAmount"),n=de(e.takerAmount,"poly: takerAmount");return ou(t==="BUY"?r:n)}function iu(e){let t=typeof e=="bigint"?e.toString(10):W(e,"poly: salt");if(!/^[1-9][0-9]*$/.test(t))throw new Error("poly: salt must be a positive integer");let r=BigInt(t);if(r>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("poly: salt exceeds safe integer");return Number(r)}function di({message:e,side:t,signature:r,orderType:n="GTC",apiKey:o}={}){if(!e||typeof e!="object")throw new Error("poly: CLOB v2 message required");if(!String(r||"").startsWith("0x"))throw new Error("poly: EIP-712 signature required");if(n!=="GTC")throw new Error("poly: only GTC is public");if(!o)throw new Error("poly: CLOB owner must be the L2 API key");let i=nu(e,t);if(ne(e.metadata||xt,"poly: metadata").toLowerCase()!==xt)throw new Error("poly: metadata must be zero");if(ne(e.builder||xt,"poly: builder").toLowerCase()!==xt)throw new Error("poly: builder must be zero");let s=iu(e.salt);return{deferExec:!1,order:{builder:xt,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:xt,salt:String(s),side:i,signature:r,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var su=new Set(["https://clob.polymarket.com/order"]),Gt=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),cg=Object.freeze(Gt.map(e=>e[0])),au=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),cu="0xe111180000d2663c0091e4f400237545b87b996b",lu="0xe2222d279d744050d28e00520010520000310f59",fi=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function pi(e){let t=String(e||"").replace(/\/$/,"");if(!su.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function mi(e){let t=ne(e,"poly: exchange").toLowerCase();if(!au.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function Be(e,t){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("poly: structured artifact required");let n=fi(r.kind,"kind",48);if(n!=="poly-order")throw new Error("poly: unsupported Polymarket kind");if(e.action!=="order")throw new Error("poly: surface/action/kind mismatch");if(ne(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(pi(r.submitTo),r.chainId!==137)throw new Error("poly: chainId must be Polygon 137");let o=r.domain;if(!o||typeof o!="object")throw new Error("poly: EIP-712 domain required");if(o.name!=="Polymarket CTF Exchange"||o.version!=="2"||o.chainId!==137)throw new Error("poly: EIP-712 domain must be official CTF Exchange v2 on Polygon");if(mi(o.verifyingContract),mi(r.exchange),ne(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==ne(r.exchange,"poly: exchange").toLowerCase())throw new Error("poly: exchange/domain mismatch");if(typeof r.negRisk!="boolean")throw new Error("poly: negRisk must be a boolean");let i=r.negRisk?lu:cu;if(ne(r.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let s=r.message||r.value;if(!s||typeof s!="object")throw new Error("poly: signed order message required");let l=r.types?.Order;if(!Array.isArray(l)||l.length!==Gt.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let v=0;v<Gt.length;v+=1)if(l[v]?.name!==Gt[v][0]||l[v]?.type!==Gt[v][1])throw new Error("poly: EIP-712 Order type must be official CLOB v2");if((r.orderType||"GTC")!=="GTC")throw new Error("poly: only GTC is public");let a=String(e.owner||"").toLowerCase();if(ne(s.maker,"poly: maker").toLowerCase()!==a)throw new Error("poly: maker must equal owner");if(ne(s.signer,"poly: signer").toLowerCase()!==a)throw new Error("poly: signer must equal owner");if(s.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof s.builder!="string"||s.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(s.side!==0&&s.side!==1)throw new Error("poly: side must be BUY or SELL");let c=fi(r.tokenId,"tokenId",80);if(ne(s.tokenId,"poly: tokenId")!==c)throw new Error("poly: tokenId mismatch");let d=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(d.length&&!d.includes(c)&&!d.includes("*"))throw new Error("poly: tokenId not allowed");let u=Number(s.side)===0?"BUY":"SELL";if(r.side&&r.side!==u)throw new Error("poly: side mismatch");let m=de(s.makerAmount,"poly: makerAmount"),f=de(s.takerAmount,"poly: takerAmount"),p=de(r.makerAmount,"poly: prepared makerAmount"),w=de(r.takerAmount,"poly: prepared takerAmount");if(m!==p)throw new Error("poly: signed makerAmount differs from prepared envelope");if(f!==w)throw new Error("poly: signed takerAmount differs from prepared envelope");let g=u==="BUY"?m:f,h=u==="BUY"?f:m,y=q(r.quantity,6,"poly: quantity");if(y<=0n||y!==h)throw new Error("poly: quantity must match CLOB v2 amounts");let b=q(r.price,6,"poly: price");if(b<=0n||b>=1000000n)throw new Error("poly: price must be within (0,1)");if(h*b!==g*1000000n)throw new Error("poly: price must match CLOB v2 amounts");if(q(r.notionalUsdc,6,"poly: notionalUsdc")!==g)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let A=ui(s,u);if(q(A,6,"poly: displayed notionalUsdc")!==g)throw new Error("poly: displayed notionalUsdc must match CLOB v2 amounts");let k=t.maxNotionalUsd??t.maxNotionalUsdc;if(k!=null){let v=q(k,6,"poly: maxNotionalUsd");if(g>v)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:g.toString(),notional:g.toString(),fee:"0",kind:n,tokenId:c,side:u,makerAmount:m.toString(),takerAmount:f.toString(),price:String(r.price),quantity:String(r.quantity),notionalUsdc:A,submitTo:pi(r.submitTo)})}var uu=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),xn=14,wi=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function St(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function Sn(e){let t=String(e||"").replace(/\/$/,"");if(!uu.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function De(e,t={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("lighter: structured artifact required");let n=wi(r.kind,"kind",48);if(n!=="lighter-order")throw new Error("lighter: unsupported Lighter kind");if(e.action!=="order")throw new Error("lighter: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="lighter")throw new Error("lighter: destination must be lighter");let o=Sn(r.submitTo),i=r.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let s=Number(ae(r.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(s)||s<0)throw new Error("lighter: accountIndex required");let l=Number(ae(r.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(l)||l<0)throw new Error("lighter: clientOrderIndex required");St(r.orderType,0,"orderType"),St(r.timeInForce,1,"timeInForce"),St(r.reduceOnly,0,"reduceOnly"),St(r.triggerPrice,0,"triggerPrice"),St(r.orderExpiry,-1,"orderExpiry");let a=wi(r.symbol||r.coin,"symbol",32),c=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(c.length&&!c.includes(a)&&!c.includes(String(i))&&!c.includes("*"))throw new Error("lighter: market not allowed");if(r.side!=="buy"&&r.side!=="sell")throw new Error("lighter: side must be buy or sell");let d=de(r.baseAmount,"lighter: baseAmount"),u=de(r.price,"lighter: price");if(d>BigInt(Number.MAX_SAFE_INTEGER)||u>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("lighter: baseAmount and price must be safe integers");let m=Number(d),f=Number(u),p=Number(r.sizeDecimals??0),w=Number(r.priceDecimals??0);if(!Number.isInteger(p)||p<0||p>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(w)||w<0||w>12)throw new Error("lighter: priceDecimals required");let g=p+w,h=d*u,y=q(r.notionalUsd,g,"lighter: notionalUsd");if(y<=0n)throw new Error("lighter: notionalUsd required");if(h!==y)throw new Error("lighter: notionalUsd must match size and price");let b=q(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,g,"lighter: maxNotionalUsd");if(h>b)throw new Error("lighter: notional exceeds cap");let x=W(r.notionalUsd,"lighter: notionalUsd");return St(r.txType,xn,"txType"),Object.freeze({unit:"usd",value:String(x),notional:String(x),fee:"0",kind:n,symbol:a,marketIndex:i,side:r.side,baseAmount:m,price:f,submitTo:o,actionType:"create-order",amount:String(x)})}function br(e,t,r,n=null){let o=e?.version===1&&e?.surface?e:null,i=o?.artifact||e||{},s=[`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"}`],l=(c,d)=>{if(s.push(`LEG ${d} chain=${c.chainId??"n/a"} from=${c.from??"n/a"} to=${c.to??"n/a"}`),s.push(`LEG ${d} calldata=${String(c.data||"0x")} value=${c.value??"n/a"}`),s.push(`LEG ${d} gas=${c.gasLimit??"n/a"} maxFeePerGas=${c.maxFeePerGas??c.gasPrice??"n/a"} maxPriorityFeePerGas=${c.maxPriorityFeePerGas??"n/a"}`),s.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 u=Le(String(c.data||"0x"));s.push(`LEG ${d} APPROVAL token=${u.token||c.to||"n/a"} spender=${u.spender} amount=${u.amount}`)}catch{s.push(`LEG ${d} APPROVAL spender=undecodable amount=undecodable`)}},a=String(i.data||"0x");if(oe(a))try{let c=Le(a);s.push(`APPROVAL token=${c.token||i.to||"n/a"} spender=${c.spender} amount=${c.amount}`)}catch{s.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(i.transactions)&&(s.push(`batchLegs=${i.transactions.length}`),i.transactions.forEach((c,d)=>l(c,d))),o?.surface==="btc"){let c=dn(o,r);s.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(o?.surface==="sol"){let c=hn(o,r);s.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(o?.surface==="hl"){let c=Pe(o,r);s.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=Be(o,r);s.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"&&(s.push(`anvilAction=${o.nftAction} collection=${o.contract} tokenId=${o.tokenId} market=${o.destination}`),s.push(`paymentToken=${o.paymentToken} paymentTokenDecimals=${o.paymentTokenDecimals} maxPaymentTokenAmountRaw=${o.maxPaymentTokenAmountRaw??"n/a"} minPayoutRaw=${o.minPayoutRaw??"n/a"} nativeSwapFeeWei=${o.nativeSwapFeeWei}`),n&&(s.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}`),s.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=De(o,r);s.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
4
4
  Confirm exact action
5
5
  ${[...s,...Wo(e,t,r)].join(`
6
6
  `)}
7
- Type digest ${t}: `}import{createHash as Zl,randomBytes as Ql,timingSafeEqual as ed}from"node:crypto";import{base58 as Zi}from"@scure/base";import{Interface as _i}from"ethers";Er();var Yt=e=>String(e||"").toLowerCase(),hl=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","authorizationList","slippageBps","expiresAtMs"]),gl=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function ke(e){try{return gl.has(BigInt(e))}catch{return!1}}var we=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},yi=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},At=(e,t,r,n=String)=>{if(!Array.isArray(t)||t.length===0)throw new Error(`policy: ${r} allowlist is empty`);if(!t.map(n).includes(n(e)))throw new Error(`policy: ${r} not allowed`)};function xr(e,t,{nowMs:r=Date.now(),networkFees:n,requireNetworkFees:o=!1}={}){if(!e||!t)throw new Error("policy: artifact and policy required");if(Object.keys(e).some(f=>!hl.has(f)))throw new Error("policy: unexpected EVM artifact field");if(e.gasPrice!=null&&(e.maxFeePerGas!=null||e.maxPriorityFeePerGas!=null))throw new Error("policy: ambiguous EVM fee fields");if(e.type!=null&&![0,1,2,4].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");if(Number(e.type)===4){if(!Array.isArray(e.authorizationList)||e.authorizationList.length===0||e.authorizationList.length>8)throw new Error("policy: type-4 requires 1-8 authorizationList entries");for(let[f,p]of e.authorizationList.entries()){if(!p||typeof p!="object")throw new Error(`policy: authorizationList[${f}] required`);At(p.address,t.destinations,"destination",Yt);try{if(BigInt(p.chainId)!==BigInt(e.chainId))throw new Error("policy: type-4 authorization chainId must match transaction")}catch(w){throw String(w?.message||"").includes("authorization chainId")?w:new Error("policy: type-4 authorization chainId must match transaction")}}if(String(e.data||"0x").toLowerCase()!=="0x")throw new Error("policy: type-4 calldata must be empty");if(we(e.value,"value")!==0n)throw new Error("policy: type-4 cannot transfer native value")}else if(e.authorizationList!=null)throw new Error("policy: authorizationList is only valid on type-4");let i=(f,p)=>{try{return BigInt(f)===BigInt(p)}catch{return String(f)===String(p)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(f=>i(f,e.chainId)))throw new Error("policy: chain not allowed");if(At(e.to,t.destinations,"destination",Yt),At(String(e.data||"0x").slice(0,10),t.selectors,"selector",f=>String(f).toLowerCase()),At(e.from,t.owners,"owner",Yt),oe(e.data)){let f;try{f=Le(e.data)}catch(w){throw new Error(`policy: malformed approval calldata: ${w?.message||w}`)}At(f.spender,t.spenders,"spender",Yt),At(f.token||e.to,t.erc20Tokens,"ERC-20 token",Yt);let p=we(t.maxApproval,"maxApproval");if(BigInt(f.amount)>p)throw new Error("policy: approval exceeds cap");if(f.additive)throw new Error("policy: additive approval cannot be bounded; use approve() with an absolute amount")}if(we(e.value,"value")>we(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=we(e.gasLimit,"gasLimit");if(s>we(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let u=e.maxFeePerGas??e.gasPrice,a=we(u,"feePerGas")*s,c=0n;try{if(ke(e.chainId)&&(e.l1FeeWei===void 0||e.operatorFeeWei===void 0))throw new Error("missing")}catch{throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(e.l1FeeWei!==void 0&&(c+=we(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(c+=we(e.operatorFeeWei,"operatorFeeWei")),ke(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let f=we(n.l1FeeWei,"estimated l1FeeWei")+we(n.operatorFeeWei,"estimated operatorFeeWei");if(c<f)throw new Error("policy: rollup fee attestation understates estimate")}if(a+c>we(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=yi(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>l)throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r)throw new Error("policy: artifact expired");let m=yi(t.maxTtlMs??12e4,"maxTtlMs");if(m<=0||e.expiresAtMs-r>m)throw new Error("policy: artifact TTL exceeds cap");return!0}import{TypedDataEncoder as xi,getAddress as be}from"ethers";Er();import{TypedDataEncoder as Og,getAddress as Tg,isAddress as Ng}from"ethers";var bi=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),In=Object.freeze({Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"receiver",type:"address"},{name:"makerAsset",type:"address"},{name:"takerAsset",type:"address"},{name:"makingAmount",type:"uint256"},{name:"takingAmount",type:"uint256"},{name:"makerTraits",type:"uint256"}]});import{TypedDataEncoder as Mg,getAddress as qg,isAddress as Hg}from"ethers";var Rg=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});Er();var Ei=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Gg=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var kn=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),Yg=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});var bl=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"]),El="0x0000000000000000000000000000000000000000";function On(e,t,r=256){if(typeof e!="string"||!e||e.length>r)throw new Error(`evm-order: bounded ${t} required`);return e}function Si(e,t){let r=String(e||"").replace(/\/$/,"");if(!bl.some(o=>r===`${o}/v4.0/${t}`||r===`${o}/v4.1/${t}`))throw new Error("evm-order: submitTo must be the official 1inch orderbook");return r}function Ai(e,t){let r={1:"https://api.cow.fi/mainnet/api/v1/orders",100:"https://api.cow.fi/xdai/api/v1/orders",42161:"https://api.cow.fi/arbitrum_one/api/v1/orders",8453:"https://api.cow.fi/base/api/v1/orders"}[Number(t)],n=String(e||"").replace(/\/$/,"");if(!r||n!==r)throw new Error("evm-order: cow submitTo must be official api.cow.fi");return n}function vi(e,t){let r=e?.Order,n=t.Order;return!Array.isArray(r)||r.length!==n.length?!1:r.every((o,i)=>o?.name===n[i].name&&o?.type===n[i].type)}function Ii(e,...t){let r=Array.isArray(e.tokens)?e.tokens.map(n=>String(n).toLowerCase()):[];if(!r.length)throw new Error("evm-order: tokens allowlist is empty");if(!r.includes("*")){for(let n of t)if(!r.includes(String(n).toLowerCase()))throw new Error("evm-order: token not allowed")}}function ki(e,t,{allowZero:r=!1}={}){let n=String(t||"").toLowerCase();if(!n)throw new Error("evm-order: receiver required");if(n===El){if(!r)throw new Error("evm-order: receiver must equal owner");return}if(n!==e)throw new Error("evm-order: receiver must equal owner")}function rt(e,t){if(e?.surface!=="evm-order")throw new Error("evm-order: surface evm-order required");if(e.action!=="order")throw new Error("evm-order: action must be order");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("evm-order: structured artifact required");let n=On(r.kind,"kind",32);if(n==="option")throw new Error("evm-order: option kind refused until official Derive/Lyra domain is pinned");if(n==="cow"){let l=Number(r.chainId??e.chainId);if(Ai(r.submitTo,l),On(e.destination,"destination",32)!=="cowswap")throw new Error("evm-order: cow destination must be cowswap");let m=Ei[l];if(!m)throw new Error(`evm-order: unsupported cow chainId ${l}`);let f=r.domain||r.typedData?.domain,p=r.types||r.typedData?.types,w=r.message||r.typedData?.message;if(!f||!p?.Order||!w)throw new Error("evm-order: CoW EIP-712 Order required");if(!vi(p,kn))throw new Error("evm-order: cow types must be official GPv2 Order");if(Number(f.chainId)!==l)throw new Error("evm-order: cow domain chain mismatch");if(String(f.name)!=="Gnosis Protocol"||String(f.version)!=="v2")throw new Error("evm-order: cow domain must be official GPv2");if(be(f.verifyingContract)!==be(m))throw new Error("evm-order: cow verifyingContract must be official GPv2 settlement");let g=String(e.owner||"").toLowerCase();ki(g,w.receiver),Ii(t,w.sellToken,w.buyToken);let h=be(w.sellToken),y=String(w.feeAmount||"0"),b=(BigInt(w.sellAmount)+BigInt(y)).toString();return Object.freeze({unit:`erc20:${h.toLowerCase()}`,value:b,notional:b,fee:y,submitTo:Ai(r.submitTo,l),digest:xi.hash(f,{Order:kn.Order},w),chainId:l,kind:"cow",receiver:be(w.receiver),sellAmount:String(w.sellAmount),buyAmount:String(w.buyAmount)})}if(n!=="1inch-limit")throw new Error("evm-order: unsupported kind");if(On(e.destination,"destination",32)!=="1inch-lop")throw new Error("evm-order: destination must be 1inch-lop");let o=Number(r.chainId??e.chainId),i=bi[o];if(!i)throw new Error(`evm-order: unsupported chainId ${o}`);Si(r.submitTo,o);let s=r.domain||r.typedData?.domain,u=r.types||r.typedData?.types,a=r.message||r.typedData?.message;if(!s||!u?.Order||!a)throw new Error("evm-order: EIP-712 Order required");if(!vi(u,In))throw new Error("evm-order: types must be official LOP v4 Order");if(Number(s.chainId)!==o)throw new Error("evm-order: domain chain mismatch");if(be(s.verifyingContract)!==be(i))throw new Error("evm-order: verifyingContract must be official LOP v4");if(s.name!=="1inch Limit Order Protocol"||String(s.version)!=="4")throw new Error("evm-order: EIP-712 domain must be official LOP v4");let c=String(e.owner||"").toLowerCase();if(be(a.maker).toLowerCase()!==c)throw new Error("evm-order: maker must equal owner");ki(c,a.receiver,{allowZero:!0}),Ii(t,a.makerAsset,a.takerAsset);let d=xi.hash(s,{Order:In.Order},a);return Object.freeze({unit:`erc20:${be(a.makerAsset).toLowerCase()}`,value:String(a.makingAmount),notional:String(a.makingAmount),fee:"0",submitTo:Si(r.submitTo,o),digest:d,chainId:o,kind:"1inch-limit",receiver:be(a.receiver),makerAsset:be(a.makerAsset),takerAsset:be(a.takerAsset),makingAmount:String(a.makingAmount),takingAmount:String(a.takingAmount)})}var Ri=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]);var Tn=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,delegate:0,identity:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0}),xl=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Li=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),Sl=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),Sr=new _i(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Oi=new _i(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),Al=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}});var Zt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},N=(e,t)=>{try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`envelope: ${t} must be a non-negative integer`)}},Ti=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},vl=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},X=(e,t,r)=>{if(!vl(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Xt=(e,t,r)=>{Array.isArray(t)&&t.length&&X(e,t,r)},P=(e,t)=>{let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`envelope: ${t} must be a 20-byte address`);return r},nt=e=>String(e||"0x").slice(0,10).toLowerCase(),$i=e=>N(e.gasLimit,"gasLimit")*N(e.maxFeePerGas??e.gasPrice,"feePerGas")+N(e.l1FeeWei??0,"l1FeeWei")+N(e.operatorFeeWei??0,"operatorFeeWei");function vt(e,t,r,{dynamicTail:n=!1}={}){let o=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(o)||o.length<10+t*64)throw new Error(`envelope: malformed ${r} calldata`);if(!n&&o.length!==10+t*64)throw new Error(`envelope: malformed ${r} calldata`);return{hex:o,word:i=>o.slice(10+i*64,10+(i+1)*64)}}function Q(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function Ee(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function Il(e){if(nt(e)!=="0x095ea7b3")return null;let t=vt(e,2,"approval");return{kind:"approval",spender:Q(t.word(0),"approval spender"),amount:Ee(t.word(1),"approval amount")}}function Pi(e,t){let r=t==="router02-exact-input-single"?7:8,n=vt(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:Q(n.word(0),"input token"),outputToken:Q(n.word(1),"output token"),recipient:Q(n.word(3),"recipient"),amountIn:Ee(n.word(o),"amountIn"),minimumOut:Ee(n.word(o+1),"amountOutMinimum")}}function kl(e){let t=vt(e,12,"Across depositV3",{dynamicTail:!0}),r=Ee(t.word(11),"message offset");if(r!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let n=10+Number(r)*2;if(t.hex.length<n+64)throw new Error("envelope: malformed Across depositV3 message");let o=Number(BigInt(`0x${t.hex.slice(n,n+64)}`));if(!Number.isSafeInteger(o))throw new Error("envelope: malformed Across depositV3 message length");let i=Math.ceil(o/32)*64;if(t.hex.length!==n+64+i)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:Q(t.word(0),"depositor"),recipient:Q(t.word(1),"recipient"),inputToken:Q(t.word(2),"input token"),outputToken:Q(t.word(3),"output token"),amountIn:Ee(t.word(4),"inputAmount"),minimumOut:Ee(t.word(5),"outputAmount"),destinationChainId:Ee(t.word(6),"destinationChainId")}}function Ol(e){let t=String(e||"").replace(/^0x/i,"").toLowerCase();if(t.length<86||t.length%2!==0)throw new Error("envelope: malformed Uniswap path");let r=`0x${t.slice(0,40)}`,n=`0x${t.slice(t.length-40)}`;if(!/^0x[0-9a-f]{40}$/.test(r)||!/^0x[0-9a-f]{40}$/.test(n))throw new Error("envelope: malformed Uniswap path tokens");return{inputToken:r,outputToken:n}}function Ni(e,{hasDeadline:t}){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<74)throw new Error("envelope: malformed exactInput calldata");let n=[];for(let g=10;g+64<=r.length;g+=64)n.push(r.slice(g,g+64));let o=(g,h)=>{if(!n[g])throw new Error(`envelope: malformed ${h}`);return BigInt(`0x${n[g]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let s=i/32,u=Number(o(s,"path offset")),a=n[s+1],c=o(s+(t?3:2),"amountIn"),d=o(s+(t?4:3),"amountOutMinimum"),l=s+u/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let m=Number(o(l,"path length")),f=r.slice(10+(l+1)*64,10+(l+1)*64+m*2),{inputToken:p,outputToken:w}=Ol(`0x${f}`);return{kind:"action",action:"swap",inputToken:p,outputToken:w,recipient:Q(a,"recipient"),amountIn:c,minimumOut:d}}function Tl(e){let t=vt(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:Q(t.word(0),"input token"),outputToken:Q(t.word(1),"output token"),recipient:Q(t.word(3),"recipient"),amountIn:Ee(t.word(5),"amountIn"),minimumOut:Ee(t.word(6),"amountOutMinimum")}}function Nl(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let m=10;m+64<=t.length;m+=64)r.push(t.slice(m,m+64));let n=Number(BigInt(`0x${r[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${r[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let s=Number(BigInt(`0x${r[o+1]}`)),u=o+1+s/32,a=Number(BigInt(`0x${r[u]}`)),d=`0x${t.slice(10+(u+1)*64,10+(u+1)*64+a*2)}`,l=nt(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Pi(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function Cl(e,t){let r=nt(e),n=Li[r];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed selector");if(n.layout==="router02-exact-input-single"||n.layout==="swap-router-exact-input-single")return{...Pi(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...Ni(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...Ni(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...Nl(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Tl(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...kl(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function _l(e){let t=vt(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:Q(t.word(0),"mint NFT contract"),feeRecipient:Q(t.word(1),"mint fee recipient"),recipient:Q(t.word(2),"mint recipient"),quantity:Ee(t.word(3),"mint quantity")}}function Rl(e){let t;try{t=Oi.decodeFunctionData("mintAllowList",e)}catch{throw new Error("envelope: malformed SeaDrop mintAllowList calldata")}let r=t[4],n=[...t[5]].map(String);if(n.length<1||n.length>64||n.some(a=>!/^0x[0-9a-fA-F]{64}$/.test(a)))throw new Error("envelope: bounded canonical SeaDrop allowlist proof required");if(Oi.encodeFunctionData("mintAllowList",[t[0],t[1],t[2],t[3],r,n]).toLowerCase()!==String(e).toLowerCase())throw new Error("envelope: SeaDrop allowlist calldata must be canonical");let i=BigInt(r.startTime),s=BigInt(r.endTime);if(s<=i)throw new Error("envelope: SeaDrop allowlist stage time range is invalid");let u=BigInt(t[3]);if(BigInt(r.maxTotalMintableByWallet)<u)throw new Error("envelope: SeaDrop allowlist wallet cap is below quantity");return{kind:"mint",action:"mint",mintType:"allowlist",contract:P(t[0],"mint NFT contract"),feeRecipient:P(t[1],"mint fee recipient"),recipient:P(t[2],"mint recipient"),quantity:u,mintPrice:BigInt(r.mintPrice),startTime:i,endTime:s,dropStageIndex:BigInt(r.dropStageIndex),proof:n}}function Ll(e,t){let r=nt(e);if(String(t).toLowerCase()==="nft-mint")return $l(e);let n=Sl[r];if(!n)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed NFT selector");if(n.layout==="seadrop-mint-public")return{..._l(e),selector:r,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...Rl(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function $l(e){let t=nt(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=Al[t];if(!r)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(r.layout==="mint-no-args")return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:1n};if(r.layout==="mint-quantity"){let n=vt(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:Ee(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function Ar(e){let t=e?.artifact;if(Array.isArray(t?.transactions))return t.transactions;if(t?.transaction&&typeof t.transaction=="object")return[t.transaction];if(t?.data)return[t];throw new Error("envelope: ordered EVM transaction batch required")}function Bi(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let s=P(e.owner,"owner"),u=e.artifact,a=Number(u?.chainId??Ar(e)[0]?.chainId);if(!Number.isSafeInteger(a)||a<=0)throw new Error("envelope: explicit batch chainId required");if(X(a,t.chains,"chain"),u?.owner!==void 0&&P(u.owner,"batch owner")!==s)throw new Error("envelope: explicit batch owner mismatch");let c=Ar(e);if(!c.length||c.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,l=0n,m=0n;for(let f of c){if(!f||typeof f!="object"||Array.isArray(f))throw new Error("envelope: structured EVM transaction required");if(Number(f.chainId)!==a)throw new Error("envelope: every batch leg must use the same chain");if(P(f.from,"transaction owner")!==s)throw new Error("envelope: every batch leg must use the same owner");if(X(nt(f.data),t.selectors,"selector"),d+=N(f.value??0,"value"),l+=N(f.gasLimit,"gasLimit"),m+=$i(f),ke(a)&&(f.l1FeeWei===void 0||f.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>N(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>N(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(m>N(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:c,chainId:a,owner:s,totalValue:d,totalGas:l,totalFee:m}}function Di(e,t,{nowMs:r=Date.now(),routeAttestationSecret:n}={}){let o=String(e?.surface||"");if(o!=="evm-swap"&&o!=="evm-bridge")throw new Error("envelope: strict EVM swap/bridge surface required");let i=Zt(e.provider,"provider",64).toLowerCase();X(i,t.providers,"provider");let s=Bi(e,t,o,{nowMs:r}),u=[],a=-1;for(let p=0;p<s.transactions.length;p++){let w=s.transactions[p],g=Il(w.data),h;if(g){if(a!==-1)throw new Error("envelope: approval must be before action");if(N(w.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let S=P(w.to,"approval token");if(X(S,t.tokens,"token"),X(g.spender,t.spenders,"spender"),g.amount>N(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...g,token:S,index:p}}else{if(a!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");X(w.to,t.destinations,"destination"),h={...Cl(w.data,i),target:P(w.to,"action target"),index:p},a=p}let y=N(w.value??0,"value"),b=N(w.gasLimit,"gasLimit");u.push({...h,value:y,gas:b,fee:$i(w)})}if(a<0)throw new Error("envelope: reviewed swap/bridge action required");let c=u[a],d=o==="evm-swap"?"swap":"bridge";if(c.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if(P(e.destination,"destination")!==c.target)throw new Error("envelope: destination must equal decoded action target");if(c.recipient!==s.owner)throw new Error("envelope: decoded recipient must equal owner");if(c.depositor&&c.depositor!==s.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(X(c.inputToken,t.tokens,"input token"),X(c.outputToken,t.tokens,"output token"),c.amountIn<=0n||c.amountIn>N(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(c.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(an(e.autoSlippage,{nowMs:r,chainId:s.chainId,venue:i,tx:s.transactions[a],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(c.minimumOut!==N(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(c.action==="bridge"&&N(e.toChainId,"toChainId")!==c.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=u.filter(p=>p.kind==="approval");if(!new Set([...xl,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(p=>String(p).toLowerCase()):[]]).has(c.inputToken))throw new Error("envelope: strict local signer swap/bridge requires native input token; use wallet signing for token-unit rails");if(l.length)throw new Error("envelope: native-value action must not include token approval");if(c.value!==c.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let f=Object.freeze({quoteAmountOut:N(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:N(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...s,decoded:u,action:c,provider:i,authenticatedQuote:f}}function Pl(e,t,{nowMs:r}){let n=e.anvilAttestation,o=e.artifact?.anvilAttestation;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("envelope: Anvil attestation is required");if(!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: Anvil attestation artifact mismatch");if(Number(n.version)!==1||n.source!=="anvil-snapshot-rpc-reviewed-runtime")throw new Error("envelope: unsupported Anvil attestation");if(Number(n.chainId)!==4663)throw new Error("envelope: Anvil attestation chain mismatch");let i=P(e.destination,"Anvil market"),s=P(e.contract,"NFT contract"),u=P(e.paymentToken,"payment token");if(P(n.market,"attested Anvil market")!==i)throw new Error("envelope: Anvil attestation market mismatch");if(P(n.collection,"attested NFT collection")!==s)throw new Error("envelope: Anvil attestation collection mismatch");if(P(n.paymentToken,"attested payment token")!==u)throw new Error("envelope: Anvil attestation payment token mismatch");let a=Number(e.paymentTokenDecimals??e.artifact?.paymentTokenDecimals);if(!Number.isSafeInteger(a)||a<0||a>255||Number(n.paymentTokenDecimals)!==a)throw new Error("envelope: Anvil payment token decimals mismatch");let c=N(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei").toString();if(N(n.nativeSwapFeeWei,"attested nativeSwapFeeWei").toString()!==c)throw new Error("envelope: Anvil attestation native swap fee mismatch");let d=Number(n.snapshotFetchedAtMs),l=Number(n.snapshotExpiresAtMs);if(!Number.isFinite(d)||!Number.isFinite(l)||d>r||l<=r||l<=d)throw new Error("envelope: Anvil snapshot attestation is stale");let m=N(n.blockNumber,"attested blockNumber");if(m<=0n||!/^0x[0-9a-f]{64}$/.test(String(n.blockHash||"").toLowerCase()))throw new Error("envelope: Anvil block attestation is invalid");let f=String(n.runtimeCodeHash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(f))throw new Error("envelope: Anvil runtime code hash is invalid");let p=Object.entries(t.anvilRuntimeCodeHashes||{}).find(([g])=>g.toLowerCase()===i)?.[1];if(!p||String(p).toLowerCase()!==f)throw new Error("policy: Anvil runtime code hash is not reviewed");let w=Object.entries(t.nftPaymentTokenCaps||{}).find(([g])=>g.toLowerCase()===u)?.[1];if(!w||Number(w.decimals)!==a)throw new Error("policy: Anvil payment token decimals are not reviewed");return Object.freeze({...n,market:i,collection:s,paymentToken:u,paymentTokenDecimals:a,runtimeCodeHash:f,blockNumber:m})}function Ci(e,t){let r=e.artifact,n=e.anvilQuote,o=r?.anvilQuote;if(!n||typeof n!="object"||Array.isArray(n)||!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: exact Anvil quote artifact mismatch");if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("envelope: exact Anvil quote confirmation required");let i=t==="buy"?[[n.totalCostRaw,"anvilQuote.totalCostRaw"],[e.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw"],[r?.maxPaymentTokenAmountRaw,"artifact maxPaymentTokenAmountRaw"],[e.exactQuoteTotalCostRaw,"exactQuoteTotalCostRaw"],[r?.exactQuoteTotalCostRaw,"artifact exactQuoteTotalCostRaw"],[e.preconditions?.confirmedTotalCostRaw,"confirmedTotalCostRaw"]]:[[n.netPayoutRaw,"anvilQuote.netPayoutRaw"],[e.minPayoutRaw,"minPayoutRaw"],[r?.minPayoutRaw,"artifact minPayoutRaw"],[e.exactQuoteNetPayoutRaw,"exactQuoteNetPayoutRaw"],[r?.exactQuoteNetPayoutRaw,"artifact exactQuoteNetPayoutRaw"],[e.preconditions?.confirmedNetPayoutRaw,"confirmedNetPayoutRaw"]],s=N(i[0][0],i[0][1]);for(let[u,a]of i.slice(1))if(N(u,a)!==s)throw new Error(`envelope: Anvil ${t} exact settlement limit mismatch`);return s}function Fi(e,t,{nowMs:r=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint or NFT action");let n=Zt(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Xt(n,t.providers,"provider");let o=Bi(e,t,"evm-nft",{nowMs:r});if(n==="anvil-nft"){if(e.action!=="nft")throw new Error("envelope: Anvil requires NFT action");if(o.chainId!==4663)throw new Error("envelope: Anvil requires chain 4663");if(t.confirmationMode!=="exact-human")throw new Error("policy: Anvil requires exact-human confirmation");if(o.transactions.length!==1)throw new Error("envelope: Anvil requires one atomic action with pre-existing approval");if(Number(e.slippageBps)!==0)throw new Error("envelope: Anvil exact limit requires zero slippageBps");let[f]=o.transactions,p=P(e.destination,"Anvil market");if(P(f.to,"Anvil action target")!==p)throw new Error("envelope: Anvil action target mismatch");X(p,t.destinations,"destination");let w=P(e.contract??e.artifact?.contract,"NFT contract");if(Xt(w,t.nftContracts,"NFT contract"),P(e.marketCollection??e.artifact?.marketCollection,"Anvil market collection")!==w)throw new Error("envelope: Anvil market collection mismatch");let h=P(e.paymentToken??e.artifact?.paymentToken,"payment token");Xt(h,t.erc20Tokens,"ERC20 token");let y=Pl(e,t,{nowMs:r}),b=N(e.tokenId??e.artifact?.tokenId,"tokenId"),S=N(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei");if(o.totalValue!==S||N(f.value??0,"Anvil action value")!==S)throw new Error("envelope: Anvil native swap fee mismatch");if(S>N(t.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"))throw new Error("policy: Anvil native swap fee exceeds cap");let A=Zt(e.nftAction,"nftAction",8).toLowerCase(),k;if(A==="buy"){let v=Ci(e,A),_=Object.entries(t.nftPaymentTokenCaps||{}).find(([U])=>U.toLowerCase()===h)?.[1];if(!_)throw new Error("policy: Anvil payment-token cap required");if(v>N(_.maxPerTradeRaw,"maxPerTradeRaw"))throw new Error("policy: Anvil payment amount exceeds cap");if(e.preconditions?.allowanceVerified!==!0||N(e.preconditions?.allowanceRaw,"allowanceRaw")<v)throw new Error("envelope: Anvil pre-existing allowance proof required");let C=Sr.decodeFunctionData("buySpecificNFT",f.data);if(Sr.encodeFunctionData("buySpecificNFT",[C[0],C[1]]).toLowerCase()!==String(f.data).toLowerCase())throw new Error("envelope: non-canonical Anvil buy calldata");if(BigInt(C[0])!==b)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(C[1])!==v)throw new Error("envelope: Anvil maxCost mismatch");k={kind:"nft",action:"buy",tokenId:b,maxPaymentTokenAmountRaw:v,target:p}}else if(A==="sell"){let v=e.preconditions||{},_=P(v.approvedAddress,"NFT approval address");if(v.nftApprovalVerified!==!0||_!==p&&v.approvedForAll!==!0)throw new Error("envelope: Anvil pre-existing NFT approval proof required");let C=Ci(e,A),z=Sr.decodeFunctionData("sellNFT",f.data);if(Sr.encodeFunctionData("sellNFT",[z[0],z[1]]).toLowerCase()!==String(f.data).toLowerCase())throw new Error("envelope: non-canonical Anvil sell calldata");if(BigInt(z[0])!==b)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(z[1])!==C)throw new Error("envelope: Anvil minPayout mismatch");k={kind:"nft",action:"sell",tokenId:b,minPayoutRaw:C,target:p}}else throw new Error("envelope: unsupported Anvil NFT action");return{...o,provider:n,nftAction:A,tokenId:b,paymentToken:h,paymentTokenDecimals:y.paymentTokenDecimals,anvilAttestation:y,decoded:[k]}}let i=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;if(i?.oraclePrepared===!0&&gi(i,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"}),o.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let s=o.transactions[0],u=nt(s.data);X(u,t.selectors,"selector"),X(s.to,t.destinations,"destination");let a=Ll(s.data,n),c=P(e.contract??e.artifact?.contract,"NFT contract");if(Xt(c,t.nftContracts,"NFT contract"),(a.contract||P(s.to,"NFT contract"))!==c)throw new Error("envelope: mint calldata NFT contract mismatch");if(a.recipient&&a.recipient!==o.owner)throw new Error("envelope: mint calldata recipient mismatch");a.feeRecipient&&Xt(a.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let l=N(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>N(t.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(a.quantity!==l)throw new Error("envelope: mint calldata quantity mismatch");let m=N(e.totalWei??e.artifact?.totalWei,"totalWei");if(o.totalValue!==m)throw new Error("envelope: mint value does not match declared totalWei");if(a.mintType==="allowlist"){let f=BigInt(Math.floor(r/1e3));if(a.startTime>f||a.endTime<=f)throw new Error("policy: SeaDrop allowlist stage is not open");if(a.mintPrice*l!==m)throw new Error("envelope: SeaDrop allowlist price does not match declared totalWei")}if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&N(e.priceWei??e.artifact.priceWei,"priceWei")*l!==m)throw new Error("envelope: mint price does not match declared totalWei");if(m>N(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...o,provider:n,decoded:[{...a,target:P(s.to,"mint target"),value:o.totalValue,gas:o.totalGas,fee:o.totalFee}]}}function Bl(e,{localsWaiver:t=!1}={}){if(!(e in Tn))throw new Error("fee: unknown action");return t?0:Tn[e]}function Qt(e,t,{nowMs:r=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:s=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let u=Zt(e.surface,"surface",16);if(!Ri.has(u))throw new Error("envelope: unsupported public surface");let a=Zt(e.action,"action",32);X(u,t.surfaces,"surface"),X(a,t.actions,"action"),X(e.owner,t.owners,"owner"),X(e.destination,t.destinations,"destination");let c=Ti(t.maxTtlMs,"maxTtlMs"),d=Ti(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>c)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>d)throw new Error("policy: slippage exceeds cap");let l=e.artifact;if(!l||typeof l!="object"||Array.isArray(l))throw new Error("envelope: structured artifact required");if(u==="evm-swap"||u==="evm-bridge")Di(e,t,{nowMs:r,routeAttestationSecret:o});else if(u==="evm-nft")Fi(e,t,{nowMs:r});else if(u==="evm"){if(!["transfer","approve","delegate","identity"].includes(a))throw new Error(a==="mint"?"envelope: generic evm requires transfer or approve; use strict evm-nft for mint action":"envelope: generic evm requires transfer, approve, delegate, or identity");if(a==="swap"||a==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(Number(l.type)===4&&a!=="delegate")throw new Error("envelope: type-4 requires delegate");if(String(l.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(String(l.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: artifact from mismatch with owner");xr({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:s});let p=String(l.data||"0x").toLowerCase(),w=N(l.value,"EVM value");if(a==="delegate"){if(Number(l.type)!==4)throw new Error("envelope: delegate requires type-4");if(p!=="0x")throw new Error("envelope: 7702 delegate calldata must be empty");if(w!==0n)throw new Error("envelope: 7702 delegate cannot transfer native value")}else if(a==="identity"){if(w!==0n)throw new Error("envelope: ERC-8004 identity cannot transfer native value");let g=p.slice(0,10);if(g!=="0xf2c298be"&&g!=="0x0af28bd3")throw new Error("envelope: ERC-8004 selector not allowed")}else if(p==="0x"){if(w===0n)throw new Error("envelope: native EVM transfer value required")}else if(oe(p)){if(w!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else u==="btc"?fn(e,t):u==="sol"?gn(e,t):u==="hl"?Pe(e,t):u==="poly"?Be(e,t):u==="lighter"?De(e,t):u==="evm-order"&&rt(e,t);let m=Number(e.fee?.oracleFeeBps)===0&&Tn[a]!==0;if(e.fee?.waiver||m&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(m&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let f=Bl(a,{localsWaiver:m});if(Number(e.fee?.oracleFeeBps)!==f)throw new Error("fee: final artifact fee mismatch");return!0}var Nn=Object.freeze([...Ri]),py=Object.freeze({...Li});function Cn(e,t){if(e.surface==="hl")return Pe(e,t);if(e.surface==="poly")return Be(e,t);if(e.surface==="lighter")return De(e,t);if(e.surface==="evm-order")return rt(e,t);if(e.surface==="btc")return fn(e,t);if(e.surface==="sol")return gn(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Di(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1),routeAttestationSecret:t.routeAttestationSecret}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(e.surface==="evm-nft"){let r=Fi(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalFee.toString();if(r.provider==="anvil-nft"&&r.nftAction==="buy"){let i=N(e.maxPaymentTokenAmountRaw??e.artifact?.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw").toString(),s=r.totalValue.toString(),u=r.totalFee,a=[{unit:`erc20:${r.paymentToken}`,value:i,notional:i,fee:"0"},{unit:"wei",value:s,notional:(r.totalValue+u).toString(),fee:u.toString()}].sort((c,d)=>c.unit<d.unit?-1:c.unit>d.unit?1:0);return Object.freeze({units:a})}let o=r.totalValue.toString();return Object.freeze({unit:"wei",value:o,notional:(r.totalValue+r.totalFee).toString(),fee:n})}if(String(e.surface).startsWith("evm")){let r=N(e.artifact?.value,"EVM value"),n=N(e.artifact?.gasLimit,"EVM gasLimit"),o=N(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+N(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+N(e.artifact?.operatorFeeWei??0,"EVM operatorFeeWei");return Object.freeze({unit:"wei",value:r.toString(),notional:(r+i).toString(),fee:i.toString()})}throw new Error("envelope: unsupported public surface")}function ji(e={}){let t={};for(let r of Nn){let n=e[r];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${r} requires simulate, sign, and broadcast functions`);t[r]=Object.freeze({simulate:(o,i)=>n.simulate(structuredClone(o),structuredClone(i)),sign:(o,i)=>n.sign(structuredClone(o),structuredClone(i)),broadcast:(o,i,s)=>n.broadcast(o,structuredClone(i),structuredClone(s))})}}return Object.freeze(t)}function vr(e,t){let r=e?.surface||"evm",n=t?.[r];if(!n)throw new Error(`adapter: ${r} is not configured on this self-host`);return n}import{createHash as Vi}from"node:crypto";import{ed25519 as Kl}from"@noble/curves/ed25519.js";import{base58 as Ji}from"@scure/base";import{RawTx as Bn,SigHash as ot,Transaction as Dn}from"@scure/btc-signer";import{Transaction as Fn,keccak256 as $n,verifyTypedData as Pn}from"ethers";import{encode as Dl}from"@msgpack/msgpack";import{keccak256 as Fl,verifyTypedData as jl}from"ethers";var It=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),_n=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Mi(e){let t=BigInt(e);if(t<0n||t>=2n**64n)throw new Error("hl-l1: nonce must fit uint64");let r=Buffer.alloc(8);return r.writeBigUInt64BE(t),r}function Ml(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Dl(e)),Mi(t)];if(r){let s=String(r).replace(/^0x/i,"");if(!/^[0-9a-fA-F]{40}$/.test(s))throw new Error("hl-l1: vaultAddress must be a 20-byte address");i.push(Buffer.from([1]),Buffer.from(s,"hex"))}else i.push(Buffer.from([0]));return n!=null&&i.push(Buffer.from([0]),Mi(n)),Fl(Buffer.concat(i))}function Rn(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:Ml(e,t,{vaultAddress:n,expiresAfter:o})}}function qi(e){let t=e?.typedData;if(t==null)return null;if(typeof t!="object")throw new Error("hl-l1: typedData must match the validated action");if(Object.prototype.hasOwnProperty.call(e,"vaultAddress"))throw new Error("hl-l1: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(e,"expiresAfter"))throw new Error("hl-l1: expiresAfter is not public");let r=Rn(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==It.name||String(t.domain?.version)!==It.version||Number(t.domain?.chainId)!==It.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(It.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(_n.Agent))throw new Error("hl-l1: typedData types must be Hyperliquid Agent");if(t.message?.source!==r.source||String(t.message?.connectionId||"").toLowerCase()!==String(r.connectionId).toLowerCase())throw new Error("hl-l1: typedData message must hash the validated action");return r}async function Hi({wallet:e,action:t,nonce:r,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let s=Rn(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(It,_n,s)}function zi({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:s=null}){try{let u=Rn(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:s}),a=jl(It,_n,u,e);return String(a).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var ql=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function Ln(e){if(e!=null){if(typeof e=="function")throw new Error("lighter: signed tx_info cannot include functions");if(typeof e=="object"){if(typeof e.toJSON=="function")throw new Error("lighter: signed tx_info cannot define toJSON");if(Array.isArray(e)){for(let t of e)Ln(t);return}for(let t of Object.values(e))Ln(t)}}}function Hl(e){if(typeof e=="string"){if(!e.startsWith("{"))throw new Error("lighter: official signed tx_info JSON required");let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("lighter: official signed tx_info JSON required");return t}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("lighter: official signed tx_info JSON required");return Ln(e),JSON.parse(JSON.stringify(e))}function Ir(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function zl(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^-?(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function Ui(e,t,{signed:r=!1}={}){if(typeof e!="number"||!Number.isSafeInteger(e)||!r&&e<0)throw new Error(`lighter: signed ${t} must be an exact numeric integer`);return e}function Ot(e,t,r,n={}){let o=t.filter(s=>e[s]!==void 0&&e[s]!==null);if(o.length===0)throw new Error(`lighter: ${r} required`);let i=o.map(s=>Ui(e[s],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function Ul(e,t,r){let n=t.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length===0)throw new Error(`lighter: ${r} required`);let o=n.map(i=>String(e[i]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${r}`);return e[n[0]]}function kt(e,t,r,n){let o=Ot(e,t,n);if(BigInt(o)!==Ir(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Wl(e,t,r,n){let o=Ot(e,t,n,{signed:!0});if(BigInt(o)!==zl(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Vl(e){let t={};for(let[r,n]of ql.entries()){let o=n.filter(s=>e[s]!==void 0&&e[s]!==null);if(!o.length)continue;let i=o.map(s=>{let u=e[s];if(r<3)return Ui(u,n[0]);if(typeof u!="string"||u.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return u});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);t[n[0]]=i[0]}return t}function er(e,t){let r=Hl(t),n=kt(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=kt(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=kt(r,["Type","type"],e.orderType,"Type"),s=kt(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),u=kt(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),a=kt(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),c=Wl(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=Ot(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=Ot(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),m=Ot(r,["Price","price"],"Price");if(BigInt(d)!==Ir(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==Ir(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(m)!==Ir(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let f=Ul(r,["IsAsk","is_ask","isAsk"],"IsAsk");if(typeof f!="number"||f!==0&&f!==1)throw new Error("lighter: signed IsAsk must be exact numeric 0 or 1");let p=f===1,w=e.side==="sell";if(p!==w)throw new Error("lighter: signed IsAsk must match the prepared side");let g=Ot(r,["txType","tx_type","TxType"],"txType");if(g!==xn)throw new Error("lighter: signed txType must be official create-order");let h={...Vl(r),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:s,ReduceOnly:u,TriggerPrice:a,OrderExpiry:c,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(m),IsAsk:p?1:0,txType:g},y=JSON.stringify(h),b=JSON.parse(y);if(b.MarketIndex!==Number(d)||b.BaseAmount!==Number(l)||b.Price!==Number(m)||b.IsAsk!==(p?1:0)||b.txType!==g)throw new Error("lighter: canonical tx_info mutated");return{txType:g,txInfo:y,submitTo:Sn(e.submitTo)}}function Wi(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var Tt=e=>{if(typeof e!="string"||e.length===0||e.length>262144||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return null;let t=Buffer.from(e,"base64");return t.toString("base64")===e?t:null},kr=e=>String(e||"").toLowerCase();function Jl(e,t){if(typeof e!="string")return!1;let r,n;try{r=Fn.from(e),n=Fn.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,type:t.type,accessList:t.accessList,authorizationList:t.authorizationList})}catch{return!1}return kr(r.from)!==kr(t.from)||kr(r.to)!==kr(t.to)?!1:r.unsignedHash===n.unsignedHash}function Gl(e){let t=Buffer.from(Bn.encode(e)),r=Vi("sha256").update(t).digest();return Buffer.from(Vi("sha256").update(r).digest()).reverse().toString("hex")}function Ki(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Gl(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))return!1;let t=e.nonWitnessUtxo.outputs?.[e.index];return t?BigInt(e.witnessUtxo.amount)===BigInt(t.amount)&&Buffer.from(e.witnessUtxo.script||[]).equals(Buffer.from(t.script||[])):!1}function Yl(e,t){let r=Tt(e),n=Tt(t.psbt);if(!r||!n)return!1;try{let o=Dn.fromPSBT(n),i=Dn.fromPSBT(r);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let s=0;s<i.inputsLength;s++){let u=i.getInput(s),a=o.getInput(s);if(!Ki(a)||!Ki(u))return!1;let c=(h,y)=>{if(h==null&&y==null)return!0;if(h==null||y==null)return!1;try{return Buffer.from(h).equals(Buffer.from(y))}catch{return!1}},d=(h,y)=>{if(h==null&&y==null)return!0;if(h==null||y==null)return!1;try{return Buffer.from(Bn.encode(h)).equals(Buffer.from(Bn.encode(y)))}catch{return c(h,y)}};if(!!u.witnessUtxo!=!!a.witnessUtxo||u.witnessUtxo&&(BigInt(u.witnessUtxo.amount)!==BigInt(a.witnessUtxo.amount)||!c(u.witnessUtxo.script,a.witnessUtxo.script))||!d(u.nonWitnessUtxo,a.nonWitnessUtxo)||!c(u.redeemScript,a.redeemScript)||!c(u.witnessScript,a.witnessScript)||u.sighashType!==void 0&&u.sighashType!==ot.DEFAULT&&u.sighashType!==ot.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===ot.ALL,m=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===ot.ALL:!1;for(let h of u.partialSig||[]){let y=Array.isArray(h)?h[1]:h;if(!l(y))return!1}if(u.tapKeySig&&!m(u.tapKeySig))return!1;for(let h of u.tapScriptSig||[]){let y=Array.isArray(h)?h[1]:h;if(!m(y))return!1}let f=h=>h[h.length-1]===ot.ALL,p=h=>h.length>=9&&h.length<=73&&h[1]===h.length-3&&h[2]===2,w=h=>{let y=!1;for(let b of h)if(b instanceof Uint8Array){if(b[0]===48){if(!p(b)||!f(b))return!1;y=!0;continue}if(b.length===64){y=!0;continue}if(b.length===65){if(b[64]!==ot.ALL&&b[64]!==ot.DEFAULT)return!1;y=!0}}return y};if(u.finalScriptWitness){let h;if(Array.isArray(u.finalScriptWitness))h=u.finalScriptWitness;else if(u.finalScriptWitness instanceof Uint8Array){let y=u.finalScriptWitness,b=k=>{let v=y[k];return v===void 0?null:v<253?{value:v,next:k+1}:v===253?{value:y[k+1]|y[k+2]<<8,next:k+3}:null},S=b(0);if(!S)return!1;h=[];let A=S.next;for(let k=0;k<S.value;k++){let v=b(A);if(!v||A+v.value>y.length)return!1;h.push(y.slice(v.next,v.next+v.value)),A=v.next+v.value}if(A!==y.length)return!1}else return!1;if(!h.length||!w(h))return!1}if(u.finalScriptSig instanceof Uint8Array&&u.finalScriptSig.length){let h=u.finalScriptSig,y=[],b=0;for(;b<h.length;){let S=h[b];if(S>=1&&S<=75){if(b+1+S>h.length)return!1;y.push(h.slice(b+1,b+1+S)),b+=1+S;continue}if(S===76){let A=h[b+1];if(A===void 0||b+2+A>h.length)return!1;y.push(h.slice(b+2,b+2+A)),b+=2+A;continue}return!1}if(!y.length||!w(y))return!1}if(![u.partialSig,u.tapKeySig,u.tapScriptSig,u.finalScriptSig,u.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function Gi(e){let t=0,r=0,n=0;for(;n<e.length&&n<3;){let o=e[n++];if(t|=(o&127)<<r,(o&128)===0)return{value:t,offset:n};r+=7}return null}function Xl(e,t,r){let n=Tt(e),o=Tt(t.messageBase64);if(!n||!o)return!1;let i=Gi(n);if(!i||i.value!==1||i.offset!==1)return!1;let s=i.offset+64;if(s>=n.length)return!1;let u=n.subarray(i.offset,s),a=n.subarray(s);if(!a.equals(o))return!1;try{let c=Ji.decode(String(r));return c.length===32&&Kl.verify(u,a,c)}catch{return!1}}function Yi(e,t,r,n){if(e==="evm-order"){let o=r?.domain||r?.typedData?.domain,i=r?.types||r?.typedData?.types,s=r?.message||r?.typedData?.message;if(!o||!i||!s)return!1;try{return String(Pn(o,i,s,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}}if(String(e).startsWith("evm"))return Jl(t,r);if(e==="btc")return Yl(t,r);if(e==="sol")return Xl(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String(Pn(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return zi({signature:t,action:r?.action,nonce:r?.nonce,isMainnet:!String(r?.submitTo||"").includes("testnet"),owner:n?.owner})}if(e==="poly"&&r?.domain&&r.types&&r.message)try{return String(Pn(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return er(r,t),!0}catch{return!1}return!1}function Xi(e,t){try{if(e==="evm-order")return $n(t);if(String(e).startsWith("evm"))return Fn.from(t).hash;if(e==="btc"){let r=Tt(t);if(!r)return null;let n=Dn.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=Tt(t);if(!r)return null;let n=Gi(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Ji.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return $n(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return $n(t)}catch{}return null}var td=e=>String(e||"").toLowerCase();function G(e){return Zl("sha256").update(JSON.stringify(e)).digest("hex")}function Nr(e,t,r={}){return xr(e,t,r)}async function rd(e,t={}){if(!ke(e?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(typeof t.estimateNetworkFees!="function")throw new Error("policy: rollup fee estimate required");let r=await t.estimateNetworkFees(e);if(!r||r.l1FeeWei===void 0||r.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");return{l1FeeWei:String(r.l1FeeWei),operatorFeeWei:String(r.operatorFeeWei)}}function Qi(e,t,r=!1){if(!ke(e?.chainId))return!0;if(e.l1FeeWei===void 0||e.operatorFeeWei===void 0)throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei");if(r||t!=null){if(!t||t.l1FeeWei===void 0||t.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let n=BigInt(e.l1FeeWei)+BigInt(e.operatorFeeWei),o=BigInt(t.l1FeeWei)+BigInt(t.operatorFeeWei);if(n<o)throw new Error("policy: rollup fee attestation understates estimate")}return!0}function es(e){if(e==null)return null;let t={tenantId:String(e.tenantId||"").trim(),runId:String(e.runId||"").trim(),handoffHash:String(e.handoffHash||""),idempotencyKey:String(e.idempotencyKey||""),legIndex:e.legIndex,legCount:e.legCount};if(!t.tenantId||!t.runId||!/^[0-9a-f]{64}$/.test(t.handoffHash)||!/^sha256:[0-9a-f]{64}$/.test(t.idempotencyKey)||!Number.isSafeInteger(t.legIndex)||t.legIndex<0||!Number.isSafeInteger(t.legCount)||t.legCount<1||t.legIndex>=t.legCount)throw new Error("confirmation: binding is invalid");return t}var Or=class{#e=new Map;constructor({now:t=Date.now}={}){this.now=t}issue({artifact:t,owner:r,ttlMs:n=6e4,binding:o}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let i=Ql(32).toString("hex");return this.#e.set(i,{digest:G(t),owner:td(r),expiresAtMs:this.now()+n,binding:es(o)}),i}consume(t,r,n){let o=this.#e.get(String(t));if(!o)throw new Error("confirmation: used or unknown nonce");if(o.expiresAtMs<=this.now())throw this.#e.delete(String(t)),new Error("confirmation: expired nonce");let i=Buffer.from(o.digest,"hex"),s=Buffer.from(G(r),"hex");if(!ed(i,s))throw new Error("confirmation: artifact mismatch");if(JSON.stringify(o.binding)!==JSON.stringify(es(n)))throw new Error("confirmation: execution binding mismatch");return this.#e.delete(String(t)),o}clear(){this.#e.clear()}};function nd(e){let t=String(e?.data||"0x").toLowerCase(),r=BigInt(e?.value??0);if(t==="0x"){if(r<=0n)throw new Error("signer: native EVM transfer value required");return!0}if(oe(t)){if(r!==0n)throw new Error("signer: EVM approval cannot transfer native value");return!0}throw new Error("signer: unsupported EVM calldata; use a versioned envelope")}function od(e={},t={}){let r={};for(let n of new Set([...Object.keys(e||{}),...Object.keys(t||{})]))r[n]=(BigInt(t?.[n]??0)-BigInt(e?.[n]??0)).toString();return r}function id(e){return e==="evm"||e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Tr(e,t){let r=String(t||"");if(e==="evm-order"||String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(r);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(r);if(e==="sol")try{let n=Zi.decode(r);return n.length===64&&Zi.encode(n)===r}catch{return!1}return e==="hl"?/^0x[0-9a-fA-F]{64}$/.test(r):e==="poly"?/^0x[0-9a-fA-F]{64}$/.test(r):!1}function ts(e,t,r){return!Tr(e,t)||!Tr(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function sd(e){let t=e?.confirmationMode;if(t!=="exact-human"&&t!=="auto-within-rails")throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");return t}async function jn({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:s,nowMs:u}){let a=sd(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(a!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(t?.triggerAttestation,e,u())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(a!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(s)return n.confirmations.consume(r,e,n.confirmationBinding);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=u())throw new Error("confirmation: expired nonce");return i}function ad(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function cd(e,t){return e&&ad(e.surface)?Ar(e):[t]}function ud(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!ts(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function ld(e,t){let r=e?.verifiedBefore??e?.before,n=e?.verifiedAfter??e?.after;return{transactionHash:t,status:e?.status,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:od(r,n)}}function dd(e){return Number.isSafeInteger(e)&&e>0?"commit":"settle-failed"}async function Mn(e,t,r){if(!r.isArmed())throw new Error("signer: disarmed");let n=typeof r.armGeneration=="function",o=typeof r.broadcastWithArmFence=="function";if(n!==o)throw new Error("signer: arm generation and broadcast fence must be configured together");let i=n?r.armGeneration():null,s=e?.version===1&&e?.surface?e:null,u=s?s.artifact:(()=>{let{tradeId:b,...S}=e||{};return S})(),a=cd(s,u),c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,d=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),l=await jn({artifact:e,envelope:s,nonce:t,deps:r,policy:c,confirmation:null,consumeNonce:!0,nowMs:d}),m=G(e),f=(b={})=>{s?Qt(s,c,b):(Nr(u,c,{nowMs:b.nowMs,networkFees:b.networkFees,requireNetworkFees:b.requireNetworkFees}),nd(u))},p=async b=>{let S=!s||id(s.surface),A=S?await rd(b,r):void 0;return{nowMs:d(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:A,requireNetworkFees:S&&ke(b?.chainId)}};f({nowMs:d(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let b of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[b]!="function")throw new Error(`signer: ${b} is required`);let w=r.reserveLedger(s||e,c);if(!w)throw new Error("signer: ledger reservation required");let g=!1,h=[];try{for(let[b,S]of a.entries()){if(typeof r.simulate!="function"||await r.simulate(S,s)!==!0)throw new Error("signer: strict affirmative simulation required");let A=await p(S);if((A.requireNetworkFees||A.networkFees!=null)&&Qi(S,A.networkFees,A.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,l=await jn({artifact:e,envelope:s,nonce:t,deps:r,policy:c,confirmation:l,consumeNonce:!1,nowMs:d}),f(A),r.validateReservation(w,c,s&&typeof r.decodeEconomics=="function"?r.decodeEconomics(s,c):void 0),g=!0;let k=await r.sign(S,s);if(typeof r.verifySigned!="function"||await r.verifySigned(k,S,s)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");let v=s?.surface||"evm",_=Xi(v,k);if(r.executionAttempt&&await r.executionAttempt.recordSigned({txIndex:b,txCount:a.length,surface:v,signedTransactionId:_}),!r.isArmed())throw new Error("signer: disarmed before broadcast");if(G(e)!==m)throw new Error("signer: artifact mutated after signing");c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,l=await jn({artifact:e,envelope:s,nonce:t,deps:r,policy:c,confirmation:l,consumeNonce:!1,nowMs:d});let C=await p(S);(C.requireNetworkFees||C.networkFees!=null)&&Qi(S,C.networkFees,C.requireNetworkFees),f(C),r.validateReservation(w,c,s&&typeof r.decodeEconomics=="function"?r.decodeEconomics(s,c):void 0),r.executionAttempt&&await r.executionAttempt.recordBroadcastAuthorized({txIndex:b});let z=()=>r.broadcast(k,S,s),U=o?await r.broadcastWithArmFence(i,z):await z(),R=U?.status,$=ud(U,v);if(!ts(v,$,_))throw new Error("signer: receipt transaction hash does not match signed bytes");if(R===0||R==="0x0")throw Tr(v,$)?(r.executionAttempt&&await r.executionAttempt.recordCanonicalReceipt({txIndex:b,receipt:U}),dd(h.length)==="commit"?r.commitLedger(w):r.settleFailedLedger(w),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(R!==1&&R!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Tr(v,$))throw new Error("signer: successful broadcast requires a valid transaction hash");r.executionAttempt&&await r.executionAttempt.recordCanonicalReceipt({txIndex:b,receipt:U}),h.push(ld(U,$))}}catch(b){throw g||r.releaseLedger(w),b}if(r.commitLedger(w),h.length===1){let b={receipt:h[0]};return s?.surface==="evm-bridge"&&(b.originStatus="success",b.destinationStatus="unverified",b.destinationSuccess=!1,b.note="Origin-chain receipts do not prove destination-chain settlement."),b}let y={receipts:h,status:"success"};return s?.surface==="evm-bridge"&&(y.originStatus="success",y.destinationStatus="unverified",y.destinationSuccess=!1,y.note="Origin-chain receipts do not prove destination-chain settlement."),y}var rs=new Set(["127.0.0.1","::1","localhost"]),md=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&pd(r,n)},O=(e,t,r)=>{let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function wd(e){let t=String(e||"");if(t.startsWith("[")){let r=t.indexOf("]");if(r>1)return t.slice(1,r)}return t.split(":")[0]}var Nt=e=>new Promise((t,r)=>{let n=0,o=[],i=!1;e.on("data",s=>{n+=s.length,n>64*1024&&!i?(i=!0,r(new Error("request refused")),e.resume()):i||o.push(s)}),e.on("end",()=>{if(!i)try{t(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{r(new Error("request refused"))}}),e.on("error",r)}),ns=e=>e?.idempotencyKey===void 0?void 0:{tenantId:e.tenantId,runId:e.runId,handoffHash:e.handoffHash,idempotencyKey:e.idempotencyKey,legIndex:e.legIndex,legCount:e.legCount},hd=e=>e==="btc"||e==="sol"||["evm","evm-swap","evm-bridge","evm-nft"].includes(e);function os(e={}){let t=e.host||"127.0.0.1";if(!rs.has(t))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let c of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[c]!="function")throw new Error(`signer: ${c} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Or,n=e.pending||new Map,o=(c,d)=>{try{e.ledgerObserver?.[c]?.(d)}catch{}};function i(c){let d=c.artifact?.version===1&&c.artifact?.surface?c.artifact:null,l=d?.artifact||c.artifact||{};return{id:c.digest.slice(0,8),digest:c.digest,surface:d?.surface||"evm",action:d?.action||"evm",chain:l.chainId??l.network??null,to:l.to||d?.destination||null,value:l.value??l.message?.sellAmount??l.message?.makingAmount??null,receiver:l.message?.receiver||l.typedData?.message?.receiver||null,maker:l.message?.maker||l.typedData?.message?.maker||null,makingAmount:l.message?.makingAmount||l.typedData?.message?.makingAmount||null,takingAmount:l.message?.takingAmount||l.typedData?.message?.takingAmount||null,sellAmount:l.message?.sellAmount||l.typedData?.message?.sellAmount||null,buyAmount:l.message?.buyAmount||l.typedData?.message?.buyAmount||null,kind:l.kind||null,type:l.type??null,authorizationList:l.authorizationList||null,feeAmount:l.message?.feeAmount||l.typedData?.message?.feeAmount||null,createdAtMs:c.createdAtMs}}function s(c){let d=String(c||"").trim().toLowerCase().replace(/^0x/,"");return d?[...n.values()].filter(l=>l.digest.toLowerCase().startsWith(d)||l.digest.slice(0,8)===d):[...n.values()]}let u=e.origin||`http://${t}`;return fd.createServer(async(c,d)=>{try{let l=String(c.headers.authorization||"").replace(/^Bearer /i,"");if(!md(l,e.token))return O(d,401,{error:"unauthorized"});let m=wd(c.headers.host);if(!rs.has(m))return O(d,403,{error:"host refused"});if(c.headers.origin&&c.headers.origin!==u)return O(d,403,{error:"origin refused"});if(c.method==="GET"&&c.url==="/status"){let f=typeof e.readPolicy=="function"?e.readPolicy():e.policy,p=new Set(Nn),w=Array.isArray(f?.surfaces)?f.surfaces.filter(g=>typeof g=="string"&&p.has(g)):[];return O(d,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:w,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(c.method==="POST"&&c.url==="/disarm")return await e.disarm(),r.clear(),n.clear(),O(d,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(c.method))return O(d,405,{error:"request refused"});if(c.method==="POST"&&String(c.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return O(d,415,{error:"request refused"});if(c.method==="GET"&&c.url==="/pending"){let f=[...n.values()].map(i);return O(d,200,{ok:!0,armed:e.isArmed?.()===!0,count:f.length,items:f})}if(c.method==="GET"&&String(c.url||"").startsWith("/execute/status?")){if(!e.executionOutbox)return O(d,503,{error:"execution outbox unavailable"});let f=new URL(String(c.url),u).searchParams.get("attemptKey"),p=await e.executionOutbox.inspect(f);return p?O(d,200,{ok:!0,attempt:p}):O(d,404,{error:"execution attempt not found"})}if(c.method==="POST"&&c.url==="/pending"){if(e.autonomous===!0)return O(d,403,{error:"autonomous signer does not queue human approvals"});let p=(await Nt(c)).artifact;if(!p||typeof p!="object")return O(d,400,{error:"artifact required"});let w=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(w?.confirmationMode!=="exact-human")return O(d,403,{error:"exact-human policy required"});let g=typeof e.nowMs=="function"?e.nowMs():Date.now();if(p?.surface==="cex"){if(typeof e.inspectCex!="function")return O(d,403,{error:"cex execution unavailable"});e.inspectCex(p,w,g)}else if(p?.version===1&&p?.surface)Qt(p,w,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:b,...S}=p||{};Nr(S,w,{nowMs:g})}let h=G(p),y=p?.surface==="cex"?Object.freeze(structuredClone(p)):p;return n.set(h,{artifact:y,digest:h,createdAtMs:g}),o("queued",{digest:h,createdAtMs:g}),O(d,200,{ok:!0,...i(n.get(h))})}if(c.method==="POST"&&c.url==="/ack"){if(e.autonomous===!0)return O(d,403,{error:"autonomous signer does not accept messaging acks"});let f=await Nt(c),p=s(f.digest||f.id);if(p.length===0)return O(d,404,{error:"no pending artifact"});if(p.length>1)return O(d,409,{error:"ambiguous digest; pass more hex"});let w=p[0];if((typeof e.readPolicy=="function"?e.readPolicy():e.policy)?.confirmationMode!=="exact-human")return O(d,403,{error:"exact-human policy required"});if(e.isArmed?.()!==!0)return O(d,403,{error:"signer is disarmed"});let h=e.verifyOwnerProof||e.verifyCexOwnerProof;if(typeof h!="function"||h(f.ownerProof,{digest:w.digest})!==!0)return O(d,403,{error:"exact owner Allow proof required"});if(w.artifact?.surface==="cex"){if(typeof e.cexExecute!="function")return O(d,403,{error:"cex execution unavailable"});n.delete(w.digest),o("approved",{digest:w.digest});let S;try{S=await e.cexExecute(w.artifact)}catch(A){throw o("failed",{digest:w.digest,reason:String(A?.message||A)}),A}return o("executed",{digest:w.digest,owner:w.artifact?.owner??w.artifact?.from,result:S}),O(d,200,{ok:!0,executed:!0,digest:w.digest,id:w.digest.slice(0,8),result:S})}n.delete(w.digest);let y=r.issue({artifact:w.artifact,owner:w.artifact?.owner??w.artifact?.from,ttlMs:f.ttlMs});o("approved",{digest:w.digest});let b;try{b=await Mn(w.artifact,y,{...e,confirmations:r})}catch(S){throw o("failed",{digest:w.digest,reason:String(S?.message||S)}),S}return o("executed",{digest:w.digest,owner:w.artifact?.owner??w.artifact?.from,result:b}),O(d,200,{ok:!0,executed:!0,confirmationNonce:y,digest:w.digest,id:w.digest.slice(0,8),result:b})}if(c.method==="POST"&&c.url==="/deny"){let f=await Nt(c),p=s(f.digest||f.id);return p.length===0?O(d,404,{error:"no pending artifact"}):p.length>1?O(d,409,{error:"ambiguous digest; pass more hex"}):(n.delete(p[0].digest),o("denied",{digest:p[0].digest}),O(d,200,{ok:!0,denied:!0,id:p[0].digest.slice(0,8)}))}if(c.method==="POST"&&c.url==="/confirm"){if(e.autonomous===!0)return O(d,403,{error:"autonomous signer does not issue human confirmation nonces"});let f=await Nt(c);if(f.artifact?.surface==="cex")return O(d,403,{error:"cex requires pending owner ack"});let p=G(f.artifact),w=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(w?.confirmationMode!=="exact-human")return O(d,403,{error:"exact-human policy required"});let g=typeof e.nowMs=="function"?e.nowMs():Date.now();if(f.artifact?.version===1&&f.artifact?.surface)Qt(f.artifact,w,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:h,...y}=f.artifact||{};Nr(y,w,{nowMs:g})}return typeof e.confirmArtifact!="function"?O(d,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(f.artifact,p,w)!==!0?O(d,400,{error:"exact human confirmation refused"}):O(d,200,{confirmationNonce:r.issue({artifact:f.artifact,owner:f.artifact?.owner??f.artifact?.from,ttlMs:f.ttlMs,binding:ns(f)})})}if(c.method==="POST"&&c.url==="/execute/reconcile"){let f=await Nt(c);if(!e.executionOutbox||typeof e.observeExecutionTransaction!="function")return O(d,503,{error:"execution reconciliation unavailable"});let p=await e.executionOutbox.reconcile({attemptKey:f.attemptKey,observeTransaction:e.observeExecutionTransaction,commitLedger:e.commitLedger,settleFailedLedger:e.settleFailedLedger});return O(d,200,{ok:!0,attempt:p})}if(c.method==="POST"&&c.url==="/execute"){let f=await Nt(c);if(f.artifact?.surface==="cex")return O(d,403,{error:"cex requires pending owner ack"});let p=typeof e.executeArtifact=="function"?e.executeArtifact:Mn;if(f.idempotencyKey!==void 0){if(!hd(f.artifact?.surface))return O(d,422,{error:"surface does not support durable Team execution reconciliation"});if(!e.executionOutbox)return O(d,503,{error:"execution outbox required for idempotent execution"});let g=await e.executionOutbox.begin({attemptKey:f.idempotencyKey,artifact:f.artifact,tenantId:f.tenantId,runId:f.runId,handoffHash:f.handoffHash,legIndex:f.legIndex,legCount:f.legCount});if(g.state==="recovery-required")return O(d,409,{error:"execution recovery-required; automatic replay refused",transactions:g.transactions||[]});if(g.state==="failed")return O(d,409,{error:"execution has a canonical failed receipt",receipts:g.receipts||[]});if(g.state==="completed")return n.delete(G(f.artifact)),O(d,200,g.result);let h=await e.executionOutbox.acquireExecutor({attemptKey:f.idempotencyKey}),y={recordSigned:b=>e.executionOutbox.recordSigned({attemptKey:f.idempotencyKey,leaseId:h,...b}),recordBroadcastAuthorized:b=>e.executionOutbox.recordBroadcastAuthorized({attemptKey:f.idempotencyKey,leaseId:h,...b}),recordCanonicalReceipt:b=>e.executionOutbox.recordCanonicalReceipt({attemptKey:f.idempotencyKey,leaseId:h,...b})};try{let b={...e,confirmations:r,confirmationBinding:ns(f),executionAttempt:y,reserveLedger:(A,k)=>e.reserveLedger(A,k,{retryReleasedTradeId:g.retryReleasedTradeId})},S=await p(f.artifact,f.confirmationNonce,b);return await e.executionOutbox.complete({attemptKey:f.idempotencyKey,leaseId:h,result:S}),n.delete(G(f.artifact)),O(d,200,S)}catch(b){throw await e.executionOutbox.failPreSubmission({attemptKey:f.idempotencyKey,leaseId:h,error:b}),b}finally{await e.executionOutbox.releaseExecutor({attemptKey:f.idempotencyKey,leaseId:h})}}let w=await p(f.artifact,f.confirmationNonce,{...e,confirmations:r});return n.delete(G(f.artifact)),O(d,200,w)}return O(d,404,{error:"not found"})}catch(l){e.onError?.(String(l?.message||l));let m=String(c.url||"");return m==="/pending"||m==="/ack"||m==="/deny"?O(d,400,{error:String(l?.message||"request refused").slice(0,300)}):O(d,400,{error:"request refused"})}})}import{closeSync as Cr,constants as Ke,fchmodSync as ss,fsyncSync as Hn,lstatSync as ps,mkdirSync as Td,openSync as zn,readFileSync as ms,renameSync as Nd,rmSync as as,writeFileSync as cs}from"node:fs";import{randomBytes as Un}from"node:crypto";import{dirname as Cd,resolve as _d}from"node:path";import{wordlists as gd}from"ethers";var yd=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),bd=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Ed=new Set([12,15,18,21,24]);function xd(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Ed.has(t.length)&&t.every(r=>gd.en.getWordIndex(r)>=0)}var Sd=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,Ad=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,vd=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function Id(e){let t=is(e);return vd.has(t)||Ad.test(t)}var tr=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function is(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function kd(e){let t=is(e);return[...yd].some(r=>t.includes(r))}function Od(e,t,r){if(typeof t=="string"){if(bd.some(n=>n.test(t))||xd(t))throw new tr(r);if(Sd.test(t)&&!Id(e))throw new tr(r)}}function qn(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return Od(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((o,i)=>qn(o,`${t}[${i}]`,r));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${t}`);let n={};for(let o of Object.keys(e).sort()){let i=`${t}.${o}`;if(kd(o))throw new tr(i);e[o]!==void 0&&(n[o]=qn(e[o],i,o))}return n}function Ct(e){return qn(e)}var ws=2,us=Ke.O_NOFOLLOW??0;function he(e){return e==null?e:structuredClone(e)}function ls(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function hs(e,t,r=!1){let n=r?!e.isDirectory():!e.isFile(),o=typeof process.getuid=="function"&&e.uid!==process.getuid();if(e.isSymbolicLink()||n||o||(e.mode&18)!==0)throw new Error(`${t} must be owner-controlled`)}function ds(e){Td(e,{recursive:!0,mode:448}),hs(ps(e),"execution outbox directory",!0)}function Rd(){return{version:ws,attempts:{}}}function gs(e){if(!e||e.version!==ws||!e.attempts||typeof e.attempts!="object"||Array.isArray(e.attempts))throw new Error("execution outbox is invalid");return Ct(e),he(e)}function fs(e){try{let t=ps(e);if(hs(t,"execution outbox file"),t.size>16*1024*1024)throw new Error("execution outbox is too large");return gs(JSON.parse(ms(e,"utf8")))}catch(t){if(t?.code==="ENOENT")return Rd();throw t}}function Ld(e){let t=String(e?.attemptKey||"");if(!/^sha256:[0-9a-f]{64}$/.test(t))throw new TypeError("execution attemptKey must be a sha256 digest");let r=String(e?.tenantId||"").trim(),n=String(e?.runId||"").trim(),o=String(e?.handoffHash||""),i=e?.legIndex,s=e?.legCount;if(!r||!n||!/^[0-9a-f]{64}$/.test(o))throw new TypeError("execution attempt identity is incomplete");if(!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(s)||s<1||i>=s)throw new TypeError("execution attempt leg identity is invalid");return{attemptKey:t,tenantId:r,runId:n,handoffHash:o,legIndex:i,legCount:s}}function $d(e){let t=e?.txIndex,r=e?.txCount,n=String(e?.surface||"").trim(),o=String(e?.signedTransactionId||"").trim();if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(r)||r<1||t>=r)throw new TypeError("execution transaction identity is invalid");if(!n||!o)throw new TypeError("execution signed transaction identity is required");return{txIndex:t,txCount:r,surface:n,signedTransactionId:o}}function Oe(e,t){let r=e.attempts[String(t||"")];if(!r)throw new Error("execution attempt is unknown");return r}function _t(e,t){let r=e.executorLeaseId||e.recoveryLeaseId;if(!r)throw new Error("active execution attempt lease required");if(r!==t)throw new Error("execution attempt lease conflict")}function ys(e){if(!Number.isSafeInteger(e)||e<1)return null;try{let t=ms(`/proc/${e}/stat`,"utf8");return t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[19]||null}catch{return null}}function Pd(e){let t=Number(e?.pid),r=String(e?.startToken||"");if(!Number.isSafeInteger(t)||t<1||!r)return!0;if(r==="pid-only")try{return process.kill(t,0),!0}catch(o){return o?.code!=="ESRCH"}let n=ys(t);return n===null?!1:n===r}function Bd(e){return e.transactions.length>0&&e.transactions.length===e.transactionCount&&e.transactions.every(t=>t?.state==="confirmed"||t?.state==="failed")}function Dd(e,t){Bd(e)&&(e.state=e.transactions.some(r=>r.state==="failed")?"failed":"receipts-confirmed",e.receiptsRecordedAtMs=t())}function bs({path:e,now:t=Date.now,leaseOwner:r,isLeaseOwnerAlive:n=Pd}={}){if(!e)throw new TypeError("execution outbox path is required");if(typeof n!="function")throw new TypeError("execution lease liveness checker is required");let o=r||{pid:process.pid,startToken:ys(process.pid)||"pid-only"};if(!Number.isSafeInteger(Number(o.pid))||!String(o.startToken||""))throw new Error("execution lease owner identity is unavailable");let i=_d(e),s=Cd(i),u=`${i}.lock`;function a(d){ds(s);let l,m=!1,f=`${i}.${process.pid}.${Un(8).toString("hex")}.tmp`,p;try{l=zn(u,Ke.O_CREAT|Ke.O_EXCL|Ke.O_WRONLY|us,384),m=!0,cs(l,`${process.pid}
8
- `,"utf8"),Hn(l),ss(l,384);let w=fs(i),g=d(w),h=gs(w);p=zn(f,Ke.O_CREAT|Ke.O_EXCL|Ke.O_WRONLY|us,384),cs(p,`${JSON.stringify(h)}
9
- `,"utf8"),Hn(p),ss(p,384),Cr(p),p=void 0,Nd(f,i);let y=zn(s,Ke.O_RDONLY);try{Hn(y)}finally{Cr(y)}return he(g)}finally{p!==void 0&&Cr(p),as(f,{force:!0}),l!==void 0&&Cr(l),m&&as(u,{force:!0})}}let c={async begin(d){let l=Ld(d),m=G(d.artifact);return a(f=>{let p=f.attempts[l.attemptKey];if(p){if(p.artifactDigest!==m||p.tenantId!==l.tenantId||p.runId!==l.runId||p.handoffHash!==l.handoffHash||p.legIndex!==l.legIndex||p.legCount!==l.legCount)throw new Error("execution attempt conflict: identity or artifact changed");return p.state==="completed"?{state:"completed",result:he(p.result)}:p.state==="pre-sign-failed"?(p.state="reserved",p.retryCount=(p.retryCount||0)+1,p.reservedAtMs=t(),delete p.failure,{state:"started",retryReleasedTradeId:p.tradeId||null}):p.state==="failed"?{state:"failed",receipts:he(p.transactions.map(w=>w.receipt))}:{state:"recovery-required",transactions:he(p.transactions)}}return f.attempts[l.attemptKey]={...l,artifactDigest:m,tradeId:d.artifact?.tradeId?String(d.artifact.tradeId):null,surface:String(d.artifact?.surface||"evm"),action:d.artifact?.action?String(d.artifact.action):null,state:"reserved",transactions:[],transactionCount:null,retryCount:0,createdAtMs:t(),reservedAtMs:t()},{state:"started"}})},async acquireExecutor({attemptKey:d}){let l=Un(32).toString("hex");return a(m=>{let f=Oe(m,d);if(["completed","failed","partial"].includes(f.state))throw new Error("execution attempt is terminal");if(f.executorLeaseId||f.recoveryLeaseId)throw new Error("execution attempt already has an active lease");return f.executorLeaseId=l,f.executorLeaseAcquiredAtMs=t(),f.executorLeaseOwnerPid=Number(o.pid),f.executorLeaseOwnerStartToken=String(o.startToken),l})},async releaseExecutor({attemptKey:d,leaseId:l}){return a(m=>{let f=Oe(m,d);if(f.executorLeaseId&&f.executorLeaseId!==l)throw new Error("execution executor lease conflict");return f.executorLeaseId===l&&(delete f.executorLeaseId,delete f.executorLeaseAcquiredAtMs,delete f.executorLeaseOwnerPid,delete f.executorLeaseOwnerStartToken),{released:!0}})},async recordSigned(d){let l=$d(d);return a(m=>{let f=Oe(m,d.attemptKey);if(_t(f,d.leaseId),!["reserved","signed","broadcast-authorized"].includes(f.state))throw new Error("execution attempt cannot record signed identity in current state");if(f.transactionCount!=null&&f.transactionCount!==l.txCount)throw new Error("execution transaction count conflict");f.transactionCount=l.txCount;let p=f.transactions[l.txIndex];if(p&&(!ls(p.signedTransactionId,l.signedTransactionId)||p.surface!==l.surface))throw new Error("execution signed transaction conflict");return f.transactions[l.txIndex]={...p||{},...l,state:p?.state||"signed",signedAtMs:p?.signedAtMs||t()},f.state="signed",f.transactions[l.txIndex]})},async recordBroadcastAuthorized({attemptKey:d,txIndex:l,leaseId:m}){return a(f=>{let p=Oe(f,d);_t(p,m);let w=p.transactions[l];if(!w||!["signed","broadcast-authorized"].includes(w.state))throw new Error("execution transaction must be durably signed before broadcast authorization");return w.state="broadcast-authorized",w.broadcastAuthorizedAtMs||=t(),p.state="broadcast-authorized",w})},async recordCanonicalReceipt({attemptKey:d,txIndex:l,receipt:m,leaseId:f}){return Ct(m),a(p=>{let w=Oe(p,d);_t(w,f);let g=w.transactions[l];if(!g||!["broadcast-authorized","confirmed","failed"].includes(g.state))throw new Error("execution transaction was not authorized for broadcast");let h=m?.transactionHash??m?.hash;if(!ls(h,g.signedTransactionId))throw new Error("execution receipt transaction identity conflict");let y=m?.status===0||m?.status==="0x0",b=m?.status===1||m?.status==="0x1";if(!y&&!b)throw new Error("execution receipt is not canonical");if(g.receipt&&JSON.stringify(g.receipt)!==JSON.stringify(m))throw new Error("execution canonical receipt conflict");return g.receipt=he(m),g.state=y?"failed":"confirmed",g.receiptRecordedAtMs||=t(),Dd(w,t),g})},async failPreSubmission({attemptKey:d,error:l,leaseId:m}){return a(f=>{let p=Oe(f,d);return _t(p,m),p.transactions.some(w=>w?.signedTransactionId)?{state:"recovery-required"}:(p.state="pre-sign-failed",p.failure=String(l?.message||l||"pre-sign failure").slice(0,300),p.failedAtMs=t(),{state:p.state})})},async complete({attemptKey:d,result:l,leaseId:m}){return Ct(l),a(f=>{let p=Oe(f,d);if(_t(p,m),p.state==="completed"){if(JSON.stringify(p.result)!==JSON.stringify(l))throw new Error("execution terminal result conflict");return p}if(p.state!=="receipts-confirmed")throw new Error("execution cannot complete before every canonical receipt is durable");return p.state="completed",p.result=he(l),p.completedAtMs=t(),p})},async reconcile({attemptKey:d,observeTransaction:l,commitLedger:m,settleFailedLedger:f}){if(typeof l!="function")throw new TypeError("execution reconciliation observer is required");let p=Un(32).toString("hex"),w=a(g=>{let h=Oe(g,d);if(["completed","failed","partial"].includes(h.state)&&h.result)return{terminal:!0,attempt:h};if(h.executorLeaseId){let y={pid:h.executorLeaseOwnerPid,startToken:h.executorLeaseOwnerStartToken};if(!y.pid||!y.startToken||n(y))throw new Error("execution reconciliation refused while live executor lease is active");delete h.executorLeaseId,delete h.executorLeaseAcquiredAtMs,delete h.executorLeaseOwnerPid,delete h.executorLeaseOwnerStartToken,h.executorLeaseRecoveredAtMs=t()}if(h.recoveryLeaseId)throw new Error("execution recovery is already active");return h.recoveryLeaseId=p,h.recoveryLeaseAcquiredAtMs=t(),{terminal:!1}});if(w.terminal)return w.attempt;try{let g=await c.inspect(d);if(g.state==="reserved"&&g.transactions.length===0)return c.failPreSubmission({attemptKey:d,leaseId:p,error:"recovered before signing"});for(let R of g.transactions){if(!R||R.state==="confirmed"||R.state==="failed")continue;let $=await l(he(R),he(g));$&&await c.recordCanonicalReceipt({attemptKey:d,leaseId:p,txIndex:R.txIndex,receipt:$})}let h=await c.inspect(d),y=h.transactions.filter(Boolean);if(y.some(R=>R.state!=="confirmed"&&R.state!=="failed"))return h;let b=Number(h.transactionCount||y.length),S=y.filter(R=>R.state==="confirmed").length,A=y.filter(R=>R.state==="failed").length,k=Math.max(0,b-y.length);if(y.length===0)return h;let v=y.map(R=>({...he(R.receipt),transactionHash:R.receipt?.transactionHash??R.receipt?.hash,balanceDeltaVerified:!1,delta:{},reconciled:!0})),_=A>0?S>0?"partial":"failed":k>0?"partial":"success",C={status:_,receipts:v,confirmedCount:S,failedCount:A,unattemptedCount:k};_==="success"&&v.length===1&&(C.receipt=v[0]),(h.surface==="evm-bridge"||h.action==="bridge")&&(C.originStatus=_==="success"?"success":_,C.destinationStatus="unknown",C.destinationSuccess=!1,C.warning="Origin-chain receipts do not prove destination-chain settlement.");let z={tradeId:h.tradeId};if(!z.tradeId)throw new Error("execution reconciliation is missing ledger tradeId");let U=S>0?"committed":"failed-fee-settled";if(!h.ledgerDisposition){let R=S>0?m:f;if(typeof R!="function")throw new TypeError("execution reconciliation ledger settlement callback is required");await R(z)}return a(R=>{let $=Oe(R,d);return _t($,p),["completed","failed","partial"].includes($.state)&&$.result||($.ledgerDisposition=$.ledgerDisposition||U,$.state=_==="success"?"completed":_,$.result=he(C),$.completedAtMs=t()),$})}finally{a(g=>{let h=Oe(g,d);return h.recoveryLeaseId===p&&(delete h.recoveryLeaseId,delete h.recoveryLeaseAcquiredAtMs),null})}},async inspect(d){ds(s);let l=fs(i).attempts[String(d||"")];return l?he(l):null}};return Object.freeze(c)}import{createHash as Fd}from"node:crypto";import{wordlists as jd}from"ethers";var Lt="oracle.control-plane/1",Fe="0.28.26+control-plane.1",Rt=64*1024,xs=32,Md=32*1024,qd=2e3,Hd=512,zd=/^(?:0|[1-9][0-9]*)$/,Ud=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/,Wd=/^[a-f0-9]{64}$/,Vd=/(?:amount|quantity|value|notional|balance|price|fee|gas|slippage|bps|basispoints|limit|maximum|minimum|cap|allowance|decimals|confirmations|executions|sequence|count)(?:$|[A-Z_])/i,Kd=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,Jd=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Gd=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),Yd=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,Xd=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]),Zd=new Set([12,15,18,21,24]),x=class extends TypeError{constructor(t,r="CONTROL_PLANE_INVALID"){super(`control-plane: ${t}`),this.name="ControlPlaneValidationError",this.code=r}};function xe(e,t="value",{positive:r=!1}={}){if(typeof e!="string"||!zd.test(e))throw new x(`${t} must be a canonical integer string`);if(r&&e==="0")throw new x(`${t} must be a positive integer string`);return e}function V(e,t="id"){if(typeof e!="string"||!Ud.test(e))throw new x(`${t} must be a bounded explicit id`);return e}function je(e,t="timestamp"){if(typeof e!="string"||e.length>64)throw new x(`${t} must be an explicit ISO timestamp`);let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new x(`${t} must be a canonical ISO timestamp`);return e}function Te(e,t="hash",{nullable:r=!1}={}){if(r&&e===null)return e;if(typeof e!="string"||!Wd.test(e))throw new x(`${t} must be a lowercase sha256 hash`);return e}function Se(e,t,r,n="record"){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new x(`${n} must be a plain object`);let o=new Set(t);for(let i of Object.keys(e))if(!o.has(i))throw new x(`${n} has unexpected field ${i}`);for(let i of r)if(!Object.hasOwn(e,i))throw new x(`${n}.${i} is required`)}function Ne(e,t){return`${V(e,"tenantId")}\0${V(t,"workflowId")}`}function Kn(e,t,r){return`${Ne(e,t)}\0${V(r,"idempotencyKey")}`}function Es(e,t){return e==="quantities"||Vd.test(t)}function Ss(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Qd(e){let t=Ss(e);return[...Gd].some(r=>t.includes(r))}function ef(e){let t=Ss(e);return Xd.has(t)||Yd.test(t)}function tf(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Zd.has(t.length)&&t.every(r=>jd.en.getWordIndex(r)>=0)}function rf(e,t,r){if(typeof t=="string"){if(Jd.some(n=>n.test(t))||tf(t))throw new x(`${r} contains secret or custody material`,"CONTROL_PLANE_SECRET");if(Kd.test(t)&&!ef(e))throw new x(`${r} contains secret or custody material`,"CONTROL_PLANE_SECRET")}}function nf(e){return[...new Set([...Object.getOwnPropertyNames(e),...Object.keys(e)])]}function Wn(e,t="record",r="",n=new WeakSet){if(!(e===null||typeof e=="boolean"||typeof e=="number")){if(typeof e=="string"){rf(r,e,t);return}if(!(typeof e=="bigint"||e===void 0)){if(typeof e=="function")throw new x(`${t} functions are not JSON-safe public data`,"CONTROL_PLANE_SECRET");if(typeof e!="object")throw new x(`${t} must contain JSON-safe plain objects only`,"CONTROL_PLANE_SECRET");if(n.has(e))throw new x(`${t} cyclic values are not JSON-safe`,"CONTROL_PLANE_SECRET");if(n.add(e),Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)throw new x(`${t} binary buffers and typed arrays are not JSON-safe public data`,"CONTROL_PLANE_SECRET");if(typeof e.toJSON=="function")throw new x(`${t} toJSON is not allowed on control-plane records`,"CONTROL_PLANE_SECRET");if(Array.isArray(e)){e.forEach((o,i)=>Wn(o,`${t}[${i}]`,r,n));return}if(Object.getPrototypeOf(e)!==Object.prototype)throw new x(`${t} must contain JSON-safe plain objects only`,"CONTROL_PLANE_SECRET");for(let o of nf(e)){let i=`${t}.${o}`;if(Qd(o))throw new x(`${i} contains secret or custody material`,"CONTROL_PLANE_SECRET");let s=Object.getOwnPropertyDescriptor(e,o);if(s&&(typeof s.get=="function"||typeof s.set=="function"))throw new x(`${i} getters are not JSON-safe public data`,"CONTROL_PLANE_SECRET");Wn(e[o],i,o,n)}}}}function Vn(e,t,r,n,o,i){if(o>xs)throw new x(`${t} exceeds depth limit`);if(e===null||typeof e=="boolean")return i.bytes+=e===null||e?4:5,e;if(typeof e=="string"){let a=Buffer.byteLength(e,"utf8");if(a>Md)throw new x(`${t} exceeds string size limit`);return Es(n,r)&&xe(e,t),i.bytes+=a+2,e}if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isSafeInteger(e))throw new x(`${t} must be a finite safe integer or an exact integer string`);if(Es(n,r))throw new x(`${t} financial quantity must be an exact integer string`);return i.bytes+=String(e).length,e}if(typeof e=="bigint")throw new x(`${t} bigint is not JSON-safe; use an exact integer string`);if(e===void 0)throw new x(`${t} undefined is not JSON-safe`);if(typeof e=="function")throw new x(`${t} functions are not JSON-safe public data`);if(Array.isArray(e)){if(e.length>qd)throw new x(`${t} exceeds array item limit`);i.bytes+=2;let a=e.map((c,d)=>Vn(c,`${t}[${d}]`,r,n,o+1,i));if(i.bytes>Rt)throw new x(`${t} exceeds size limit`);return a}if(Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)throw new x(`${t} binary buffers and typed arrays are not JSON-safe public data`);if(!e||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new x(`${t} must contain JSON-safe plain objects only`);if(typeof e.toJSON=="function")throw new x(`${t} toJSON is not allowed on control-plane records`);let s=Object.keys(e).sort();if(s.length>Hd)throw new x(`${t} exceeds object key limit`);let u={};i.bytes+=2;for(let a of s){let c=Object.getOwnPropertyDescriptor(e,a);if(c&&(typeof c.get=="function"||typeof c.set=="function"))throw new x(`${t}.${a} getters are not JSON-safe public data`);if(i.bytes+=Buffer.byteLength(a,"utf8")+3,u[a]=Vn(e[a],`${t}.${a}`,a,r,o+1,i),i.bytes>Rt)throw new x(`${t} exceeds size limit`)}return u}function Me(e,t="record"){try{Ct(e)}catch(i){throw new x(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}try{Wn(e,t)}catch(i){throw i instanceof x?i:new x(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}let n=Vn(e,t,"","",0,{bytes:0});if(Buffer.byteLength(_r(n),"utf8")>Rt)throw new x(`${t} exceeds size limit`);return n}function _r(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(_r).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${_r(e[t])}`).join(",")}}`}function it(e){return _r(Me(e))}function Rr(e){return Fd("sha256").update(it(e),"utf8").digest("hex")}function se(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))se(t);Object.freeze(e)}return e}function rr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new x("record object required");let{recordHash:t,eventHash:r,...n}=e;return Rr(n)}function Jn(e,t){return Me({schemaVersion:Lt,buildVersion:Fe,recordType:e,execution:"prepare-only",custody:"none",...t})}function Gn(e,t){if(e.schemaVersion!==Lt)throw new x("schemaVersion mismatch");if(e.buildVersion!==Fe)throw new x("buildVersion mismatch");if(e.recordType!==t)throw new x(`recordType must be ${t}`);if(e.execution!=="prepare-only")throw new x("execution must be prepare-only");if(e.custody!=="none")throw new x("custody must be none")}var of=["schemaVersion","buildVersion","recordType","execution","custody"],eb=[...of,"recordHash"];var tb=Object.freeze({signed:new Set(["workflow.signed","legacy.signed"]),submitted:new Set(["workflow.submitted","legacy.broadcast"]),finalized:new Set(["workflow.finalized"]),reorged:new Set(["workflow.reorged"]),orphaned:new Set(["workflow.orphaned"]),compensating:new Set(["workflow.compensating"]),compensated:new Set(["workflow.compensated"])}),sf=new Set(["block","blockNumber","blockHash","inclusionBlock","inclusionBlockNumber","inclusionBlockHash","receipt","receiptHash","transactionIndex","logIndex","confirmations"]),af=/^(?:0x)?[a-f0-9]{64}$/,cf=/^(?:0x)[a-f0-9]{64}$/;function Lr(e,t=new WeakSet){if(!e||typeof e!="object"||t.has(e))return!1;if(t.add(e),Array.isArray(e))return e.some(r=>Lr(r,t));for(let[r,n]of Object.entries(e))if(sf.has(r)||Lr(n,t))return!0;return!1}function or(e,t,{min:r=1,max:n=4096}={}){if(typeof e!="string"||e.length<r||e.length>n)throw new x(`${t} must be an explicit bounded string`);return e}function vs(e,t){if(or(e,t,{min:66,max:66}),!cf.test(e))throw new x(`${t} must be a 0x-prefixed 32-byte hash`);return e}function nr(e,t){if(or(e,t,{min:64,max:66}),!af.test(e))throw new x(`${t} must be a 32-byte digest`);return e}function Is(e,t,{positive:r=!1}={}){return xe(e,t,{positive:r})}function uf(e,t){if(Lr(e))throw new x(`${t} signed proof must not require or carry inclusion block fields`);let r=e.artifactHash??e.signedArtifactHash??e.digest,n=e.signer??e.expectedSigner??e.from;nr(r,`${t}.artifactHash`),or(n,`${t}.signer`,{min:1,max:256})}function lf(e,t){if(Lr(e))throw new x(`${t} submitted proof must not require or carry inclusion block fields`);let r=e.transactionHash??e.txHash,n=e.endpoint??e.submissionEndpoint??e.provider;vs(r,`${t}.transactionHash`),or(n,`${t}.endpoint`,{min:1,max:4096})}function As(e,t,{requireReceiptStatus:r=!1}={}){let n=e.transactionHash??e.txHash,o=e.blockNumber,i=e.blockHash;vs(n,`${t}.transactionHash`),Is(o,`${t}.blockNumber`,{positive:!0}),nr(i,`${t}.blockHash`),e.receiptHash!=null&&nr(e.receiptHash,`${t}.receiptHash`),(r||e.receiptStatus!=null)&&or(e.receiptStatus,`${t}.receiptStatus`,{min:1,max:32})}function Yn(e,t,r){switch(e){case"workflow.signed":case"legacy.signed":uf(t,r);break;case"workflow.submitted":case"legacy.broadcast":lf(t,r);break;case"workflow.finalized":As(t,r,{requireReceiptStatus:!0}),t.confirmations!=null&&Is(t.confirmations,`${r}.confirmations`);break;case"workflow.reorged":case"workflow.orphaned":As(t,r),t.observedBlockHash!=null&&nr(t.observedBlockHash,`${r}.observedBlockHash`),t.replacementBlockHash!=null&&nr(t.replacementBlockHash,`${r}.replacementBlockHash`);break;default:break}}var df=Object.freeze(["draft","checked","approval","signed","submitted","finalized","reorged","orphaned","compensating","compensated","failed","cancelled"]),Ts=Object.freeze(["workflow.drafted","workflow.checked","workflow.approval_requested","workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated","workflow.failed","workflow.cancelled","workflow.annotated"]),Ns=new Set(Ts),ff=new Set(["workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated"]),Cs=new Set(["workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned"]),pf=new Set(["failed","cancelled","compensated"]),ks=["schemaVersion","buildVersion","recordType","execution","custody","tenantId","id","workflowId","sequence","previousEventHash","idempotencyKey","occurredAt","recordedAt","type","external","evidence","data","eventHash"],$r=["tenantId","id","workflowId","idempotencyKey","occurredAt","recordedAt","type","external","evidence","data"];function mf(e,t){return{status:e?.status,source:e?.source,reference:e?.reference,observedAt:e?.observedAt??t}}function _s(e,t="WorkflowEvent.evidence"){if(Se(e,["status","source","reference","observedAt"],["status","source","reference","observedAt"],t),!new Set(["known","verified","unknown"]).has(e.status))throw new x(`${t}.status is invalid`);if(e.status==="unknown")throw new x("UNKNOWN evidence fails closed");if(V(e.source,`${t}.source`),typeof e.reference!="string"||e.reference.length<1||e.reference.length>4096)throw new x(`${t}.reference must be an explicit bounded reference`);je(e.observedAt,`${t}.observedAt`)}function Rs(e){return ff.has(e)}function Xn(e={}){Se(e,$r,$r,"WorkflowEvent input");let t=Me({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:mf(e.evidence,e.recordedAt),data:e.data},"WorkflowEvent input");if(V(t.tenantId,"WorkflowEvent.tenantId"),V(t.id,"WorkflowEvent.id"),V(t.workflowId,"WorkflowEvent.workflowId"),V(t.idempotencyKey,"WorkflowEvent.idempotencyKey"),je(t.occurredAt,"WorkflowEvent.occurredAt"),je(t.recordedAt,"WorkflowEvent.recordedAt"),!Ns.has(t.type))throw new x(`unknown workflow event type ${String(t.type)}`);if(typeof t.external!="boolean")throw new x("WorkflowEvent.external must be boolean");if(_s(t.evidence),Rs(t.type)){if(t.external!==!0)throw new x(`${t.type} must be an explicitly external fact`);if(t.evidence.status!=="verified"||t.evidence.source!=="external")throw new x(`${t.type} requires verified external evidence; caller external:true is not proof`)}else if(t.external===!0)throw new x(`${t.type} is not an external fact; caller external:true is not proof`);return Me(t.data,"WorkflowEvent.data"),Cs.has(t.type)&&Yn(t.type,t.data,"WorkflowEvent.data"),se(t)}function Pr(e={}){let t=e.sequence,r=e.previousEventHash,n=Object.fromEntries($r.map(a=>[a,e[a]])),o=Object.keys(e).filter(a=>!$r.includes(a)&&a!=="sequence"&&a!=="previousEventHash");if(o.length)throw new x(`WorkflowEvent input has unexpected field ${o[0]}`);let i=Xn(n);if(xe(t,"WorkflowEvent.sequence",{positive:!0}),t==="1"){if(r!==null)throw new x("first WorkflowEvent previousEventHash must be null")}else Te(r,"WorkflowEvent.previousEventHash");let s=Jn("WorkflowEvent",{...i,sequence:t,previousEventHash:r}),u=se({...s,eventHash:rr(s)});return ir(u),u}function ir(e){if(Se(e,ks,ks,"WorkflowEvent"),Gn(e,"WorkflowEvent"),V(e.tenantId,"WorkflowEvent.tenantId"),V(e.id,"WorkflowEvent.id"),V(e.workflowId,"WorkflowEvent.workflowId"),V(e.idempotencyKey,"WorkflowEvent.idempotencyKey"),xe(e.sequence,"WorkflowEvent.sequence",{positive:!0}),e.sequence==="1"){if(e.previousEventHash!==null)throw new x("first WorkflowEvent previousEventHash must be null")}else Te(e.previousEventHash,"WorkflowEvent.previousEventHash");if(je(e.occurredAt,"WorkflowEvent.occurredAt"),je(e.recordedAt,"WorkflowEvent.recordedAt"),!Ns.has(e.type))throw new x(`unknown workflow event type ${String(e.type)}`);if(typeof e.external!="boolean")throw new x("WorkflowEvent.external must be boolean");if(_s(e.evidence),Rs(e.type)){if(e.external!==!0)throw new x(`${e.type} must be an explicitly external fact`);if(e.evidence.status!=="verified"||e.evidence.source!=="external")throw new x(`${e.type} requires verified external evidence; caller external:true is not proof`)}else if(e.external===!0)throw new x(`${e.type} is not an external fact; caller external:true is not proof`);if(Me(e.data,"WorkflowEvent.data"),Cs.has(e.type)&&Yn(e.type,e.data,"WorkflowEvent.data"),Te(e.eventHash,"WorkflowEvent.eventHash"),rr(e)!==e.eventHash)throw new x("WorkflowEvent hash mismatch");return!0}function ee(e,t){throw new x(`invalid workflow transition ${e??"NONE"} -> ${t.type}`)}function Br(e=[]){if(!Array.isArray(e)||e.length<1)throw new x("workflow replay requires at least one event");let t=null,r=null,n=null,o=null,i=!1,s=null,u=[];for(let a of e){if(ir(a),t===null&&(t=a.tenantId),r===null&&(r=a.workflowId),n===null&&(n=Ne(a.tenantId,a.workflowId)),a.tenantId!==t)throw new x("workflow replay cannot mix tenant ids");if(a.workflowId!==r)throw new x("workflow replay cannot mix workflow ids");if(Ne(a.tenantId,a.workflowId)!==n)throw new x("workflow replay cannot mix tenant-scoped streams");let c=String(BigInt(s?.sequence??"0")+1n);if(a.sequence!==c)throw new x(`workflow sequence gap at ${a.sequence}`);if(a.previousEventHash!==(s?.eventHash??null))throw new x(`workflow previous-event hash mismatch at ${a.sequence}`);if(s&&Date.parse(a.recordedAt)<Date.parse(s.recordedAt))throw new x(`workflow recordedAt is not monotonic at ${a.sequence}`);if(pf.has(o))throw new x(`workflow state ${o} is terminal`);switch(a.type){case"workflow.drafted":o!==null&&ee(o,a),o="draft";break;case"workflow.checked":if(o!=="draft"&&ee(o,a),a.evidence.status!=="verified"||a.data?.checksPassed!==!0)throw new x("workflow.checked requires verified evidence and checksPassed=true");o="checked";break;case"workflow.approval_requested":o!=="checked"&&ee(o,a),o="approval",i=!1;break;case"workflow.approval_granted":o!=="approval"&&ee(o,a),i=!0;break;case"workflow.signed":if(o!=="approval"&&ee(o,a),!i)throw new x("external approval must be granted before signed state");o="signed";break;case"workflow.submitted":o!=="signed"&&ee(o,a),o="submitted";break;case"workflow.finalized":o!=="submitted"&&ee(o,a),o="finalized";break;case"workflow.reorged":o!=="submitted"&&o!=="finalized"&&ee(o,a),o="reorged";break;case"workflow.orphaned":o!=="submitted"&&o!=="finalized"&&o!=="reorged"&&ee(o,a),o="orphaned";break;case"workflow.compensating":o!=="reorged"&&o!=="orphaned"&&ee(o,a),o="compensating";break;case"workflow.compensated":o!=="compensating"&&ee(o,a),o="compensated";break;case"workflow.failed":if(o==="finalized"||o==="compensated")throw new x("failed must not follow finalized");new Set(["draft","checked","approval","signed","submitted","reorged","orphaned","compensating"]).has(o)||ee(o,a),o="failed";break;case"workflow.cancelled":new Set(["draft","checked","approval","signed"]).has(o)||ee(o,a),o="cancelled";break;case"workflow.annotated":o===null&&ee(o,a);break;default:ee(o,a)}a.external&&u.push({id:a.id,type:a.type,eventHash:a.eventHash,occurredAt:a.occurredAt,evidence:a.evidence,data:a.data}),s=a}return se({schemaVersion:Lt,buildVersion:Fe,tenantId:t,workflowId:r,streamKey:n,state:o,approvalGranted:i,eventCount:String(e.length),headEventHash:s.eventHash,externalFacts:u,authority:"event-ledger",execution:"prepare-only",custody:"none"})}import{createHash as wf,randomUUID as Ps}from"node:crypto";import{chmodSync as Qn,closeSync as at,constants as ce,existsSync as st,fstatSync as hf,fsyncSync as Mr,lstatSync as gf,mkdirSync as yf,openSync as qr,readFileSync as Fr,renameSync as bf,unlinkSync as Bs,writeSync as Ef}from"node:fs";import{dirname as Ds,resolve as xf}from"node:path";import{setTimeout as Sf}from"node:timers/promises";var eo="oracle.control-plane-ledger-checkpoint/1",to="oracle.control-plane-ledger-lock/1",ro=64*1024*1024,Fs=1e4,js=Rt,Ls=["schemaVersion","buildVersion","totalEvents","fileSize","ledgerHash","lastEventHash","workflowHeads","checkpointHash"],$s=["schemaVersion","token","pid","createdAt"],B=class extends Error{constructor(t,r="WORKFLOW_LEDGER_ERROR",n=null){super(`workflow-ledger: ${t}`),this.name="WorkflowLedgerError",this.code=r,this.detail=n}};function ct(e){if(typeof e!="string"||e.length<1||e.length>4096)throw new B("bounded path required","PATH_INVALID");let t=xf(e);return{ledger:t,checkpoint:`${t}.checkpoint`,lock:`${t}.lock`,directory:Ds(t)}}function Af(e){yf(e,{recursive:!0,mode:448})}function jr(e,t){let r=gf(e);if(!r.isFile()||r.isSymbolicLink())throw new B(`${t} must be a regular non-symlink file`,"UNSAFE_FILE");if((r.mode&511)!==384)throw new B(`${t} permissions must be 0600`,"UNSAFE_PERMISSIONS");return r}function Hr(e){let t;try{t=qr(e,ce.O_RDONLY),Mr(t)}finally{t!==void 0&&at(t)}}function no(e,t){let r=0;for(;r<t.length;)r+=Ef(e,t,r,t.length-r)}function vf(e){let t=ce.O_WRONLY|ce.O_CREAT|ce.O_APPEND|(ce.O_NOFOLLOW||0),r=qr(e,t,384);if(!hf(r).isFile())throw at(r),new B("ledger target is not a regular file","UNSAFE_FILE");return r}function If(e){ir(e);let t=Pr({tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,sequence:e.sequence,previousEventHash:e.previousEventHash,idempotencyKey:e.idempotencyKey,occurredAt:e.occurredAt,recordedAt:e.recordedAt,type:e.type,external:e.external,evidence:e.evidence,data:e.data});if(t.eventHash!==e.eventHash)throw new x("WorkflowEvent hash mismatch");return t}function Zn(e){return Ne(e.tenantId,e.workflowId)}function kf(e){let t={};for(let r of e)t[Zn(r)]={tenantId:r.tenantId,workflowId:r.workflowId,sequence:r.sequence,eventHash:r.eventHash};return Object.fromEntries(Object.entries(t).sort(([r],[n])=>r.localeCompare(n)))}function Ms(e,t,r=null){let n=r??(st(e)?Fr(e):Buffer.alloc(0));return Me({schemaVersion:eo,buildVersion:Fe,totalEvents:String(t.length),fileSize:String(n.length),ledgerHash:wf("sha256").update(n).digest("hex"),lastEventHash:t.at(-1)?.eventHash??null,workflowHeads:kf(t)},"workflow checkpoint")}function qs(e,t,r=null){let n=Ms(e,t,r);return se({...n,checkpointHash:Rr(n)})}function Of(e){if(Se(e,Ls,Ls,"workflow checkpoint"),e.schemaVersion!==eo)throw new B("checkpoint schema mismatch","CHECKPOINT_INVALID");if(e.buildVersion!==Fe)throw new B("checkpoint build mismatch","CHECKPOINT_INVALID");if(xe(e.totalEvents,"workflow checkpoint.totalEvents"),xe(e.fileSize,"workflow checkpoint.fileSize"),Te(e.ledgerHash,"workflow checkpoint.ledgerHash"),Te(e.lastEventHash,"workflow checkpoint.lastEventHash",{nullable:!0}),!e.workflowHeads||typeof e.workflowHeads!="object"||Array.isArray(e.workflowHeads))throw new B("checkpoint workflowHeads invalid","CHECKPOINT_INVALID");for(let[n,o]of Object.entries(e.workflowHeads)){if(Se(o,["tenantId","workflowId","sequence","eventHash"],["tenantId","workflowId","sequence","eventHash"],`workflow checkpoint.${n}`),V(o.tenantId,`workflow checkpoint.${n}.tenantId`),V(o.workflowId,`workflow checkpoint.${n}.workflowId`),Ne(o.tenantId,o.workflowId)!==n)throw new B("checkpoint workflowHeads stream key mismatch","CHECKPOINT_INVALID");xe(o.sequence,`workflow checkpoint.${n}.sequence`,{positive:!0}),Te(o.eventHash,`workflow checkpoint.${n}.eventHash`)}Te(e.checkpointHash,"workflow checkpoint.checkpointHash");let{checkpointHash:t,...r}=e;if(Rr(r)!==t)throw new B("checkpoint hash mismatch","CHECKPOINT_INVALID");if(e.totalEvents==="0"!=(e.lastEventHash===null))throw new B("checkpoint event count/head mismatch","CHECKPOINT_INVALID");return!0}function Tf(e,t,r=null,n=null){let{checkpoint:o,directory:i}=ct(e),s=n??qs(e,t,r),u=`${o}.${Ps()}.tmp`,a;try{a=qr(u,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),no(a,Buffer.from(`${JSON.stringify(s)}
10
- `,"utf8")),Mr(a),at(a),a=void 0,bf(u,o),Qn(o,384),Hr(i)}catch(c){a!==void 0&&at(a);try{st(u)&&Bs(u)}catch{}throw c}return s}function Nf(e,t){let r=BigInt(e.totalEvents),n=BigInt(t.totalEvents);if(r>n)return{ok:!1,reason:"checkpoint-ahead",recoverable:!1};if(r<n)return{ok:!1,reason:"checkpoint-behind",recoverable:!0};let o=BigInt(e.fileSize),i=BigInt(t.fileSize);return o>i?{ok:!1,reason:"checkpoint-ahead",recoverable:!1}:o<i?{ok:!1,reason:"checkpoint-behind",recoverable:!0}:e.ledgerHash!==t.ledgerHash?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:e.lastEventHash!==t.lastEventHash?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:it(e.workflowHeads)!==it(t.workflowHeads)?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:{ok:!0}}function Cf({path:e,maxBytes:t=ro,checkCheckpoint:r=!0}={}){let n=ct(e);if(!Number.isSafeInteger(t)||t<1||t>1024*1024*1024)return{ok:!1,reason:"size-limit",count:0,workflows:0,events:[],paths:n};try{if(!st(n.ledger))return r&&st(n.checkpoint)?{ok:!1,reason:"checkpoint-ahead",recoverable:!1,count:0,workflows:0,events:[],paths:n}:{ok:!0,count:0,workflows:0,events:[],heads:new Map,paths:n,empty:!0};if(jr(n.ledger,"ledger").size>t)return{ok:!1,reason:"size-limit",count:0,workflows:0,events:[],paths:n};let i=Fr(n.ledger);if(i.length>0&&i.at(-1)!==10)return{ok:!1,reason:"truncated-line",count:0,workflows:0,events:[],paths:n};let s=i.toString("utf8"),u=i.length===0?[]:s.slice(0,-1).split(`
11
- `),a=[],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")>js)return{ok:!1,reason:"event-size-limit",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};let w;try{w=JSON.parse(p)}catch{return{ok:!1,reason:"malformed-json",line:f+1,count:a.length,workflows:c.size,events:a,paths:n}}let g;try{g=If(w)}catch(A){return{ok:!1,reason:"event-invalid",line:f+1,detail:String(A?.message||A),count:a.length,workflows:c.size,events:a,paths:n}}if(d.has(g.id))return{ok:!1,reason:"duplicate-event-id",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};let h=Zn(g),y=Kn(g.tenantId,g.workflowId,g.idempotencyKey);if(l.has(y))return{ok:!1,reason:"duplicate-idempotency-key",line:f+1,count:a.length,workflows:c.size,events:a,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:a.length,workflows:c.size,events:a,paths:n};if(g.previousEventHash!==(b?.eventHash??null))return{ok:!1,reason:"previous-event-hash-mismatch",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};if(b&&Date.parse(g.recordedAt)<Date.parse(b.recordedAt))return{ok:!1,reason:"recorded-at-regression",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};d.add(g.id),l.add(y),c.set(h,g),a.push(g)}let m=new Map;for(let f of a){let p=Zn(f);m.has(p)||m.set(p,[]),m.get(p).push(f)}for(let[f,p]of m)try{Br(p)}catch(w){return{ok:!1,reason:"workflow-invalid",streamKey:f,detail:String(w?.message||w),count:a.length,workflows:c.size,events:a,heads:c,paths:n}}if(r){if(!st(n.checkpoint))return a.length===0?{ok:!0,count:0,workflows:0,events:a,heads:c,paths:n,empty:!0}:{ok:!1,reason:"checkpoint-missing",recoverable:!0,count:a.length,workflows:c.size,events:a,heads:c,paths:n};let f;try{jr(n.checkpoint,"checkpoint");let g=Fr(n.checkpoint,"utf8");if(!g.endsWith(`
12
- `))throw new B("checkpoint truncated","CHECKPOINT_INVALID");f=JSON.parse(g),Of(f)}catch(g){return{ok:!1,reason:"checkpoint-invalid",recoverable:!1,detail:String(g?.message||g),count:a.length,workflows:c.size,events:a,heads:c,paths:n}}let p=Ms(n.ledger,a,i),w=Nf(f,p);if(!w.ok)return{...w,count:a.length,workflows:c.size,events:a,heads:c,paths:n}}return{ok:!0,count:a.length,workflows:c.size,events:a,heads:c,paths:n,raw:i,lastEventHash:a.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 _f(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 se(t)}function Rf(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 Hs(e){let{lock:t}=ct(e);jr(t,"lock");let r=JSON.parse(Fr(t,"utf8"));if(Se(r,$s,$s,"workflow ledger lock"),r.schemaVersion!==to)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 je(r.createdAt,"workflow ledger lock.createdAt"),r}function zs({path:e}={}){let{lock:t}=ct(e);if(!st(t))return se({state:"unlocked",lock:null});try{let r=Hs(e);return se({state:Rf(r.pid),lock:r})}catch(r){return se({state:"invalid",lock:null,error:String(r?.message||r)})}}function Lf(e){let t=ct(e);Af(t.directory);let r={schemaVersion:to,token:Ps(),pid:process.pid,createdAt:new Date().toISOString()},n;try{return n=qr(t.lock,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),no(n,Buffer.from(`${JSON.stringify(r)}
13
- `,"utf8")),Mr(n),at(n),n=void 0,Qn(t.lock,384),Hr(t.directory),r}catch(o){throw n!==void 0&&at(n),o}}async function $f(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 Lf(e)}catch(n){if(n?.code!=="EEXIST")throw n;if(Date.now()-r>=t){let o=zs({path:e});throw new B(`ledger busy (${o.state} lock); explicit token-bound recovery is required for stale locks`,"LEDGER_BUSY",o)}await Sf(10)}}function Dr(e,t){let r=Hs(e);if(r.token!==t||r.pid!==process.pid)throw new B("lock fencing token no longer owned","LOCK_FENCED");return!0}function Pf(e,t){let r=ct(e);Dr(e,t),Bs(r.lock),Hr(r.directory)}function Bf(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 oo(e={}){Se(e,["path","event","lockTimeoutMs","maxBytes"],["path","event"],"appendWorkflowEvent options");let t=ct(e.path).ledger,r=Xn(e.event),n=e.lockTimeoutMs??Fs,o=e.maxBytes??ro,i=await $f(t,n),s=null;try{Dr(t,i.token);let u=Cf({path:t,maxBytes:o});if(!u.ok)throw new B(`append refused until ledger recovery: ${u.reason}`,"LEDGER_CORRUPT",_f(u));let a=u.events.find(b=>b.tenantId===r.tenantId&&b.workflowId===r.workflowId&&b.idempotencyKey===r.idempotencyKey);if(a){if(it(Bf(a))!==it(r))throw new B("idempotency key reused with different payload","IDEMPOTENCY_CONFLICT");return se({event:a,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=Pr({...r,sequence:String(BigInt(d?.sequence??"0")+1n),previousEventHash:d?.eventHash??null}),m=u.events.filter(b=>Ne(b.tenantId,b.workflowId)===c);Br([...m,l]);let f=Buffer.from(`${JSON.stringify(l)}
14
- `,"utf8");if(f.length>js)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=qs(t,w,p),h=st(t);h&&jr(t,"ledger"),Dr(t,i.token);let y;try{y=vf(t),no(y,f),Mr(y)}finally{y!==void 0&&at(y)}return Qn(t,384),h||Hr(Ds(t)),Dr(t,i.token),Tf(t,w,p,g),se({event:l,duplicate:!1})}catch(u){throw s=u,u}finally{try{Pf(t,i.token)}catch(u){if(s===null)throw u}}}var pb=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),mb=Object.freeze(["read","simulate"]);var wb=1440*60;var vb=Object.freeze(["privkey","wif","xprv","seed"]);var Ib=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}]),kb=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);var io=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),Cb=Object.freeze(Object.fromEntries(io.map((e,t)=>[e,Object.freeze(t+1<io.length?[io[t+1]]:[])])));var Df=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 zf,randomBytes as Uf}from"node:crypto";var Ff=Object.freeze(["owner","operator","agent","viewer"]),jf=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),Mf=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),c0=Object.freeze(["owner"]),u0=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"}),l0=new Set(Ff),d0=new Set(jf),f0=new Set(Object.values(Mf));var qf=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;var Hf=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"])}),p0=Object.freeze(Object.fromEntries(Object.entries(Hf).map(([e,t])=>[e,Object.freeze([...t])]))),zr=class extends Error{constructor(t,r="invalid-context"){super(t),this.name="TenantContextError",this.code=r}};function Us(e,t){let r=String(e??"").trim();if(!qf.test(r))throw new zr(`${t} is invalid`);return r}function Ws(e,t){let r=Us(e,"tenantId"),n=Us(t,"workflowId");if(r.includes(":")||n.includes(":"))throw new zr("stream key parts must not contain ':'","invalid-stream-key");return`${r}:${n}`}var Xs=1,Zs=1,Wf=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),Vf=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),Qs=Object.freeze(["taskId","intentId","planId","runId","eventId"]);function Vs(e,t){return Ws(e,t)}var sr=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),Kf=new Set(Wf),Jf=new Set(Vf),Gf=new Set(Qs),Yf=/^[0-9a-f]{32}$/,Ks=/^[0-9a-f]{16}$/;var Xf=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,95}$/,Zf=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Qf=/^[A-Za-z][A-Za-z0-9_.-]*$/,ep=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"]),tp=/(?:^|\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,rp=/(?:0x)?[0-9a-fA-F]{66,}/,np=/[A-Za-z0-9+/=_-]{96,}/,F=class extends Error{constructor(t,r="invalid-telemetry"){super(t),this.name="WorkflowTelemetryError",this.code=r}};function Ur(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Wr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Wr(t)}return e}function so(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(so).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${so(e[t])}`).join(",")}}`}function ea(e){return zf("sha256").update(so(e)).digest("hex")}function Js(e,t,r){let n=r?r(e,t):Uf(e).toString("hex");return String(n??"").trim().toLowerCase()}function ta(e={}){if(e==null)return{};if(!Ur(e))throw new F("correlation must be a plain object");let t=Object.keys(e).filter(n=>!Gf.has(n));if(t.length)throw new F(`unknown correlation fields: ${t.sort().join(", ")}`);let r={};for(let n of Qs){if(e[n]==null)continue;let o=String(e[n]).trim();if(!Zf.test(o))throw new F(`${n} is invalid`);r[n]=o}return r}function ra(e){if(!Ur(e)||e.schemaVersion!==Xs)throw new F("trace context version is invalid","invalid-trace");if(!Yf.test(e.traceId||"")||!Ks.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&&!Ks.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 ta(e.correlation),e}function op({traceId:e,spanId:t,parentSpanId:r=null,sampled:n=!1,correlation:o={}}={},{idFactory:i}={}){let s=e==null?Js(16,"trace",i):String(e).trim().toLowerCase(),u=t==null?Js(8,"span",i):String(t).trim().toLowerCase(),a=r==null?null:String(r).trim().toLowerCase(),c=Wr({schemaVersion:Xs,traceId:s,spanId:u,parentSpanId:a,sampled:n===!0,correlation:ta(o)});return ra(c)}var na=op;var g0=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 Gs(e){let t=String(e).replace(/[^a-z0-9]/gi,"").toLowerCase();return ep.some(r=>t.includes(r))}function ip(e){return tp.test(e)||rp.test(e)||np.test(e)?{value:"[REDACTED]",redacted:!0,truncated:!1}:e.length>sr.maxStringLength?{value:`${e.slice(0,sr.maxStringLength-1)}\u2026`,redacted:!1,truncated:!0}:{value:e,redacted:!1,truncated:!1}}function oa(e){if(typeof e=="string")return ip(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,sr.maxArrayLength),r=[],n=!1,o=e.length>t.length;for(let i of t){if(!["string","boolean","number"].includes(typeof i))return null;let s=oa(i);if(!s)return null;r.push(s.value),n||=s.redacted,o||=s.truncated}return{value:r,redacted:n,truncated:o}}return null}function sp(e={}){if(!Ur(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 s of i){if(Object.keys(t).length>=sr.maxAttributes){n+=1;continue}if(s.length>sr.maxKeyLength||!Qf.test(s)||Gs(s)){n+=1,Gs(s)&&(r+=1);continue}let u=oa(e[s]);if(!u){n+=1;continue}t[s]=u.value,u.redacted&&(r+=1),u.truncated&&(o+=1)}return Wr({attributes:t,redactedCount:r,droppedCount:n,truncatedCount:o})}function Ys(e,t){if(!Number.isSafeInteger(e)||e<0)throw new F(`${t} must be a non-negative integer milliseconds value`);return e}function ap(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 cp({streamKey:e,tenantId:t,workflowId:r,sourceEvent:n}){let o=e??n?.streamKey??null,i=t??n?.tenantId??null,s=r??n?.workflowId??null;if(o!=null){let u=String(o).trim();if(i!=null&&s!=null){let a=Vs(i,s);if(u!==a)throw new F("streamKey must equal tenantId:workflowId","invalid-stream-key");return a}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&&s!=null?Vs(i,s):null}function up({trace:e,name:t,kind:r,diagnosticOutcome:n=null,outcome:o=null,outcomeCode:i=null,startedAt:s,endedAt:u,attributes:a,authority:c,sourceEvent:d=null,streamKey:l=null,tenantId:m=null,workflowId:f=null}){ra(e);let p=String(t??"").trim();if(!Xf.test(p))throw new F("workflow telemetry name is invalid");if(!Jf.has(r))throw new F("workflow telemetry kind is invalid");let w=c==="ledger_projection"?o:n;if(!Kf.has(w))throw new F("workflow telemetry outcome is invalid");let g=Ys(s,"startedAt"),h=Ys(u,"endedAt");if(h<g)throw new F("endedAt must not be before startedAt");let y=sp(a),b=cp({streamKey:l,tenantId:m,workflowId:f,sourceEvent:d}),S={schemaVersion:Zs,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:ap(i),startedAt:g,endedAt:h,durationMs:h-g,attributes:{...y.attributes},attributePolicy:{redactedCount:y.redactedCount,droppedCount:y.droppedCount,truncatedCount:y.truncatedCount}};return Wr({...S,recordId:ea(S)})}function ao({trace:e,name:t,kind:r="workflow",outcome:n,outcomeCode:o=null,startedAt:i,endedAt:s,attributes:u={},tenantId:a=null,workflowId:c=null,streamKey:d=null}={}){return up({trace:e,name:t,kind:r,diagnosticOutcome:n,outcomeCode:o,startedAt:i,endedAt:s,attributes:u,authority:"diagnostic",tenantId:a,workflowId:c,streamKey:d})}function co(e){if(!Ur(e)||!Object.isFrozen(e)||e.schemaVersion!==Zs||e.recordType!=="oracle.workflow.telemetry")return!1;let{recordId:t,...r}=e;return typeof t=="string"&&t===ea(r)}function uo({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=co(r)?r:ao(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 lp="ORACLE_LEDGER_DUAL_WRITE",ia=/^[a-f0-9]{64}$/,dp=/^0x[a-f0-9]{64}$/,fp=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"});function $t(e,t){return String(e??"").slice(0,t)}function sa(e=process.env){return String(e?.[lp]??"")==="1"}function aa({path:e,tenantId:t="local-signer",nowMs:r=Date.now,onError:n=null,telemetry:o=null,append:i=oo}={}){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 s=typeof n=="function"?n:()=>{},u=new Map,a=Promise.resolve(),c=()=>new Date(r()).toISOString();function d(f,p,w){if(!(!o||typeof o.emit!="function"))try{let g=r(),h=ao({trace:f.trace,name:p,kind:"workflow",outcome:fp[p]??"succeeded",startedAt:g,endedAt:g,attributes:w,tenantId:t,workflowId:f.workflowId});a=a.then(()=>o.emit(h)).catch(y=>{s(`signer telemetry emit failed: ${$t(y?.message||y,200)}`)})}catch(g){s(`signer telemetry record failed: ${$t(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 a=a.then(()=>i({path:e,event:S})).catch(A=>{s(`workflow ledger dual-write failed for ${p}: ${$t(A?.message||A,200)}`)}),d(f,p,{digest:f.digest}),a}function m(f){let p=String(f??"").toLowerCase();return ia.test(p)?u.get(p)??null:null}return Object.freeze({queued({digest:f,createdAtMs:p}={}){let w=String(f??"").toLowerCase();if(!ia.test(w))return s("ledger observer: queued without a valid artifact digest"),a;let g=Number.isFinite(Number(p))?Number(p):r(),h={workflowId:`signer-${w}-${g}`,digest:w,trace:na()};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}`}),a},denied({digest:f}={}){let p=m(f);return p&&(u.delete(p.digest),l(p,"workflow.cancelled",{source:"owner-ack",reference:`deny:${p.digest}`})),a},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}`}),a},executed({digest:f,owner:p=null,result:w=null}={}){let g=m(f);if(!g)return a;u.delete(g.digest),l(g,"workflow.signed",{external:!0,reference:`signed:${g.digest}`,data:{artifactHash:g.digest,signer:$t(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&&dp.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:$t(h,512)}}),a},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:$t(p,300)}})),a},flush(){return a}})}import{appendFileSync as pp,existsSync as mp,mkdirSync as wp,renameSync as hp,statSync as gp}from"node:fs";import{dirname as yp}from"node:path";var bp="ORACLE_TELEMETRY_JSONL",Ep=32*1024*1024,ca=4096;function xp({path:e,maxBytes:t=Ep}={}){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<ca)throw new F(`jsonl exporter maxBytes must be >= ${ca}`,"invalid-exporter-cap");let n=e;return Object.freeze({path:n,maxBytes:r,export(o){if(!co(o))throw new F("jsonl exporter accepts only sealed workflow telemetry records","invalid-record");let i=`${JSON.stringify(o)}
15
- `;wp(yp(n),{recursive:!0,mode:448}),mp(n)&&gp(n).size+Buffer.byteLength(i)>r&&hp(n,`${n}.1`),pp(n,i,{mode:384})}})}function ua(e=process.env,{maxBytes:t}={}){let r=String(e?.[bp]??"").trim();return r?uo({exporter:xp({path:r,...t===void 0?{}:{maxBytes:t}})}):uo({})}import{createCipheriv as O0,createDecipheriv as Sp,randomBytes as Ap,scryptSync as vp}from"node:crypto";import D from"node:fs";import Pt from"node:path";var Ip="ORACLE-LOCAL-VAULT",kp=1,Kr=Object.freeze({N:1<<17,r:8,p:1}),Op=256*1024*1024,Tp=16*1024;function Vr(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 Np(e,t,r=Kr){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 vp(n,t,32,{...r,maxmem:Op})}function la(e,t){if(e?.magic!==Ip||e?.version!==kp)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!==Kr.N||e.kdf.r!==Kr.r||e.kdf.p!==Kr.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=Vr(e.kdf.salt,32,"salt"),o=Vr(e.cipher.iv,12,"iv"),i=Vr(e.tag,16,"tag"),s=Vr(e.ciphertext,1,"ciphertext",{max:Tp}),{ciphertext:u,tag:a,...c}=e,d=Np(t,n);try{let l=Sp("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(c))),l.setAuthTag(i),Buffer.concat([l.update(s),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function Cp(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 _p(e){let t=Pt.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 L(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(Cp(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 da(e){return JSON.parse(L(e))}function Ae(e,t){D.mkdirSync(Pt.dirname(e),{recursive:!0,mode:448}),_p(e);let r=Pt.join(Pt.dirname(e),`.${Pt.basename(e)}.${process.pid}.${Ap(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(Pt.dirname(e),"r");try{D.fsyncSync(o)}finally{D.closeSync(o)}}catch(n){try{D.unlinkSync(r)}catch{}throw n}}var fa=/^0x[0-9a-fA-F]+$/,Rp=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 Lp(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 $p(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=Rp[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=Lp(r),i=o||n.endpoints,s=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&s!=="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:s,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function pa(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!fa.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let s=$p(t,{requirePrivate:r}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let a=[];for(let c of s.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&&fa.test(p.result))return{hash:p.result,endpoint:c,mode:s.mode,chainId:s.chainId,fellBack:!1};a.push({endpoint:c,error:p&&p.error&&p.error.message||`http ${m.status}`})}catch(m){a.push({endpoint:c,error:String(m&&m.message||m).slice(0,160)})}finally{clearTimeout(l)}}if(n&&!r)return{fellBack:!0,mode:s.mode,chainId:s.chainId,attempts:a};throw new Error(`submitPrivate: all private endpoints failed for chain ${s.chainId} (${a.map(c=>`${c.endpoint}:${c.error}`).join("; ")||"none configured"})`)}import{createHmac as Bp,randomBytes as Dp,timingSafeEqual as Fp}from"node:crypto";import te from"node:fs";import ut from"node:path";import{homedir as lo}from"node:os";import{join as fo}from"node:path";var ma=process.env.ORACLE_PUBLIC_DESKTOP==="1",Pp=ma?process.env.ORACLE_CONFIG_DIR||fo(lo(),".config","oracle"):fo(lo(),".config","oracle"),$0=ma?Pp:fo(lo(),".config","mad-desk");var j0="0".repeat(64),M0=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 Jr(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Jr).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Jr(e[r])).join(",")+"}"}var q0=Promise.resolve();function lt(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=s=>{try{return te.realpathSync(s)}catch{return ut.resolve(s)}},n=r(ut.dirname(ut.resolve(e))),o=r(ut.dirname(ut.resolve(t))),i=(s,u)=>u===s||u.startsWith(s+ut.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var jp=864e5,ue=(e,t)=>Bp("sha256",t).update(Jr(e)).digest("hex"),Ce=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Fp(r,n)},Mp=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function qp(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 Yr(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=L(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 Hp(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=Yr(e,r);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let s={policySequence:Number(t),policyMac:String(n)};i&&(s.ledgerInitialized=!0),Ae(e,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(s,r)}})+`
16
- `)}function zp(e,t){let r=Yr(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 Hp(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function Xr(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=L(t),o;try{o=JSON.parse(L(e))}catch(a){throw new Error(`policy: cannot read sealed policy: ${a?.message||a}`)}let i=qp(o,n);lt(r,e);let s=Yr(r,n),u=Number(i.policySequence||0);if(!s.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(u!==s.sequence)throw new Error("policy: rolled back to a superseded policy");if(s.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!Ce(s.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Dt(e,t,r,n,o){let i=`${e}.continuity`,s;try{let u=JSON.parse(L(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(s=u.ledger,!Number.isFinite(s?.windowStartMs)||!Array.isArray(s?.entries)||s.sequence!==void 0&&(!Number.isSafeInteger(s.sequence)||s.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 a=Yr(o,t);if(a.present&&a.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(L(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!==s.sequence||!Ce(u.marker.ledgerMac,ue(s,t))))throw new Error("continuity rollback detected");if(u.marker?.version!==2&&s.sequence!==void 0)throw new Error("continuity rollback detected");if(te.existsSync(n)&&(u.marker?.version!==2||s.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(u.marker?.version===2){let a=JSON.parse(L(n));if(a?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(a?.integrity?.mac,ue(a.marker,t))||a.marker?.version!==1||a.marker.sequence!==s.sequence||!Ce(a.marker.ledgerMac,ue(s,t)))throw new Error("checkpoint rollback detected")}}catch(u){throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}if(r-s.windowStartMs>=jp){let u=new Date(r).toISOString().slice(0,10),a=d=>String(d||"").startsWith("cex:")&&String(d).endsWith(`:${u}`),c=s.entries.map(d=>{if(d.state==="reserved"||d.state==="consumed")return d;if(Array.isArray(d.units)){let l=d.units.map(f=>a(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 a(d.unit)?d:{...d,state:"consumed",value:"0",notional:"0"}});return{windowStartMs:r,entries:c,sequence:s.sequence??0}}return{...s,sequence:s.sequence??0}}function Up(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=Up(o).find(s=>s.unit===r);return i?n+BigInt(i[t]??0):n},0n)}function Gr(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),s=BigInt(n.notional??0);if(i<0n||s<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:s.toString(),fee:u.toString()}});return r.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),r}function Wp(e,t){let r=e[t];if(r==null||r==="")throw new Error(`ledger: ${t} required`);return ae(r,`ledger: ${t}`)}function Bt(e,t){if(String(t).startsWith("cex:")){let[,n,o,i,s,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(s||"")||!/^\d{4}-\d{2}-\d{2}$/.test(u||""))throw new Error("ledger: invalid CEX accounting unit");let a=e.cexAccounts?.[n];if(!a||String(a.accountId)!==o||!Array.isArray(a.venues)||!a.venues.includes(i))throw new Error("ledger: CEX account/venue policy required");if(!a.symbolQuotes||!Object.values(a.symbolQuotes).includes(s))throw new Error("ledger: CEX quote policy required");let c=ae(a.dailyGrossQuoteCap,"ledger: dailyGrossQuoteCap"),d=ae(a.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(([s])=>String(s).toLowerCase()===n)?.[1];if(!o)throw new Error("ledger: ERC-20 token caps required");let i=["maxDailyValueRaw","maxDailyNotionalRaw","maxPerTradeRaw"];for(let s of i)if(o[s]===void 0||o[s]===null||o[s]==="")throw new Error(`ledger: ${s} required`);return i.map(s=>BigInt(o[s]))}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(a=>e[a]!==void 0&&e[a]!==null&&e[a]!=="");if(n.length===r.length)return r.map(a=>Wp(e,a));if(n.length>0){let a=r.filter(c=>!n.includes(c));throw new Error(`ledger: ${a[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 s=q(o,6,"ledger: maxDailyNotionalUsdc"),u=q(i,6,"ledger: maxPerTradeUsdc");return[s,s,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 Ft(e,t){let r=`${e}.lock`,n=Dp(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{L(r)===n&&te.unlinkSync(r)}catch{}}}function qe(e,t,r,n,o){let i=`${e}.continuity`,s={...t,sequence:(t.sequence??0)+1},u=ue(s,r);Ae(e,JSON.stringify({ledger:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:u}})+`
17
- `);let a={version:2,sequence:s.sequence,ledgerMac:u};Ae(i,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(a,r)}})+`
18
- `);let c={version:1,sequence:s.sequence,ledgerMac:u};te.mkdirSync(ut.dirname(n),{recursive:!0,mode:448}),Ae(n,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(c,r)}})+`
19
- `),o&&zp(o,r)}function ar({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:s=0,notional:u=0,fee:a,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");lt(r,e);let p=L(t);return Ft(e,()=>{let w=Dt(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=Gr(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]=Bt(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(s).toString(),notional:BigInt(u).toString(),fee:a===void 0?"0":BigInt(a).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]=Bt(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,qe(e,w,p,r,n),structuredClone(g)}let h;if(c!==void 0){let y=Gr(c);for(let b of y){let[S,A,k]=Bt(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(s),b=BigInt(u),[S,A,k]=Bt(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:a===void 0?"0":BigInt(a).toString(),state:"reserved",atMs:m}}return w.entries.push(h),qe(e,w,p,r,n),structuredClone(h)})}function wa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:s,nowMs:u=Date.now()}){lt(r,e);let a=L(t);return Ft(e,()=>{let c=Dt(e,a,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=Gr(o.units);if(JSON.stringify(w)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(s){if(!Array.isArray(s.units))throw new Error("ledger: reserved units no longer match decoded economics");let g=Gr(s.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]=Bt(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(s){if(s.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(s.value)>BigInt(d.value)||BigInt(s.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[m,f,p]=Bt(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 ha({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){lt(r,e);let s=L(t);return Ft(e,()=>{let u=Dt(e,s,i,r,n),a=u.entries.find(c=>String(c.tradeId)===String(o??""));if(!a)throw new Error("ledger: reservation unavailable");if(a.state==="committed"&&["fee-only","no-fee"].includes(a.settledAs))throw new Error("ledger: reservation unavailable");if(a.state==="committed")return structuredClone(a);if(a.state!=="reserved")throw new Error("ledger: reservation unavailable");return a.state="committed",a.committedAtMs=i,qe(e,u,s,r,n),structuredClone(a)})}function ga({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){lt(r,e);let s=L(t);return Ft(e,()=>{let u=Dt(e,s,i,r,n),a=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!a)throw new Error("ledger: reservation unavailable");let c=structuredClone(a);return a.state="released",a.releasedAtMs=i,qe(e,u,s,r,n),c})}function Vp(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 ya({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:s,disposition:u,nowMs:a=Date.now()}){if(lt(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let c=L(t);return Ft(e,()=>{let d=Dt(e,c,a,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(Vp(s,l.notional))throw new Error("ledger: CEX overfill refused; reservation retained");if(u==="release"){if(!/^0(?:\.0+)?$/.test(s))throw new Error("ledger: nonzero CEX fill cannot release");let m=structuredClone(l);return l.state="consumed",l.releasedAtMs=a,l.value="0",l.notional="0",l.fee="0",qe(e,d,c,r,n),m}return l.state="committed",l.committedAtMs=a,l.filledQuote=s,qe(e,d,c,r,n),structuredClone(l)})}function ba({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){lt(r,e);let s=L(t);return Ft(e,()=>{let u=Dt(e,s,i,r,n),a=u.entries.find(d=>String(d.tradeId)===String(o??""));if(!a)throw new Error("ledger: reservation unavailable");if(a.state==="committed"&&["fee-only","no-fee"].includes(a.settledAs))return structuredClone(a);if(a.state!=="reserved")throw new Error("ledger: reservation unavailable");if(Array.isArray(a.units))return a.state="committed",a.committedAtMs=i,a.units=a.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),a.settledAs=a.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",qe(e,u,s,r,n),structuredClone(a);let c=BigInt(a.fee??0);return c<=0n?(a.state="committed",a.committedAtMs=i,a.value="0",a.notional="0",a.settledAs="no-fee",qe(e,u,s,r,n),structuredClone(a)):(a.state="committed",a.committedAtMs=i,a.value="0",a.notional=c.toString(),a.settledAs="fee-only",qe(e,u,s,r,n),structuredClone(a))})}function Ea(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:G(Mp(t))};return Ce(e.mac,ue(o,L(r)))}function Kp(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function xa(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:G(Kp(t))};return Ce(e.mac,ue(o,L(r)))}import{spawnSync as Jp}from"node:child_process";function Sa(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=Jp(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}import{Wallet as po}from"ethers";import{base58 as mo}from"@scure/base";import{ed25519 as Oa}from"@noble/curves/ed25519.js";import{NETWORK as Ta,TEST_NETWORK as Na,WIF as Gp,p2wpkh as Aa}from"@scure/btc-signer";import{pubECDSA as Yp}from"@scure/btc-signer/utils.js";var Zr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Xp=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},va=e=>{let t=String(e||"").trim();try{let r=Buffer.from(mo.decode(t));return mo.encode(r)===t?r:null}catch{return null}},wo=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(Oa.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},Ia=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),He=(e,t)=>{if(t==="sol")return wo(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`)},Zp=(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 He(r,t)};function ho(e,t){let r=String(t||"").trim();if(e==="evm")return new po(r).privateKey;if(e==="btc")for(let i of[Ta,Na])try{return Buffer.from(Gp(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let c=Zr(r.slice(4));if(!c)throw new Error("sol: invalid explicit hex private key");return He(c,"sol")}if(/^base58:/i.test(r)){let c=va(r.slice(7));if(!Ia(c))throw new Error("sol: invalid explicit base58 private key");return wo(c)}if(/^0x/i.test(r)){let c=Zr(r);if(!c)throw new Error("sol: invalid explicit hex private key");return He(c,"sol")}let i=Zr(r),s=i&&(i.length===32||i.length===64)?He(i,"sol"):null,u=va(r),a=Ia(u);if(s&&a&&!s.equals(a))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(a)return wo(u);if(i)return He(i,"sol")}let n=Zr(r);if(n)return e==="evm"?new po(`0x${n.toString("hex")}`).privateKey:He(n,e);let o=Xp(r);if(o)return He(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Zp(i,e);let s=i.privateKey??i.secretKey??i.key;if(s)return ho(e,Array.isArray(s)?JSON.stringify(s):String(s))}throw new Error(`${e}: unsupported private key format`)}function ka(e,t){if(e==="evm"){let r=new po(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=He(t,"btc"),n=Yp(r);return{kind:e,secret:r.toString("hex"),addresses:[Aa(n,Ta).address,Aa(n,Na).address]}}if(e==="sol"){let r=He(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[mo.encode(Oa.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function Ca(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:ka(t.kind||"evm",ho(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=ka(i,ho(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,s]of Object.entries(n.cex)){if(!/^[A-Za-z0-9._-]{1,64}$/.test(i)||!s||typeof s!="object")throw new Error("local-vault: cex credential record invalid");if(!/^(?:binance|bybit|okx|coinbase)$/.test(s.venue)||!/^[A-Za-z0-9._-]{1,64}$/.test(s.accountId||""))throw new Error("local-vault: cex credential binding invalid");let u=(c,d=!0)=>{let l=s[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)}},a=s.apiSecretEncoding;if(a!==(s.venue==="coinbase"?"base64":"raw"))throw new Error("local-vault: explicit cex secret encoding refused");o.cex[i]=Object.freeze({venue:s.venue,accountId:s.accountId,apiKeyBytes:u("apiKeyBytes"),apiSecretBytes:u("apiSecretBytes"),apiSecretEncoding:a,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 go(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Qp=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),em=Object.freeze(["binance","bybit","okx","coinbase"]),tm=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),rm=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),nm=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),sE=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),om=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),aE=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),cE=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),uE=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),lE=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function yo(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 _a(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 im(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function sm(e){return new Date(e).toISOString().slice(0,10)}function am(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 Qr(e={},t={},r=Date.now()){for(let C of Object.keys(e)){let z=C.toLowerCase();if(om.some(U=>U.toLowerCase()===z))throw new Error(`cex-policy: envelope field ${C} forbidden`);if(!nm.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(!Qp.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=le(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!em.includes(o)||!tm[o]||!rm[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:s}=am(e,t);if(!Array.isArray(s.venues)||!s.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(s.symbols)||!s.symbols.includes(u))throw new Error(`cex-policy: symbol ${u} not allowlisted`);let a=le(e.quote,"quote",/^[A-Z0-9._-]{1,24}$/);if(!s.symbolQuotes||typeof s.symbolQuotes!="object"||s.symbolQuotes[u]!==a)throw new Error("cex-policy: quote does not match sealed symbol policy");let c=le(s.accountId,"accountId",/^[A-Za-z0-9._-]{1,64}$/);if(!Array.isArray(s.allowedOperations)||!s.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(s.base!==d||s.quote!==a)throw new Error("cex-policy: base/quote do not match sealed account policy");if(s.credentialRecordRef!==i)throw new Error("cex-policy: credential record reference mismatch");let l=s.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=_a(e.baseSize,"baseSize"),g=_a(e.limitPrice,"limitPrice"),!m)throw new Error("cex-policy: clientOrderId required");if(h=yo(e.maxQuoteNotional,"maxQuoteNotional"),y=im(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=yo(s.perOrderQuoteCap,"sealed perOrderQuoteCap"),A=yo(s.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}:${a}:${sm(r)}`;return Object.freeze({kind:n,venue:o,symbol:u,base:d,quote:a,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 Ra({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Xr(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Qr(e,n,r);return ar({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 K from"node:fs";import dt from"node:path";import{createHmac as cm,randomBytes as um,timingSafeEqual as lm}from"node:crypto";var en=(e,t)=>cm("sha256",e).update(JSON.stringify(t)).digest("hex"),La=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&lm(r,n)},$a=e=>Buffer.from(L(e));function Pa({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 K.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),s=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 K.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{K.mkdirSync(dt.dirname(n),{recursive:!0,mode:448});let l=um(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()})+`
20
- `;for(;;)try{let w=K.openSync(f,"wx",384);try{K.writeFileSync(w,p),K.fsyncSync(w)}finally{K.closeSync(w)}try{K.linkSync(f,n)}finally{K.unlinkSync(f)}break}catch(w){try{K.existsSync(f)&&K.unlinkSync(f)}catch{}if(w?.code!=="EEXIST")throw new Error("cex-state: lock refused");let g;try{g=K.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(s(h)===!1&&Date.now()-h.createdAtMs>3e4){try{K.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(K.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");K.unlinkSync(n)}},a=()=>{let d=$a(t);try{if(!K.existsSync(e)){if(K.existsSync(r))throw new Error("cex-state: rollback detected");return{version:1,sequence:0,orders:[]}}let l=JSON.parse(L(e));if(!La(l.mac,en(d,l.state)))throw new Error("cex-state: integrity failed");let m=JSON.parse(L(r));if(!La(m.mac,en(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=$a(t);try{let m={...d,sequence:d.sequence+1},f=en(l,m),p={version:1,sequence:m.sequence,stateMac:f};return K.mkdirSync(dt.dirname(e),{recursive:!0,mode:448}),K.mkdirSync(dt.dirname(r),{recursive:!0,mode:448}),Ae(r,JSON.stringify({marker:p,mac:en(l,p)})+`
7
+ Type digest ${t}: `}import{createHash as Zu,randomBytes as Qu,timingSafeEqual as ed}from"node:crypto";import{base58 as Zi}from"@scure/base";import{Interface as _i}from"ethers";Er();var Yt=e=>String(e||"").toLowerCase(),hu=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","authorizationList","slippageBps","expiresAtMs"]),gu=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function ke(e){try{return gu.has(BigInt(e))}catch{return!1}}var we=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},yi=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},At=(e,t,r,n=String)=>{if(!Array.isArray(t)||t.length===0)throw new Error(`policy: ${r} allowlist is empty`);if(!t.map(n).includes(n(e)))throw new Error(`policy: ${r} not allowed`)};function xr(e,t,{nowMs:r=Date.now(),networkFees:n,requireNetworkFees:o=!1}={}){if(!e||!t)throw new Error("policy: artifact and policy required");if(Object.keys(e).some(f=>!hu.has(f)))throw new Error("policy: unexpected EVM artifact field");if(e.gasPrice!=null&&(e.maxFeePerGas!=null||e.maxPriorityFeePerGas!=null))throw new Error("policy: ambiguous EVM fee fields");if(e.type!=null&&![0,1,2,4].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");if(Number(e.type)===4){if(!Array.isArray(e.authorizationList)||e.authorizationList.length===0||e.authorizationList.length>8)throw new Error("policy: type-4 requires 1-8 authorizationList entries");for(let[f,p]of e.authorizationList.entries()){if(!p||typeof p!="object")throw new Error(`policy: authorizationList[${f}] required`);At(p.address,t.destinations,"destination",Yt);try{if(BigInt(p.chainId)!==BigInt(e.chainId))throw new Error("policy: type-4 authorization chainId must match transaction")}catch(w){throw String(w?.message||"").includes("authorization chainId")?w:new Error("policy: type-4 authorization chainId must match transaction")}}if(String(e.data||"0x").toLowerCase()!=="0x")throw new Error("policy: type-4 calldata must be empty");if(we(e.value,"value")!==0n)throw new Error("policy: type-4 cannot transfer native value")}else if(e.authorizationList!=null)throw new Error("policy: authorizationList is only valid on type-4");let i=(f,p)=>{try{return BigInt(f)===BigInt(p)}catch{return String(f)===String(p)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(f=>i(f,e.chainId)))throw new Error("policy: chain not allowed");if(At(e.to,t.destinations,"destination",Yt),At(String(e.data||"0x").slice(0,10),t.selectors,"selector",f=>String(f).toLowerCase()),At(e.from,t.owners,"owner",Yt),oe(e.data)){let f;try{f=Le(e.data)}catch(w){throw new Error(`policy: malformed approval calldata: ${w?.message||w}`)}At(f.spender,t.spenders,"spender",Yt),At(f.token||e.to,t.erc20Tokens,"ERC-20 token",Yt);let p=we(t.maxApproval,"maxApproval");if(BigInt(f.amount)>p)throw new Error("policy: approval exceeds cap");if(f.additive)throw new Error("policy: additive approval cannot be bounded; use approve() with an absolute amount")}if(we(e.value,"value")>we(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=we(e.gasLimit,"gasLimit");if(s>we(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let l=e.maxFeePerGas??e.gasPrice,a=we(l,"feePerGas")*s,c=0n;try{if(ke(e.chainId)&&(e.l1FeeWei===void 0||e.operatorFeeWei===void 0))throw new Error("missing")}catch{throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(e.l1FeeWei!==void 0&&(c+=we(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(c+=we(e.operatorFeeWei,"operatorFeeWei")),ke(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let f=we(n.l1FeeWei,"estimated l1FeeWei")+we(n.operatorFeeWei,"estimated operatorFeeWei");if(c<f)throw new Error("policy: rollup fee attestation understates estimate")}if(a+c>we(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let u=yi(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>u)throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r)throw new Error("policy: artifact expired");let m=yi(t.maxTtlMs??12e4,"maxTtlMs");if(m<=0||e.expiresAtMs-r>m)throw new Error("policy: artifact TTL exceeds cap");return!0}import{TypedDataEncoder as xi,getAddress as be}from"ethers";Er();import{TypedDataEncoder as Og,getAddress as Tg,isAddress as Ng}from"ethers";var bi=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),In=Object.freeze({Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"receiver",type:"address"},{name:"makerAsset",type:"address"},{name:"takerAsset",type:"address"},{name:"makingAmount",type:"uint256"},{name:"takingAmount",type:"uint256"},{name:"makerTraits",type:"uint256"}]});import{TypedDataEncoder as Mg,getAddress as qg,isAddress as Hg}from"ethers";var Rg=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});Er();var Ei=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Gg=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var kn=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),Yg=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});var bu=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"]),Eu="0x0000000000000000000000000000000000000000";function On(e,t,r=256){if(typeof e!="string"||!e||e.length>r)throw new Error(`evm-order: bounded ${t} required`);return e}function Si(e,t){let r=String(e||"").replace(/\/$/,"");if(!bu.some(o=>r===`${o}/v4.0/${t}`||r===`${o}/v4.1/${t}`))throw new Error("evm-order: submitTo must be the official 1inch orderbook");return r}function Ai(e,t){let r={1:"https://api.cow.fi/mainnet/api/v1/orders",100:"https://api.cow.fi/xdai/api/v1/orders",42161:"https://api.cow.fi/arbitrum_one/api/v1/orders",8453:"https://api.cow.fi/base/api/v1/orders"}[Number(t)],n=String(e||"").replace(/\/$/,"");if(!r||n!==r)throw new Error("evm-order: cow submitTo must be official api.cow.fi");return n}function vi(e,t){let r=e?.Order,n=t.Order;return!Array.isArray(r)||r.length!==n.length?!1:r.every((o,i)=>o?.name===n[i].name&&o?.type===n[i].type)}function Ii(e,...t){let r=Array.isArray(e.tokens)?e.tokens.map(n=>String(n).toLowerCase()):[];if(!r.length)throw new Error("evm-order: tokens allowlist is empty");if(!r.includes("*")){for(let n of t)if(!r.includes(String(n).toLowerCase()))throw new Error("evm-order: token not allowed")}}function ki(e,t,{allowZero:r=!1}={}){let n=String(t||"").toLowerCase();if(!n)throw new Error("evm-order: receiver required");if(n===Eu){if(!r)throw new Error("evm-order: receiver must equal owner");return}if(n!==e)throw new Error("evm-order: receiver must equal owner")}function rt(e,t){if(e?.surface!=="evm-order")throw new Error("evm-order: surface evm-order required");if(e.action!=="order")throw new Error("evm-order: action must be order");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("evm-order: structured artifact required");let n=On(r.kind,"kind",32);if(n==="option")throw new Error("evm-order: option kind refused until official Derive/Lyra domain is pinned");if(n==="cow"){let u=Number(r.chainId??e.chainId);if(Ai(r.submitTo,u),On(e.destination,"destination",32)!=="cowswap")throw new Error("evm-order: cow destination must be cowswap");let m=Ei[u];if(!m)throw new Error(`evm-order: unsupported cow chainId ${u}`);let f=r.domain||r.typedData?.domain,p=r.types||r.typedData?.types,w=r.message||r.typedData?.message;if(!f||!p?.Order||!w)throw new Error("evm-order: CoW EIP-712 Order required");if(!vi(p,kn))throw new Error("evm-order: cow types must be official GPv2 Order");if(Number(f.chainId)!==u)throw new Error("evm-order: cow domain chain mismatch");if(String(f.name)!=="Gnosis Protocol"||String(f.version)!=="v2")throw new Error("evm-order: cow domain must be official GPv2");if(be(f.verifyingContract)!==be(m))throw new Error("evm-order: cow verifyingContract must be official GPv2 settlement");let g=String(e.owner||"").toLowerCase();ki(g,w.receiver),Ii(t,w.sellToken,w.buyToken);let h=be(w.sellToken),y=String(w.feeAmount||"0"),b=(BigInt(w.sellAmount)+BigInt(y)).toString();return Object.freeze({unit:`erc20:${h.toLowerCase()}`,value:b,notional:b,fee:y,submitTo:Ai(r.submitTo,u),digest:xi.hash(f,{Order:kn.Order},w),chainId:u,kind:"cow",receiver:be(w.receiver),sellAmount:String(w.sellAmount),buyAmount:String(w.buyAmount)})}if(n!=="1inch-limit")throw new Error("evm-order: unsupported kind");if(On(e.destination,"destination",32)!=="1inch-lop")throw new Error("evm-order: destination must be 1inch-lop");let o=Number(r.chainId??e.chainId),i=bi[o];if(!i)throw new Error(`evm-order: unsupported chainId ${o}`);Si(r.submitTo,o);let s=r.domain||r.typedData?.domain,l=r.types||r.typedData?.types,a=r.message||r.typedData?.message;if(!s||!l?.Order||!a)throw new Error("evm-order: EIP-712 Order required");if(!vi(l,In))throw new Error("evm-order: types must be official LOP v4 Order");if(Number(s.chainId)!==o)throw new Error("evm-order: domain chain mismatch");if(be(s.verifyingContract)!==be(i))throw new Error("evm-order: verifyingContract must be official LOP v4");if(s.name!=="1inch Limit Order Protocol"||String(s.version)!=="4")throw new Error("evm-order: EIP-712 domain must be official LOP v4");let c=String(e.owner||"").toLowerCase();if(be(a.maker).toLowerCase()!==c)throw new Error("evm-order: maker must equal owner");ki(c,a.receiver,{allowZero:!0}),Ii(t,a.makerAsset,a.takerAsset);let d=xi.hash(s,{Order:In.Order},a);return Object.freeze({unit:`erc20:${be(a.makerAsset).toLowerCase()}`,value:String(a.makingAmount),notional:String(a.makingAmount),fee:"0",submitTo:Si(r.submitTo,o),digest:d,chainId:o,kind:"1inch-limit",receiver:be(a.receiver),makerAsset:be(a.makerAsset),takerAsset:be(a.takerAsset),makingAmount:String(a.makingAmount),takingAmount:String(a.takingAmount)})}var Ri=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]);var Tn=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,delegate:0,identity:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0}),xu=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Li=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),Su=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),Sr=new _i(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Oi=new _i(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),Au=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}});var Zt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},N=(e,t)=>{try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`envelope: ${t} must be a non-negative integer`)}},Ti=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},vu=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},X=(e,t,r)=>{if(!vu(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Xt=(e,t,r)=>{Array.isArray(t)&&t.length&&X(e,t,r)},P=(e,t)=>{let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`envelope: ${t} must be a 20-byte address`);return r},nt=e=>String(e||"0x").slice(0,10).toLowerCase(),$i=e=>N(e.gasLimit,"gasLimit")*N(e.maxFeePerGas??e.gasPrice,"feePerGas")+N(e.l1FeeWei??0,"l1FeeWei")+N(e.operatorFeeWei??0,"operatorFeeWei");function vt(e,t,r,{dynamicTail:n=!1}={}){let o=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(o)||o.length<10+t*64)throw new Error(`envelope: malformed ${r} calldata`);if(!n&&o.length!==10+t*64)throw new Error(`envelope: malformed ${r} calldata`);return{hex:o,word:i=>o.slice(10+i*64,10+(i+1)*64)}}function Q(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function Ee(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function Iu(e){if(nt(e)!=="0x095ea7b3")return null;let t=vt(e,2,"approval");return{kind:"approval",spender:Q(t.word(0),"approval spender"),amount:Ee(t.word(1),"approval amount")}}function Pi(e,t){let r=t==="router02-exact-input-single"?7:8,n=vt(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:Q(n.word(0),"input token"),outputToken:Q(n.word(1),"output token"),recipient:Q(n.word(3),"recipient"),amountIn:Ee(n.word(o),"amountIn"),minimumOut:Ee(n.word(o+1),"amountOutMinimum")}}function ku(e){let t=vt(e,12,"Across depositV3",{dynamicTail:!0}),r=Ee(t.word(11),"message offset");if(r!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let n=10+Number(r)*2;if(t.hex.length<n+64)throw new Error("envelope: malformed Across depositV3 message");let o=Number(BigInt(`0x${t.hex.slice(n,n+64)}`));if(!Number.isSafeInteger(o))throw new Error("envelope: malformed Across depositV3 message length");let i=Math.ceil(o/32)*64;if(t.hex.length!==n+64+i)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:Q(t.word(0),"depositor"),recipient:Q(t.word(1),"recipient"),inputToken:Q(t.word(2),"input token"),outputToken:Q(t.word(3),"output token"),amountIn:Ee(t.word(4),"inputAmount"),minimumOut:Ee(t.word(5),"outputAmount"),destinationChainId:Ee(t.word(6),"destinationChainId")}}function Ou(e){let t=String(e||"").replace(/^0x/i,"").toLowerCase();if(t.length<86||t.length%2!==0)throw new Error("envelope: malformed Uniswap path");let r=`0x${t.slice(0,40)}`,n=`0x${t.slice(t.length-40)}`;if(!/^0x[0-9a-f]{40}$/.test(r)||!/^0x[0-9a-f]{40}$/.test(n))throw new Error("envelope: malformed Uniswap path tokens");return{inputToken:r,outputToken:n}}function Ni(e,{hasDeadline:t}){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<74)throw new Error("envelope: malformed exactInput calldata");let n=[];for(let g=10;g+64<=r.length;g+=64)n.push(r.slice(g,g+64));let o=(g,h)=>{if(!n[g])throw new Error(`envelope: malformed ${h}`);return BigInt(`0x${n[g]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let s=i/32,l=Number(o(s,"path offset")),a=n[s+1],c=o(s+(t?3:2),"amountIn"),d=o(s+(t?4:3),"amountOutMinimum"),u=s+l/32;if(!Number.isInteger(u)||!n[u])throw new Error("envelope: malformed exactInput path");let m=Number(o(u,"path length")),f=r.slice(10+(u+1)*64,10+(u+1)*64+m*2),{inputToken:p,outputToken:w}=Ou(`0x${f}`);return{kind:"action",action:"swap",inputToken:p,outputToken:w,recipient:Q(a,"recipient"),amountIn:c,minimumOut:d}}function Tu(e){let t=vt(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:Q(t.word(0),"input token"),outputToken:Q(t.word(1),"output token"),recipient:Q(t.word(3),"recipient"),amountIn:Ee(t.word(5),"amountIn"),minimumOut:Ee(t.word(6),"amountOutMinimum")}}function Nu(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let m=10;m+64<=t.length;m+=64)r.push(t.slice(m,m+64));let n=Number(BigInt(`0x${r[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${r[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let s=Number(BigInt(`0x${r[o+1]}`)),l=o+1+s/32,a=Number(BigInt(`0x${r[l]}`)),d=`0x${t.slice(10+(l+1)*64,10+(l+1)*64+a*2)}`,u=nt(d);if(u!=="0x04e45aaf"&&u!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Pi(d,u==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function Cu(e,t){let r=nt(e),n=Li[r];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed selector");if(n.layout==="router02-exact-input-single"||n.layout==="swap-router-exact-input-single")return{...Pi(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...Ni(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...Ni(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...Nu(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Tu(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...ku(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function _u(e){let t=vt(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:Q(t.word(0),"mint NFT contract"),feeRecipient:Q(t.word(1),"mint fee recipient"),recipient:Q(t.word(2),"mint recipient"),quantity:Ee(t.word(3),"mint quantity")}}function Ru(e){let t;try{t=Oi.decodeFunctionData("mintAllowList",e)}catch{throw new Error("envelope: malformed SeaDrop mintAllowList calldata")}let r=t[4],n=[...t[5]].map(String);if(n.length<1||n.length>64||n.some(a=>!/^0x[0-9a-fA-F]{64}$/.test(a)))throw new Error("envelope: bounded canonical SeaDrop allowlist proof required");if(Oi.encodeFunctionData("mintAllowList",[t[0],t[1],t[2],t[3],r,n]).toLowerCase()!==String(e).toLowerCase())throw new Error("envelope: SeaDrop allowlist calldata must be canonical");let i=BigInt(r.startTime),s=BigInt(r.endTime);if(s<=i)throw new Error("envelope: SeaDrop allowlist stage time range is invalid");let l=BigInt(t[3]);if(BigInt(r.maxTotalMintableByWallet)<l)throw new Error("envelope: SeaDrop allowlist wallet cap is below quantity");return{kind:"mint",action:"mint",mintType:"allowlist",contract:P(t[0],"mint NFT contract"),feeRecipient:P(t[1],"mint fee recipient"),recipient:P(t[2],"mint recipient"),quantity:l,mintPrice:BigInt(r.mintPrice),startTime:i,endTime:s,dropStageIndex:BigInt(r.dropStageIndex),proof:n}}function Lu(e,t){let r=nt(e);if(String(t).toLowerCase()==="nft-mint")return $u(e);let n=Su[r];if(!n)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed NFT selector");if(n.layout==="seadrop-mint-public")return{..._u(e),selector:r,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...Ru(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function $u(e){let t=nt(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=Au[t];if(!r)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(r.layout==="mint-no-args")return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:1n};if(r.layout==="mint-quantity"){let n=vt(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:Ee(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function Ar(e){let t=e?.artifact;if(Array.isArray(t?.transactions))return t.transactions;if(t?.transaction&&typeof t.transaction=="object")return[t.transaction];if(t?.data)return[t];throw new Error("envelope: ordered EVM transaction batch required")}function Bi(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let s=P(e.owner,"owner"),l=e.artifact,a=Number(l?.chainId??Ar(e)[0]?.chainId);if(!Number.isSafeInteger(a)||a<=0)throw new Error("envelope: explicit batch chainId required");if(X(a,t.chains,"chain"),l?.owner!==void 0&&P(l.owner,"batch owner")!==s)throw new Error("envelope: explicit batch owner mismatch");let c=Ar(e);if(!c.length||c.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,u=0n,m=0n;for(let f of c){if(!f||typeof f!="object"||Array.isArray(f))throw new Error("envelope: structured EVM transaction required");if(Number(f.chainId)!==a)throw new Error("envelope: every batch leg must use the same chain");if(P(f.from,"transaction owner")!==s)throw new Error("envelope: every batch leg must use the same owner");if(X(nt(f.data),t.selectors,"selector"),d+=N(f.value??0,"value"),u+=N(f.gasLimit,"gasLimit"),m+=$i(f),ke(a)&&(f.l1FeeWei===void 0||f.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>N(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(u>N(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(m>N(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:c,chainId:a,owner:s,totalValue:d,totalGas:u,totalFee:m}}function Di(e,t,{nowMs:r=Date.now(),routeAttestationSecret:n}={}){let o=String(e?.surface||"");if(o!=="evm-swap"&&o!=="evm-bridge")throw new Error("envelope: strict EVM swap/bridge surface required");let i=Zt(e.provider,"provider",64).toLowerCase();X(i,t.providers,"provider");let s=Bi(e,t,o,{nowMs:r}),l=[],a=-1;for(let p=0;p<s.transactions.length;p++){let w=s.transactions[p],g=Iu(w.data),h;if(g){if(a!==-1)throw new Error("envelope: approval must be before action");if(N(w.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let x=P(w.to,"approval token");if(X(x,t.tokens,"token"),X(g.spender,t.spenders,"spender"),g.amount>N(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...g,token:x,index:p}}else{if(a!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");X(w.to,t.destinations,"destination"),h={...Cu(w.data,i),target:P(w.to,"action target"),index:p},a=p}let y=N(w.value??0,"value"),b=N(w.gasLimit,"gasLimit");l.push({...h,value:y,gas:b,fee:$i(w)})}if(a<0)throw new Error("envelope: reviewed swap/bridge action required");let c=l[a],d=o==="evm-swap"?"swap":"bridge";if(c.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if(P(e.destination,"destination")!==c.target)throw new Error("envelope: destination must equal decoded action target");if(c.recipient!==s.owner)throw new Error("envelope: decoded recipient must equal owner");if(c.depositor&&c.depositor!==s.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(X(c.inputToken,t.tokens,"input token"),X(c.outputToken,t.tokens,"output token"),c.amountIn<=0n||c.amountIn>N(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(c.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(an(e.autoSlippage,{nowMs:r,chainId:s.chainId,venue:i,tx:s.transactions[a],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(c.minimumOut!==N(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(c.action==="bridge"&&N(e.toChainId,"toChainId")!==c.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let u=l.filter(p=>p.kind==="approval");if(!new Set([...xu,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(p=>String(p).toLowerCase()):[]]).has(c.inputToken))throw new Error("envelope: strict local signer swap/bridge requires native input token; use wallet signing for token-unit rails");if(u.length)throw new Error("envelope: native-value action must not include token approval");if(c.value!==c.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let f=Object.freeze({quoteAmountOut:N(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:N(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...s,decoded:l,action:c,provider:i,authenticatedQuote:f}}function Pu(e,t,{nowMs:r}){let n=e.anvilAttestation,o=e.artifact?.anvilAttestation;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("envelope: Anvil attestation is required");if(!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: Anvil attestation artifact mismatch");if(Number(n.version)!==1||n.source!=="anvil-snapshot-rpc-reviewed-runtime")throw new Error("envelope: unsupported Anvil attestation");if(Number(n.chainId)!==4663)throw new Error("envelope: Anvil attestation chain mismatch");let i=P(e.destination,"Anvil market"),s=P(e.contract,"NFT contract"),l=P(e.paymentToken,"payment token");if(P(n.market,"attested Anvil market")!==i)throw new Error("envelope: Anvil attestation market mismatch");if(P(n.collection,"attested NFT collection")!==s)throw new Error("envelope: Anvil attestation collection mismatch");if(P(n.paymentToken,"attested payment token")!==l)throw new Error("envelope: Anvil attestation payment token mismatch");let a=Number(e.paymentTokenDecimals??e.artifact?.paymentTokenDecimals);if(!Number.isSafeInteger(a)||a<0||a>255||Number(n.paymentTokenDecimals)!==a)throw new Error("envelope: Anvil payment token decimals mismatch");let c=N(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei").toString();if(N(n.nativeSwapFeeWei,"attested nativeSwapFeeWei").toString()!==c)throw new Error("envelope: Anvil attestation native swap fee mismatch");let d=Number(n.snapshotFetchedAtMs),u=Number(n.snapshotExpiresAtMs);if(!Number.isFinite(d)||!Number.isFinite(u)||d>r||u<=r||u<=d)throw new Error("envelope: Anvil snapshot attestation is stale");let m=N(n.blockNumber,"attested blockNumber");if(m<=0n||!/^0x[0-9a-f]{64}$/.test(String(n.blockHash||"").toLowerCase()))throw new Error("envelope: Anvil block attestation is invalid");let f=String(n.runtimeCodeHash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(f))throw new Error("envelope: Anvil runtime code hash is invalid");let p=Object.entries(t.anvilRuntimeCodeHashes||{}).find(([g])=>g.toLowerCase()===i)?.[1];if(!p||String(p).toLowerCase()!==f)throw new Error("policy: Anvil runtime code hash is not reviewed");let w=Object.entries(t.nftPaymentTokenCaps||{}).find(([g])=>g.toLowerCase()===l)?.[1];if(!w||Number(w.decimals)!==a)throw new Error("policy: Anvil payment token decimals are not reviewed");return Object.freeze({...n,market:i,collection:s,paymentToken:l,paymentTokenDecimals:a,runtimeCodeHash:f,blockNumber:m})}function Ci(e,t){let r=e.artifact,n=e.anvilQuote,o=r?.anvilQuote;if(!n||typeof n!="object"||Array.isArray(n)||!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: exact Anvil quote artifact mismatch");if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("envelope: exact Anvil quote confirmation required");let i=t==="buy"?[[n.totalCostRaw,"anvilQuote.totalCostRaw"],[e.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw"],[r?.maxPaymentTokenAmountRaw,"artifact maxPaymentTokenAmountRaw"],[e.exactQuoteTotalCostRaw,"exactQuoteTotalCostRaw"],[r?.exactQuoteTotalCostRaw,"artifact exactQuoteTotalCostRaw"],[e.preconditions?.confirmedTotalCostRaw,"confirmedTotalCostRaw"]]:[[n.netPayoutRaw,"anvilQuote.netPayoutRaw"],[e.minPayoutRaw,"minPayoutRaw"],[r?.minPayoutRaw,"artifact minPayoutRaw"],[e.exactQuoteNetPayoutRaw,"exactQuoteNetPayoutRaw"],[r?.exactQuoteNetPayoutRaw,"artifact exactQuoteNetPayoutRaw"],[e.preconditions?.confirmedNetPayoutRaw,"confirmedNetPayoutRaw"]],s=N(i[0][0],i[0][1]);for(let[l,a]of i.slice(1))if(N(l,a)!==s)throw new Error(`envelope: Anvil ${t} exact settlement limit mismatch`);return s}function ji(e,t,{nowMs:r=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint or NFT action");let n=Zt(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Xt(n,t.providers,"provider");let o=Bi(e,t,"evm-nft",{nowMs:r});if(n==="anvil-nft"){if(e.action!=="nft")throw new Error("envelope: Anvil requires NFT action");if(o.chainId!==4663)throw new Error("envelope: Anvil requires chain 4663");if(t.confirmationMode!=="exact-human")throw new Error("policy: Anvil requires exact-human confirmation");if(o.transactions.length!==1)throw new Error("envelope: Anvil requires one atomic action with pre-existing approval");if(Number(e.slippageBps)!==0)throw new Error("envelope: Anvil exact limit requires zero slippageBps");let[f]=o.transactions,p=P(e.destination,"Anvil market");if(P(f.to,"Anvil action target")!==p)throw new Error("envelope: Anvil action target mismatch");X(p,t.destinations,"destination");let w=P(e.contract??e.artifact?.contract,"NFT contract");if(Xt(w,t.nftContracts,"NFT contract"),P(e.marketCollection??e.artifact?.marketCollection,"Anvil market collection")!==w)throw new Error("envelope: Anvil market collection mismatch");let h=P(e.paymentToken??e.artifact?.paymentToken,"payment token");Xt(h,t.erc20Tokens,"ERC20 token");let y=Pu(e,t,{nowMs:r}),b=N(e.tokenId??e.artifact?.tokenId,"tokenId"),x=N(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei");if(o.totalValue!==x||N(f.value??0,"Anvil action value")!==x)throw new Error("envelope: Anvil native swap fee mismatch");if(x>N(t.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"))throw new Error("policy: Anvil native swap fee exceeds cap");let A=Zt(e.nftAction,"nftAction",8).toLowerCase(),k;if(A==="buy"){let v=Ci(e,A),_=Object.entries(t.nftPaymentTokenCaps||{}).find(([U])=>U.toLowerCase()===h)?.[1];if(!_)throw new Error("policy: Anvil payment-token cap required");if(v>N(_.maxPerTradeRaw,"maxPerTradeRaw"))throw new Error("policy: Anvil payment amount exceeds cap");if(e.preconditions?.allowanceVerified!==!0||N(e.preconditions?.allowanceRaw,"allowanceRaw")<v)throw new Error("envelope: Anvil pre-existing allowance proof required");let C=Sr.decodeFunctionData("buySpecificNFT",f.data);if(Sr.encodeFunctionData("buySpecificNFT",[C[0],C[1]]).toLowerCase()!==String(f.data).toLowerCase())throw new Error("envelope: non-canonical Anvil buy calldata");if(BigInt(C[0])!==b)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(C[1])!==v)throw new Error("envelope: Anvil maxCost mismatch");k={kind:"nft",action:"buy",tokenId:b,maxPaymentTokenAmountRaw:v,target:p}}else if(A==="sell"){let v=e.preconditions||{},_=P(v.approvedAddress,"NFT approval address");if(v.nftApprovalVerified!==!0||_!==p&&v.approvedForAll!==!0)throw new Error("envelope: Anvil pre-existing NFT approval proof required");let C=Ci(e,A),z=Sr.decodeFunctionData("sellNFT",f.data);if(Sr.encodeFunctionData("sellNFT",[z[0],z[1]]).toLowerCase()!==String(f.data).toLowerCase())throw new Error("envelope: non-canonical Anvil sell calldata");if(BigInt(z[0])!==b)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(z[1])!==C)throw new Error("envelope: Anvil minPayout mismatch");k={kind:"nft",action:"sell",tokenId:b,minPayoutRaw:C,target:p}}else throw new Error("envelope: unsupported Anvil NFT action");return{...o,provider:n,nftAction:A,tokenId:b,paymentToken:h,paymentTokenDecimals:y.paymentTokenDecimals,anvilAttestation:y,decoded:[k]}}let i=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;if(i?.oraclePrepared===!0&&gi(i,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"}),o.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let s=o.transactions[0],l=nt(s.data);X(l,t.selectors,"selector"),X(s.to,t.destinations,"destination");let a=Lu(s.data,n),c=P(e.contract??e.artifact?.contract,"NFT contract");if(Xt(c,t.nftContracts,"NFT contract"),(a.contract||P(s.to,"NFT contract"))!==c)throw new Error("envelope: mint calldata NFT contract mismatch");if(a.recipient&&a.recipient!==o.owner)throw new Error("envelope: mint calldata recipient mismatch");a.feeRecipient&&Xt(a.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let u=N(e.quantity??e.artifact?.quantity,"quantity");if(u<=0n||u>N(t.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(a.quantity!==u)throw new Error("envelope: mint calldata quantity mismatch");let m=N(e.totalWei??e.artifact?.totalWei,"totalWei");if(o.totalValue!==m)throw new Error("envelope: mint value does not match declared totalWei");if(a.mintType==="allowlist"){let f=BigInt(Math.floor(r/1e3));if(a.startTime>f||a.endTime<=f)throw new Error("policy: SeaDrop allowlist stage is not open");if(a.mintPrice*u!==m)throw new Error("envelope: SeaDrop allowlist price does not match declared totalWei")}if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&N(e.priceWei??e.artifact.priceWei,"priceWei")*u!==m)throw new Error("envelope: mint price does not match declared totalWei");if(m>N(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...o,provider:n,decoded:[{...a,target:P(s.to,"mint target"),value:o.totalValue,gas:o.totalGas,fee:o.totalFee}]}}function Bu(e,{localsWaiver:t=!1}={}){if(!(e in Tn))throw new Error("fee: unknown action");return t?0:Tn[e]}function Qt(e,t,{nowMs:r=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:s=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let l=Zt(e.surface,"surface",16);if(!Ri.has(l))throw new Error("envelope: unsupported public surface");let a=Zt(e.action,"action",32);X(l,t.surfaces,"surface"),X(a,t.actions,"action"),X(e.owner,t.owners,"owner"),X(e.destination,t.destinations,"destination");let c=Ti(t.maxTtlMs,"maxTtlMs"),d=Ti(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>c)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>d)throw new Error("policy: slippage exceeds cap");let u=e.artifact;if(!u||typeof u!="object"||Array.isArray(u))throw new Error("envelope: structured artifact required");if(l==="evm-swap"||l==="evm-bridge")Di(e,t,{nowMs:r,routeAttestationSecret:o});else if(l==="evm-nft")ji(e,t,{nowMs:r});else if(l==="evm"){if(!["transfer","approve","delegate","identity"].includes(a))throw new Error(a==="mint"?"envelope: generic evm requires transfer or approve; use strict evm-nft for mint action":"envelope: generic evm requires transfer, approve, delegate, or identity");if(a==="swap"||a==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(Number(u.type)===4&&a!=="delegate")throw new Error("envelope: type-4 requires delegate");if(String(u.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(String(u.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: artifact from mismatch with owner");xr({...u,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:s});let p=String(u.data||"0x").toLowerCase(),w=N(u.value,"EVM value");if(a==="delegate"){if(Number(u.type)!==4)throw new Error("envelope: delegate requires type-4");if(p!=="0x")throw new Error("envelope: 7702 delegate calldata must be empty");if(w!==0n)throw new Error("envelope: 7702 delegate cannot transfer native value")}else if(a==="identity"){if(w!==0n)throw new Error("envelope: ERC-8004 identity cannot transfer native value");let g=p.slice(0,10);if(g!=="0xf2c298be"&&g!=="0x0af28bd3")throw new Error("envelope: ERC-8004 selector not allowed")}else if(p==="0x"){if(w===0n)throw new Error("envelope: native EVM transfer value required")}else if(oe(p)){if(w!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else l==="btc"?fn(e,t):l==="sol"?gn(e,t):l==="hl"?Pe(e,t):l==="poly"?Be(e,t):l==="lighter"?De(e,t):l==="evm-order"&&rt(e,t);let m=Number(e.fee?.oracleFeeBps)===0&&Tn[a]!==0;if(e.fee?.waiver||m&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(m&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let f=Bu(a,{localsWaiver:m});if(Number(e.fee?.oracleFeeBps)!==f)throw new Error("fee: final artifact fee mismatch");return!0}var Nn=Object.freeze([...Ri]),py=Object.freeze({...Li});function Cn(e,t){if(e.surface==="hl")return Pe(e,t);if(e.surface==="poly")return Be(e,t);if(e.surface==="lighter")return De(e,t);if(e.surface==="evm-order")return rt(e,t);if(e.surface==="btc")return fn(e,t);if(e.surface==="sol")return gn(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Di(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1),routeAttestationSecret:t.routeAttestationSecret}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(e.surface==="evm-nft"){let r=ji(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalFee.toString();if(r.provider==="anvil-nft"&&r.nftAction==="buy"){let i=N(e.maxPaymentTokenAmountRaw??e.artifact?.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw").toString(),s=r.totalValue.toString(),l=r.totalFee,a=[{unit:`erc20:${r.paymentToken}`,value:i,notional:i,fee:"0"},{unit:"wei",value:s,notional:(r.totalValue+l).toString(),fee:l.toString()}].sort((c,d)=>c.unit<d.unit?-1:c.unit>d.unit?1:0);return Object.freeze({units:a})}let o=r.totalValue.toString();return Object.freeze({unit:"wei",value:o,notional:(r.totalValue+r.totalFee).toString(),fee:n})}if(String(e.surface).startsWith("evm")){let r=N(e.artifact?.value,"EVM value"),n=N(e.artifact?.gasLimit,"EVM gasLimit"),o=N(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+N(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+N(e.artifact?.operatorFeeWei??0,"EVM operatorFeeWei");return Object.freeze({unit:"wei",value:r.toString(),notional:(r+i).toString(),fee:i.toString()})}throw new Error("envelope: unsupported public surface")}function Fi(e={}){let t={};for(let r of Nn){let n=e[r];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${r} requires simulate, sign, and broadcast functions`);t[r]=Object.freeze({simulate:(o,i)=>n.simulate(structuredClone(o),structuredClone(i)),sign:(o,i)=>n.sign(structuredClone(o),structuredClone(i)),broadcast:(o,i,s)=>n.broadcast(o,structuredClone(i),structuredClone(s))})}}return Object.freeze(t)}function vr(e,t){let r=e?.surface||"evm",n=t?.[r];if(!n)throw new Error(`adapter: ${r} is not configured on this self-host`);return n}import{createHash as Vi}from"node:crypto";import{ed25519 as Ju}from"@noble/curves/ed25519.js";import{base58 as Ki}from"@scure/base";import{RawTx as Bn,SigHash as ot,Transaction as Dn}from"@scure/btc-signer";import{Transaction as jn,keccak256 as $n,verifyTypedData as Pn}from"ethers";import{encode as Du}from"@msgpack/msgpack";import{keccak256 as ju,verifyTypedData as Fu}from"ethers";var It=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),_n=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Mi(e){let t=BigInt(e);if(t<0n||t>=2n**64n)throw new Error("hl-l1: nonce must fit uint64");let r=Buffer.alloc(8);return r.writeBigUInt64BE(t),r}function Mu(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Du(e)),Mi(t)];if(r){let s=String(r).replace(/^0x/i,"");if(!/^[0-9a-fA-F]{40}$/.test(s))throw new Error("hl-l1: vaultAddress must be a 20-byte address");i.push(Buffer.from([1]),Buffer.from(s,"hex"))}else i.push(Buffer.from([0]));return n!=null&&i.push(Buffer.from([0]),Mi(n)),ju(Buffer.concat(i))}function Rn(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:Mu(e,t,{vaultAddress:n,expiresAfter:o})}}function qi(e){let t=e?.typedData;if(t==null)return null;if(typeof t!="object")throw new Error("hl-l1: typedData must match the validated action");if(Object.prototype.hasOwnProperty.call(e,"vaultAddress"))throw new Error("hl-l1: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(e,"expiresAfter"))throw new Error("hl-l1: expiresAfter is not public");let r=Rn(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==It.name||String(t.domain?.version)!==It.version||Number(t.domain?.chainId)!==It.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(It.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(_n.Agent))throw new Error("hl-l1: typedData types must be Hyperliquid Agent");if(t.message?.source!==r.source||String(t.message?.connectionId||"").toLowerCase()!==String(r.connectionId).toLowerCase())throw new Error("hl-l1: typedData message must hash the validated action");return r}async function Hi({wallet:e,action:t,nonce:r,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let s=Rn(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(It,_n,s)}function zi({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:s=null}){try{let l=Rn(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:s}),a=Fu(It,_n,l,e);return String(a).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var qu=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function Ln(e){if(e!=null){if(typeof e=="function")throw new Error("lighter: signed tx_info cannot include functions");if(typeof e=="object"){if(typeof e.toJSON=="function")throw new Error("lighter: signed tx_info cannot define toJSON");if(Array.isArray(e)){for(let t of e)Ln(t);return}for(let t of Object.values(e))Ln(t)}}}function Hu(e){if(typeof e=="string"){if(!e.startsWith("{"))throw new Error("lighter: official signed tx_info JSON required");let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("lighter: official signed tx_info JSON required");return t}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("lighter: official signed tx_info JSON required");return Ln(e),JSON.parse(JSON.stringify(e))}function Ir(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function zu(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^-?(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function Ui(e,t,{signed:r=!1}={}){if(typeof e!="number"||!Number.isSafeInteger(e)||!r&&e<0)throw new Error(`lighter: signed ${t} must be an exact numeric integer`);return e}function Ot(e,t,r,n={}){let o=t.filter(s=>e[s]!==void 0&&e[s]!==null);if(o.length===0)throw new Error(`lighter: ${r} required`);let i=o.map(s=>Ui(e[s],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function Uu(e,t,r){let n=t.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length===0)throw new Error(`lighter: ${r} required`);let o=n.map(i=>String(e[i]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${r}`);return e[n[0]]}function kt(e,t,r,n){let o=Ot(e,t,n);if(BigInt(o)!==Ir(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Wu(e,t,r,n){let o=Ot(e,t,n,{signed:!0});if(BigInt(o)!==zu(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Vu(e){let t={};for(let[r,n]of qu.entries()){let o=n.filter(s=>e[s]!==void 0&&e[s]!==null);if(!o.length)continue;let i=o.map(s=>{let l=e[s];if(r<3)return Ui(l,n[0]);if(typeof l!="string"||l.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return l});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);t[n[0]]=i[0]}return t}function er(e,t){let r=Hu(t),n=kt(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=kt(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=kt(r,["Type","type"],e.orderType,"Type"),s=kt(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),l=kt(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),a=kt(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),c=Wu(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=Ot(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),u=Ot(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),m=Ot(r,["Price","price"],"Price");if(BigInt(d)!==Ir(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(u)!==Ir(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(m)!==Ir(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let f=Uu(r,["IsAsk","is_ask","isAsk"],"IsAsk");if(typeof f!="number"||f!==0&&f!==1)throw new Error("lighter: signed IsAsk must be exact numeric 0 or 1");let p=f===1,w=e.side==="sell";if(p!==w)throw new Error("lighter: signed IsAsk must match the prepared side");let g=Ot(r,["txType","tx_type","TxType"],"txType");if(g!==xn)throw new Error("lighter: signed txType must be official create-order");let h={...Vu(r),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:s,ReduceOnly:l,TriggerPrice:a,OrderExpiry:c,MarketIndex:Number(d),BaseAmount:Number(u),Price:Number(m),IsAsk:p?1:0,txType:g},y=JSON.stringify(h),b=JSON.parse(y);if(b.MarketIndex!==Number(d)||b.BaseAmount!==Number(u)||b.Price!==Number(m)||b.IsAsk!==(p?1:0)||b.txType!==g)throw new Error("lighter: canonical tx_info mutated");return{txType:g,txInfo:y,submitTo:Sn(e.submitTo)}}function Wi(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var Tt=e=>{if(typeof e!="string"||e.length===0||e.length>262144||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return null;let t=Buffer.from(e,"base64");return t.toString("base64")===e?t:null},kr=e=>String(e||"").toLowerCase();function Ku(e,t){if(typeof e!="string")return!1;let r,n;try{r=jn.from(e),n=jn.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,type:t.type,accessList:t.accessList,authorizationList:t.authorizationList})}catch{return!1}return kr(r.from)!==kr(t.from)||kr(r.to)!==kr(t.to)?!1:r.unsignedHash===n.unsignedHash}function Gu(e){let t=Buffer.from(Bn.encode(e)),r=Vi("sha256").update(t).digest();return Buffer.from(Vi("sha256").update(r).digest()).reverse().toString("hex")}function Ji(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Gu(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))return!1;let t=e.nonWitnessUtxo.outputs?.[e.index];return t?BigInt(e.witnessUtxo.amount)===BigInt(t.amount)&&Buffer.from(e.witnessUtxo.script||[]).equals(Buffer.from(t.script||[])):!1}function Yu(e,t){let r=Tt(e),n=Tt(t.psbt);if(!r||!n)return!1;try{let o=Dn.fromPSBT(n),i=Dn.fromPSBT(r);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let s=0;s<i.inputsLength;s++){let l=i.getInput(s),a=o.getInput(s);if(!Ji(a)||!Ji(l))return!1;let c=(h,y)=>{if(h==null&&y==null)return!0;if(h==null||y==null)return!1;try{return Buffer.from(h).equals(Buffer.from(y))}catch{return!1}},d=(h,y)=>{if(h==null&&y==null)return!0;if(h==null||y==null)return!1;try{return Buffer.from(Bn.encode(h)).equals(Buffer.from(Bn.encode(y)))}catch{return c(h,y)}};if(!!l.witnessUtxo!=!!a.witnessUtxo||l.witnessUtxo&&(BigInt(l.witnessUtxo.amount)!==BigInt(a.witnessUtxo.amount)||!c(l.witnessUtxo.script,a.witnessUtxo.script))||!d(l.nonWitnessUtxo,a.nonWitnessUtxo)||!c(l.redeemScript,a.redeemScript)||!c(l.witnessScript,a.witnessScript)||l.sighashType!==void 0&&l.sighashType!==ot.DEFAULT&&l.sighashType!==ot.ALL)return!1;let u=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===ot.ALL,m=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===ot.ALL:!1;for(let h of l.partialSig||[]){let y=Array.isArray(h)?h[1]:h;if(!u(y))return!1}if(l.tapKeySig&&!m(l.tapKeySig))return!1;for(let h of l.tapScriptSig||[]){let y=Array.isArray(h)?h[1]:h;if(!m(y))return!1}let f=h=>h[h.length-1]===ot.ALL,p=h=>h.length>=9&&h.length<=73&&h[1]===h.length-3&&h[2]===2,w=h=>{let y=!1;for(let b of h)if(b instanceof Uint8Array){if(b[0]===48){if(!p(b)||!f(b))return!1;y=!0;continue}if(b.length===64){y=!0;continue}if(b.length===65){if(b[64]!==ot.ALL&&b[64]!==ot.DEFAULT)return!1;y=!0}}return y};if(l.finalScriptWitness){let h;if(Array.isArray(l.finalScriptWitness))h=l.finalScriptWitness;else if(l.finalScriptWitness instanceof Uint8Array){let y=l.finalScriptWitness,b=k=>{let v=y[k];return v===void 0?null:v<253?{value:v,next:k+1}:v===253?{value:y[k+1]|y[k+2]<<8,next:k+3}:null},x=b(0);if(!x)return!1;h=[];let A=x.next;for(let k=0;k<x.value;k++){let v=b(A);if(!v||A+v.value>y.length)return!1;h.push(y.slice(v.next,v.next+v.value)),A=v.next+v.value}if(A!==y.length)return!1}else return!1;if(!h.length||!w(h))return!1}if(l.finalScriptSig instanceof Uint8Array&&l.finalScriptSig.length){let h=l.finalScriptSig,y=[],b=0;for(;b<h.length;){let x=h[b];if(x>=1&&x<=75){if(b+1+x>h.length)return!1;y.push(h.slice(b+1,b+1+x)),b+=1+x;continue}if(x===76){let A=h[b+1];if(A===void 0||b+2+A>h.length)return!1;y.push(h.slice(b+2,b+2+A)),b+=2+A;continue}return!1}if(!y.length||!w(y))return!1}if(![l.partialSig,l.tapKeySig,l.tapScriptSig,l.finalScriptSig,l.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function Gi(e){let t=0,r=0,n=0;for(;n<e.length&&n<3;){let o=e[n++];if(t|=(o&127)<<r,(o&128)===0)return{value:t,offset:n};r+=7}return null}function Xu(e,t,r){let n=Tt(e),o=Tt(t.messageBase64);if(!n||!o)return!1;let i=Gi(n);if(!i||i.value!==1||i.offset!==1)return!1;let s=i.offset+64;if(s>=n.length)return!1;let l=n.subarray(i.offset,s),a=n.subarray(s);if(!a.equals(o))return!1;try{let c=Ki.decode(String(r));return c.length===32&&Ju.verify(l,a,c)}catch{return!1}}function Yi(e,t,r,n){if(e==="evm-order"){let o=r?.domain||r?.typedData?.domain,i=r?.types||r?.typedData?.types,s=r?.message||r?.typedData?.message;if(!o||!i||!s)return!1;try{return String(Pn(o,i,s,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}}if(String(e).startsWith("evm"))return Ku(t,r);if(e==="btc")return Yu(t,r);if(e==="sol")return Xu(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String(Pn(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return zi({signature:t,action:r?.action,nonce:r?.nonce,isMainnet:!String(r?.submitTo||"").includes("testnet"),owner:n?.owner})}if(e==="poly"&&r?.domain&&r.types&&r.message)try{return String(Pn(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return er(r,t),!0}catch{return!1}return!1}function Xi(e,t){try{if(e==="evm-order")return $n(t);if(String(e).startsWith("evm"))return jn.from(t).hash;if(e==="btc"){let r=Tt(t);if(!r)return null;let n=Dn.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=Tt(t);if(!r)return null;let n=Gi(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Ki.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return $n(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return $n(t)}catch{}return null}var td=e=>String(e||"").toLowerCase();function G(e){return Zu("sha256").update(JSON.stringify(e)).digest("hex")}function Nr(e,t,r={}){return xr(e,t,r)}async function rd(e,t={}){if(!ke(e?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(typeof t.estimateNetworkFees!="function")throw new Error("policy: rollup fee estimate required");let r=await t.estimateNetworkFees(e);if(!r||r.l1FeeWei===void 0||r.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");return{l1FeeWei:String(r.l1FeeWei),operatorFeeWei:String(r.operatorFeeWei)}}function Qi(e,t,r=!1){if(!ke(e?.chainId))return!0;if(e.l1FeeWei===void 0||e.operatorFeeWei===void 0)throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei");if(r||t!=null){if(!t||t.l1FeeWei===void 0||t.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let n=BigInt(e.l1FeeWei)+BigInt(e.operatorFeeWei),o=BigInt(t.l1FeeWei)+BigInt(t.operatorFeeWei);if(n<o)throw new Error("policy: rollup fee attestation understates estimate")}return!0}function es(e){if(e==null)return null;let t={tenantId:String(e.tenantId||"").trim(),runId:String(e.runId||"").trim(),handoffHash:String(e.handoffHash||""),idempotencyKey:String(e.idempotencyKey||""),legIndex:e.legIndex,legCount:e.legCount};if(!t.tenantId||!t.runId||!/^[0-9a-f]{64}$/.test(t.handoffHash)||!/^sha256:[0-9a-f]{64}$/.test(t.idempotencyKey)||!Number.isSafeInteger(t.legIndex)||t.legIndex<0||!Number.isSafeInteger(t.legCount)||t.legCount<1||t.legIndex>=t.legCount)throw new Error("confirmation: binding is invalid");return t}var Or=class{#e=new Map;constructor({now:t=Date.now}={}){this.now=t}issue({artifact:t,owner:r,ttlMs:n=6e4,binding:o}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let i=Qu(32).toString("hex");return this.#e.set(i,{digest:G(t),owner:td(r),expiresAtMs:this.now()+n,binding:es(o)}),i}consume(t,r,n){let o=this.#e.get(String(t));if(!o)throw new Error("confirmation: used or unknown nonce");if(o.expiresAtMs<=this.now())throw this.#e.delete(String(t)),new Error("confirmation: expired nonce");let i=Buffer.from(o.digest,"hex"),s=Buffer.from(G(r),"hex");if(!ed(i,s))throw new Error("confirmation: artifact mismatch");if(JSON.stringify(o.binding)!==JSON.stringify(es(n)))throw new Error("confirmation: execution binding mismatch");return this.#e.delete(String(t)),o}clear(){this.#e.clear()}};function nd(e){let t=String(e?.data||"0x").toLowerCase(),r=BigInt(e?.value??0);if(t==="0x"){if(r<=0n)throw new Error("signer: native EVM transfer value required");return!0}if(oe(t)){if(r!==0n)throw new Error("signer: EVM approval cannot transfer native value");return!0}throw new Error("signer: unsupported EVM calldata; use a versioned envelope")}function od(e={},t={}){let r={};for(let n of new Set([...Object.keys(e||{}),...Object.keys(t||{})]))r[n]=(BigInt(t?.[n]??0)-BigInt(e?.[n]??0)).toString();return r}function id(e){return e==="evm"||e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Tr(e,t){let r=String(t||"");if(e==="evm-order"||String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(r);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(r);if(e==="sol")try{let n=Zi.decode(r);return n.length===64&&Zi.encode(n)===r}catch{return!1}return e==="hl"?/^0x[0-9a-fA-F]{64}$/.test(r):e==="poly"?/^0x[0-9a-fA-F]{64}$/.test(r):!1}function ts(e,t,r){return!Tr(e,t)||!Tr(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function sd(e){let t=e?.confirmationMode;if(t!=="exact-human"&&t!=="auto-within-rails")throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");return t}async function Fn({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:s,nowMs:l}){let a=sd(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(a!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(t?.triggerAttestation,e,l())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(a!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(s)return n.confirmations.consume(r,e,n.confirmationBinding);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=l())throw new Error("confirmation: expired nonce");return i}function ad(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function cd(e,t){return e&&ad(e.surface)?Ar(e):[t]}function ld(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!ts(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function ud(e,t){let r=e?.verifiedBefore??e?.before,n=e?.verifiedAfter??e?.after;return{transactionHash:t,status:e?.status,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:od(r,n),...e?.order?{order:structuredClone(e.order)}:{}}}function dd(e){return Number.isSafeInteger(e)&&e>0?"commit":"settle-failed"}async function Mn(e,t,r){if(!r.isArmed())throw new Error("signer: disarmed");let n=typeof r.armGeneration=="function",o=typeof r.broadcastWithArmFence=="function";if(n!==o)throw new Error("signer: arm generation and broadcast fence must be configured together");let i=n?r.armGeneration():null,s=e?.version===1&&e?.surface?e:null,l=s?s.artifact:(()=>{let{tradeId:b,...x}=e||{};return x})(),a=cd(s,l),c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,d=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),u=await Fn({artifact:e,envelope:s,nonce:t,deps:r,policy:c,confirmation:null,consumeNonce:!0,nowMs:d}),m=G(e),f=(b={})=>{s?Qt(s,c,b):(Nr(l,c,{nowMs:b.nowMs,networkFees:b.networkFees,requireNetworkFees:b.requireNetworkFees}),nd(l))},p=async b=>{let x=!s||id(s.surface),A=x?await rd(b,r):void 0;return{nowMs:d(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:A,requireNetworkFees:x&&ke(b?.chainId)}};f({nowMs:d(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let b of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[b]!="function")throw new Error(`signer: ${b} is required`);let w=r.reserveLedger(s||e,c);if(!w)throw new Error("signer: ledger reservation required");let g=!1,h=[];try{for(let[b,x]of a.entries()){if(typeof r.simulate!="function"||await r.simulate(x,s)!==!0)throw new Error("signer: strict affirmative simulation required");let A=await p(x);if((A.requireNetworkFees||A.networkFees!=null)&&Qi(x,A.networkFees,A.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,u=await Fn({artifact:e,envelope:s,nonce:t,deps:r,policy:c,confirmation:u,consumeNonce:!1,nowMs:d}),f(A),r.validateReservation(w,c,s&&typeof r.decodeEconomics=="function"?r.decodeEconomics(s,c):void 0),g=!0;let k=await r.sign(x,s);if(typeof r.verifySigned!="function"||await r.verifySigned(k,x,s)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");let v=s?.surface||"evm",_=Xi(v,k);if(r.executionAttempt&&await r.executionAttempt.recordSigned({txIndex:b,txCount:a.length,surface:v,signedTransactionId:_,...v==="hl"?{owner:s.owner,cloid:x.action?.type==="order"?x.action.orders?.[0]?.c??null:null,hlTestnet:x.submitTo==="https://api.hyperliquid-testnet.xyz/exchange"}:{}}),!r.isArmed())throw new Error("signer: disarmed before broadcast");if(G(e)!==m)throw new Error("signer: artifact mutated after signing");c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,u=await Fn({artifact:e,envelope:s,nonce:t,deps:r,policy:c,confirmation:u,consumeNonce:!1,nowMs:d});let C=await p(x);(C.requireNetworkFees||C.networkFees!=null)&&Qi(x,C.networkFees,C.requireNetworkFees),f(C),r.validateReservation(w,c,s&&typeof r.decodeEconomics=="function"?r.decodeEconomics(s,c):void 0),r.executionAttempt&&await r.executionAttempt.recordBroadcastAuthorized({txIndex:b});let z=()=>r.broadcast(k,x,s),U=o?await r.broadcastWithArmFence(i,z):await z(),R=U?.status,$=ld(U,v);if(!ts(v,$,_))throw new Error("signer: receipt transaction hash does not match signed bytes");if(R===0||R==="0x0")throw Tr(v,$)?(r.executionAttempt&&await r.executionAttempt.recordCanonicalReceipt({txIndex:b,receipt:U}),dd(h.length)==="commit"?r.commitLedger(w):r.settleFailedLedger(w),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(R!==1&&R!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Tr(v,$))throw new Error("signer: successful broadcast requires a valid transaction hash");r.executionAttempt&&await r.executionAttempt.recordCanonicalReceipt({txIndex:b,receipt:U}),h.push(ud(U,$))}}catch(b){throw g||r.releaseLedger(w),b}if(r.commitLedger(w),h.length===1){let b={receipt:h[0]};return s?.surface==="evm-bridge"&&(b.originStatus="success",b.destinationStatus="unverified",b.destinationSuccess=!1,b.note="Origin-chain receipts do not prove destination-chain settlement."),b}let y={receipts:h,status:"success"};return s?.surface==="evm-bridge"&&(y.originStatus="success",y.destinationStatus="unverified",y.destinationSuccess=!1,y.note="Origin-chain receipts do not prove destination-chain settlement."),y}var rs=new Set(["127.0.0.1","::1","localhost"]),md=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&pd(r,n)},O=(e,t,r)=>{let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function wd(e){let t=String(e||"");if(t.startsWith("[")){let r=t.indexOf("]");if(r>1)return t.slice(1,r)}return t.split(":")[0]}var Nt=e=>new Promise((t,r)=>{let n=0,o=[],i=!1;e.on("data",s=>{n+=s.length,n>64*1024&&!i?(i=!0,r(new Error("request refused")),e.resume()):i||o.push(s)}),e.on("end",()=>{if(!i)try{t(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{r(new Error("request refused"))}}),e.on("error",r)}),ns=e=>e?.idempotencyKey===void 0?void 0:{tenantId:e.tenantId,runId:e.runId,handoffHash:e.handoffHash,idempotencyKey:e.idempotencyKey,legIndex:e.legIndex,legCount:e.legCount},hd=e=>e==="hl"||e==="btc"||e==="sol"||["evm","evm-swap","evm-bridge","evm-nft"].includes(e);function os(e={}){let t=e.host||"127.0.0.1";if(!rs.has(t))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let c of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[c]!="function")throw new Error(`signer: ${c} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Or,n=e.pending||new Map,o=(c,d)=>{try{e.ledgerObserver?.[c]?.(d)}catch{}};function i(c){let d=c.artifact?.version===1&&c.artifact?.surface?c.artifact:null,u=d?.artifact||c.artifact||{};return{id:c.digest.slice(0,8),digest:c.digest,surface:d?.surface||"evm",action:d?.action||"evm",chain:u.chainId??u.network??null,to:u.to||d?.destination||null,value:u.value??u.message?.sellAmount??u.message?.makingAmount??null,receiver:u.message?.receiver||u.typedData?.message?.receiver||null,maker:u.message?.maker||u.typedData?.message?.maker||null,makingAmount:u.message?.makingAmount||u.typedData?.message?.makingAmount||null,takingAmount:u.message?.takingAmount||u.typedData?.message?.takingAmount||null,sellAmount:u.message?.sellAmount||u.typedData?.message?.sellAmount||null,buyAmount:u.message?.buyAmount||u.typedData?.message?.buyAmount||null,kind:u.kind||null,type:u.type??null,authorizationList:u.authorizationList||null,feeAmount:u.message?.feeAmount||u.typedData?.message?.feeAmount||null,createdAtMs:c.createdAtMs}}function s(c){let d=String(c||"").trim().toLowerCase().replace(/^0x/,"");return d?[...n.values()].filter(u=>u.digest.toLowerCase().startsWith(d)||u.digest.slice(0,8)===d):[...n.values()]}let l=e.origin||`http://${t}`;return fd.createServer(async(c,d)=>{try{let u=String(c.headers.authorization||"").replace(/^Bearer /i,"");if(!md(u,e.token))return O(d,401,{error:"unauthorized"});let m=wd(c.headers.host);if(!rs.has(m))return O(d,403,{error:"host refused"});if(c.headers.origin&&c.headers.origin!==l)return O(d,403,{error:"origin refused"});if(c.method==="GET"&&c.url==="/status"){let f=typeof e.readPolicy=="function"?e.readPolicy():e.policy,p=new Set(Nn),w=Array.isArray(f?.surfaces)?f.surfaces.filter(g=>typeof g=="string"&&p.has(g)):[];return O(d,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:w,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(c.method==="POST"&&c.url==="/disarm")return await e.disarm(),r.clear(),n.clear(),O(d,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(c.method))return O(d,405,{error:"request refused"});if(c.method==="POST"&&String(c.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return O(d,415,{error:"request refused"});if(c.method==="GET"&&c.url==="/pending"){let f=[...n.values()].map(i);return O(d,200,{ok:!0,armed:e.isArmed?.()===!0,count:f.length,items:f})}if(c.method==="GET"&&String(c.url||"").startsWith("/execute/status?")){if(!e.executionOutbox)return O(d,503,{error:"execution outbox unavailable"});let f=new URL(String(c.url),l).searchParams.get("attemptKey"),p=await e.executionOutbox.inspect(f);return p?O(d,200,{ok:!0,attempt:p}):O(d,404,{error:"execution attempt not found"})}if(c.method==="POST"&&c.url==="/pending"){if(e.autonomous===!0)return O(d,403,{error:"autonomous signer does not queue human approvals"});let p=(await Nt(c)).artifact;if(!p||typeof p!="object")return O(d,400,{error:"artifact required"});let w=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(w?.confirmationMode!=="exact-human")return O(d,403,{error:"exact-human policy required"});let g=typeof e.nowMs=="function"?e.nowMs():Date.now();if(p?.surface==="cex"){if(typeof e.inspectCex!="function")return O(d,403,{error:"cex execution unavailable"});e.inspectCex(p,w,g)}else if(p?.version===1&&p?.surface)Qt(p,w,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:b,...x}=p||{};Nr(x,w,{nowMs:g})}let h=G(p),y=p?.surface==="cex"?Object.freeze(structuredClone(p)):p;return n.set(h,{artifact:y,digest:h,createdAtMs:g}),o("queued",{digest:h,createdAtMs:g}),O(d,200,{ok:!0,...i(n.get(h))})}if(c.method==="POST"&&c.url==="/ack"){if(e.autonomous===!0)return O(d,403,{error:"autonomous signer does not accept messaging acks"});let f=await Nt(c),p=s(f.digest||f.id);if(p.length===0)return O(d,404,{error:"no pending artifact"});if(p.length>1)return O(d,409,{error:"ambiguous digest; pass more hex"});let w=p[0];if((typeof e.readPolicy=="function"?e.readPolicy():e.policy)?.confirmationMode!=="exact-human")return O(d,403,{error:"exact-human policy required"});if(e.isArmed?.()!==!0)return O(d,403,{error:"signer is disarmed"});let h=e.verifyOwnerProof||e.verifyCexOwnerProof;if(typeof h!="function"||h(f.ownerProof,{digest:w.digest})!==!0)return O(d,403,{error:"exact owner Allow proof required"});if(w.artifact?.surface==="cex"){if(typeof e.cexExecute!="function")return O(d,403,{error:"cex execution unavailable"});n.delete(w.digest),o("approved",{digest:w.digest});let x;try{x=await e.cexExecute(w.artifact)}catch(A){throw o("failed",{digest:w.digest,reason:String(A?.message||A)}),A}return o("executed",{digest:w.digest,owner:w.artifact?.owner??w.artifact?.from,result:x}),O(d,200,{ok:!0,executed:!0,digest:w.digest,id:w.digest.slice(0,8),result:x})}n.delete(w.digest);let y=r.issue({artifact:w.artifact,owner:w.artifact?.owner??w.artifact?.from,ttlMs:f.ttlMs});o("approved",{digest:w.digest});let b;try{b=await Mn(w.artifact,y,{...e,confirmations:r})}catch(x){throw o("failed",{digest:w.digest,reason:String(x?.message||x)}),x}return o("executed",{digest:w.digest,owner:w.artifact?.owner??w.artifact?.from,result:b}),O(d,200,{ok:!0,executed:!0,confirmationNonce:y,digest:w.digest,id:w.digest.slice(0,8),result:b})}if(c.method==="POST"&&c.url==="/deny"){let f=await Nt(c),p=s(f.digest||f.id);return p.length===0?O(d,404,{error:"no pending artifact"}):p.length>1?O(d,409,{error:"ambiguous digest; pass more hex"}):(n.delete(p[0].digest),o("denied",{digest:p[0].digest}),O(d,200,{ok:!0,denied:!0,id:p[0].digest.slice(0,8)}))}if(c.method==="POST"&&c.url==="/confirm"){if(e.autonomous===!0)return O(d,403,{error:"autonomous signer does not issue human confirmation nonces"});let f=await Nt(c);if(f.artifact?.surface==="cex")return O(d,403,{error:"cex requires pending owner ack"});let p=G(f.artifact),w=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(w?.confirmationMode!=="exact-human")return O(d,403,{error:"exact-human policy required"});let g=typeof e.nowMs=="function"?e.nowMs():Date.now();if(f.artifact?.version===1&&f.artifact?.surface)Qt(f.artifact,w,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:h,...y}=f.artifact||{};Nr(y,w,{nowMs:g})}return typeof e.confirmArtifact!="function"?O(d,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(f.artifact,p,w)!==!0?O(d,400,{error:"exact human confirmation refused"}):O(d,200,{confirmationNonce:r.issue({artifact:f.artifact,owner:f.artifact?.owner??f.artifact?.from,ttlMs:f.ttlMs,binding:ns(f)})})}if(c.method==="POST"&&c.url==="/execute/reconcile"){let f=await Nt(c);if(!e.executionOutbox||typeof e.observeExecutionTransaction!="function")return O(d,503,{error:"execution reconciliation unavailable"});let p=await e.executionOutbox.reconcile({attemptKey:f.attemptKey,observeTransaction:e.observeExecutionTransaction,commitLedger:e.commitLedger,settleFailedLedger:e.settleFailedLedger});return O(d,200,{ok:!0,attempt:p})}if(c.method==="POST"&&c.url==="/execute"){let f=await Nt(c);if(f.artifact?.surface==="cex")return O(d,403,{error:"cex requires pending owner ack"});let p=typeof e.executeArtifact=="function"?e.executeArtifact:Mn;if(f.idempotencyKey!==void 0){if(!hd(f.artifact?.surface))return O(d,422,{error:"surface does not support durable Team execution reconciliation"});if(!e.executionOutbox)return O(d,503,{error:"execution outbox required for idempotent execution"});let g=await e.executionOutbox.begin({attemptKey:f.idempotencyKey,artifact:f.artifact,tenantId:f.tenantId,runId:f.runId,handoffHash:f.handoffHash,legIndex:f.legIndex,legCount:f.legCount});if(g.state==="recovery-required")return O(d,409,{error:"execution recovery-required; automatic replay refused",transactions:g.transactions||[]});if(g.state==="failed")return O(d,409,{error:"execution has a canonical failed receipt",receipts:g.receipts||[]});if(g.state==="completed")return n.delete(G(f.artifact)),O(d,200,g.result);let h=await e.executionOutbox.acquireExecutor({attemptKey:f.idempotencyKey}),y={recordSigned:b=>e.executionOutbox.recordSigned({attemptKey:f.idempotencyKey,leaseId:h,...b}),recordBroadcastAuthorized:b=>e.executionOutbox.recordBroadcastAuthorized({attemptKey:f.idempotencyKey,leaseId:h,...b}),recordCanonicalReceipt:b=>e.executionOutbox.recordCanonicalReceipt({attemptKey:f.idempotencyKey,leaseId:h,...b})};try{let b={...e,confirmations:r,confirmationBinding:ns(f),executionAttempt:y,reserveLedger:(A,k)=>e.reserveLedger(A,k,{retryReleasedTradeId:g.retryReleasedTradeId})},x=await p(f.artifact,f.confirmationNonce,b);return await e.executionOutbox.complete({attemptKey:f.idempotencyKey,leaseId:h,result:x}),n.delete(G(f.artifact)),O(d,200,x)}catch(b){throw await e.executionOutbox.failPreSubmission({attemptKey:f.idempotencyKey,leaseId:h,error:b}),b}finally{await e.executionOutbox.releaseExecutor({attemptKey:f.idempotencyKey,leaseId:h})}}let w=await p(f.artifact,f.confirmationNonce,{...e,confirmations:r});return n.delete(G(f.artifact)),O(d,200,w)}return O(d,404,{error:"not found"})}catch(u){e.onError?.(String(u?.message||u));let m=String(c.url||"");return m==="/pending"||m==="/ack"||m==="/deny"?O(d,400,{error:String(u?.message||"request refused").slice(0,300)}):O(d,400,{error:"request refused"})}})}import{closeSync as Cr,constants as Je,fchmodSync as ss,fsyncSync as Hn,lstatSync as ps,mkdirSync as Td,openSync as zn,readFileSync as ms,renameSync as Nd,rmSync as as,writeFileSync as cs}from"node:fs";import{randomBytes as Un}from"node:crypto";import{dirname as Cd,resolve as _d}from"node:path";import{wordlists as gd}from"ethers";var yd=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),bd=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Ed=new Set([12,15,18,21,24]);function xd(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Ed.has(t.length)&&t.every(r=>gd.en.getWordIndex(r)>=0)}var Sd=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,Ad=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,vd=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function Id(e){let t=is(e);return vd.has(t)||Ad.test(t)}var tr=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function is(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function kd(e){let t=is(e);return[...yd].some(r=>t.includes(r))}function Od(e,t,r){if(typeof t=="string"){if(bd.some(n=>n.test(t))||xd(t))throw new tr(r);if(Sd.test(t)&&!Id(e))throw new tr(r)}}function qn(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return Od(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((o,i)=>qn(o,`${t}[${i}]`,r));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${t}`);let n={};for(let o of Object.keys(e).sort()){let i=`${t}.${o}`;if(kd(o))throw new tr(i);e[o]!==void 0&&(n[o]=qn(e[o],i,o))}return n}function Ct(e){return qn(e)}var ws=2,ls=Je.O_NOFOLLOW??0;function he(e){return e==null?e:structuredClone(e)}function us(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function hs(e,t,r=!1){let n=r?!e.isDirectory():!e.isFile(),o=typeof process.getuid=="function"&&e.uid!==process.getuid();if(e.isSymbolicLink()||n||o||(e.mode&18)!==0)throw new Error(`${t} must be owner-controlled`)}function ds(e){Td(e,{recursive:!0,mode:448}),hs(ps(e),"execution outbox directory",!0)}function Rd(){return{version:ws,attempts:{}}}function gs(e){if(!e||e.version!==ws||!e.attempts||typeof e.attempts!="object"||Array.isArray(e.attempts))throw new Error("execution outbox is invalid");return Ct(e),he(e)}function fs(e){try{let t=ps(e);if(hs(t,"execution outbox file"),t.size>16*1024*1024)throw new Error("execution outbox is too large");return gs(JSON.parse(ms(e,"utf8")))}catch(t){if(t?.code==="ENOENT")return Rd();throw t}}function Ld(e){let t=String(e?.attemptKey||"");if(!/^sha256:[0-9a-f]{64}$/.test(t))throw new TypeError("execution attemptKey must be a sha256 digest");let r=String(e?.tenantId||"").trim(),n=String(e?.runId||"").trim(),o=String(e?.handoffHash||""),i=e?.legIndex,s=e?.legCount;if(!r||!n||!/^[0-9a-f]{64}$/.test(o))throw new TypeError("execution attempt identity is incomplete");if(!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(s)||s<1||i>=s)throw new TypeError("execution attempt leg identity is invalid");return{attemptKey:t,tenantId:r,runId:n,handoffHash:o,legIndex:i,legCount:s}}function $d(e){let t=e?.txIndex,r=e?.txCount,n=String(e?.surface||"").trim(),o=String(e?.signedTransactionId||"").trim();if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(r)||r<1||t>=r)throw new TypeError("execution transaction identity is invalid");if(!n||!o)throw new TypeError("execution signed transaction identity is required");if(n==="hl"){if(!/^0x[0-9a-f]{40}$/i.test(String(e.owner))||e.cloid!=null&&!/^0x[0-9a-f]{32}$/i.test(String(e.cloid)))throw new TypeError("execution HL owner/cloid identity is invalid");return{txIndex:t,txCount:r,surface:n,signedTransactionId:o,owner:e.owner,cloid:e.cloid??null,hlTestnet:e.hlTestnet===!0}}return{txIndex:t,txCount:r,surface:n,signedTransactionId:o}}function Oe(e,t){let r=e.attempts[String(t||"")];if(!r)throw new Error("execution attempt is unknown");return r}function _t(e,t){let r=e.executorLeaseId||e.recoveryLeaseId;if(!r)throw new Error("active execution attempt lease required");if(r!==t)throw new Error("execution attempt lease conflict")}function ys(e){if(!Number.isSafeInteger(e)||e<1)return null;try{let t=ms(`/proc/${e}/stat`,"utf8");return t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[19]||null}catch{return null}}function Pd(e){let t=Number(e?.pid),r=String(e?.startToken||"");if(!Number.isSafeInteger(t)||t<1||!r)return!0;if(r==="pid-only")try{return process.kill(t,0),!0}catch(o){return o?.code!=="ESRCH"}let n=ys(t);return n===null?!1:n===r}function Bd(e){return e.transactions.length>0&&e.transactions.length===e.transactionCount&&e.transactions.every(t=>t?.state==="confirmed"||t?.state==="failed")}function Dd(e,t){Bd(e)&&(e.state=e.transactions.some(r=>r.state==="failed")?"failed":"receipts-confirmed",e.receiptsRecordedAtMs=t())}function bs({path:e,now:t=Date.now,leaseOwner:r,isLeaseOwnerAlive:n=Pd}={}){if(!e)throw new TypeError("execution outbox path is required");if(typeof n!="function")throw new TypeError("execution lease liveness checker is required");let o=r||{pid:process.pid,startToken:ys(process.pid)||"pid-only"};if(!Number.isSafeInteger(Number(o.pid))||!String(o.startToken||""))throw new Error("execution lease owner identity is unavailable");let i=_d(e),s=Cd(i),l=`${i}.lock`;function a(d){ds(s);let u,m=!1,f=`${i}.${process.pid}.${Un(8).toString("hex")}.tmp`,p;try{u=zn(l,Je.O_CREAT|Je.O_EXCL|Je.O_WRONLY|ls,384),m=!0,cs(u,`${process.pid}
8
+ `,"utf8"),Hn(u),ss(u,384);let w=fs(i),g=d(w),h=gs(w);p=zn(f,Je.O_CREAT|Je.O_EXCL|Je.O_WRONLY|ls,384),cs(p,`${JSON.stringify(h)}
9
+ `,"utf8"),Hn(p),ss(p,384),Cr(p),p=void 0,Nd(f,i);let y=zn(s,Je.O_RDONLY);try{Hn(y)}finally{Cr(y)}return he(g)}finally{p!==void 0&&Cr(p),as(f,{force:!0}),u!==void 0&&Cr(u),m&&as(l,{force:!0})}}let c={async begin(d){let u=Ld(d),m=G(d.artifact);return a(f=>{let p=f.attempts[u.attemptKey];if(p){if(p.artifactDigest!==m||p.tenantId!==u.tenantId||p.runId!==u.runId||p.handoffHash!==u.handoffHash||p.legIndex!==u.legIndex||p.legCount!==u.legCount)throw new Error("execution attempt conflict: identity or artifact changed");return p.state==="completed"?{state:"completed",result:he(p.result)}:p.state==="pre-sign-failed"?(p.state="reserved",p.retryCount=(p.retryCount||0)+1,p.reservedAtMs=t(),delete p.failure,{state:"started",retryReleasedTradeId:p.tradeId||null}):p.state==="failed"?{state:"failed",receipts:he(p.transactions.map(w=>w.receipt))}:{state:"recovery-required",transactions:he(p.transactions)}}return f.attempts[u.attemptKey]={...u,artifactDigest:m,tradeId:d.artifact?.tradeId?String(d.artifact.tradeId):null,surface:String(d.artifact?.surface||"evm"),action:d.artifact?.action?String(d.artifact.action):null,state:"reserved",transactions:[],transactionCount:null,retryCount:0,createdAtMs:t(),reservedAtMs:t()},{state:"started"}})},async acquireExecutor({attemptKey:d}){let u=Un(32).toString("hex");return a(m=>{let f=Oe(m,d);if(["completed","failed","partial"].includes(f.state))throw new Error("execution attempt is terminal");if(f.executorLeaseId||f.recoveryLeaseId)throw new Error("execution attempt already has an active lease");return f.executorLeaseId=u,f.executorLeaseAcquiredAtMs=t(),f.executorLeaseOwnerPid=Number(o.pid),f.executorLeaseOwnerStartToken=String(o.startToken),u})},async releaseExecutor({attemptKey:d,leaseId:u}){return a(m=>{let f=Oe(m,d);if(f.executorLeaseId&&f.executorLeaseId!==u)throw new Error("execution executor lease conflict");return f.executorLeaseId===u&&(delete f.executorLeaseId,delete f.executorLeaseAcquiredAtMs,delete f.executorLeaseOwnerPid,delete f.executorLeaseOwnerStartToken),{released:!0}})},async recordSigned(d){let u=$d(d);return a(m=>{let f=Oe(m,d.attemptKey);if(_t(f,d.leaseId),!["reserved","signed","broadcast-authorized"].includes(f.state))throw new Error("execution attempt cannot record signed identity in current state");if(f.transactionCount!=null&&f.transactionCount!==u.txCount)throw new Error("execution transaction count conflict");f.transactionCount=u.txCount;let p=f.transactions[u.txIndex];if(p&&(!us(p.signedTransactionId,u.signedTransactionId)||p.surface!==u.surface||u.surface==="hl"&&(p.owner!==u.owner||p.cloid!==u.cloid||p.hlTestnet!==u.hlTestnet)))throw new Error("execution signed transaction conflict");return f.transactions[u.txIndex]={...p||{},...u,state:p?.state||"signed",signedAtMs:p?.signedAtMs||t()},f.state="signed",f.transactions[u.txIndex]})},async recordBroadcastAuthorized({attemptKey:d,txIndex:u,leaseId:m}){return a(f=>{let p=Oe(f,d);_t(p,m);let w=p.transactions[u];if(!w||!["signed","broadcast-authorized"].includes(w.state))throw new Error("execution transaction must be durably signed before broadcast authorization");return w.state="broadcast-authorized",w.broadcastAuthorizedAtMs||=t(),p.state="broadcast-authorized",w})},async recordCanonicalReceipt({attemptKey:d,txIndex:u,receipt:m,leaseId:f}){return Ct(m),a(p=>{let w=Oe(p,d);_t(w,f);let g=w.transactions[u];if(!g||!["broadcast-authorized","confirmed","failed"].includes(g.state))throw new Error("execution transaction was not authorized for broadcast");let h=m?.transactionHash??m?.hash;if(!us(h,g.signedTransactionId))throw new Error("execution receipt transaction identity conflict");let y=m?.status===0||m?.status==="0x0",b=m?.status===1||m?.status==="0x1";if(!y&&!b)throw new Error("execution receipt is not canonical");if(g.receipt&&JSON.stringify(g.receipt)!==JSON.stringify(m))throw new Error("execution canonical receipt conflict");return g.receipt=he(m),g.state=y?"failed":"confirmed",g.receiptRecordedAtMs||=t(),Dd(w,t),g})},async failPreSubmission({attemptKey:d,error:u,leaseId:m}){return a(f=>{let p=Oe(f,d);return _t(p,m),p.transactions.some(w=>w?.signedTransactionId)?{state:"recovery-required"}:(p.state="pre-sign-failed",p.failure=String(u?.message||u||"pre-sign failure").slice(0,300),p.failedAtMs=t(),{state:p.state})})},async complete({attemptKey:d,result:u,leaseId:m}){return Ct(u),a(f=>{let p=Oe(f,d);if(_t(p,m),p.state==="completed"){if(JSON.stringify(p.result)!==JSON.stringify(u))throw new Error("execution terminal result conflict");return p}if(p.state!=="receipts-confirmed")throw new Error("execution cannot complete before every canonical receipt is durable");return p.state="completed",p.result=he(u),p.completedAtMs=t(),p})},async reconcile({attemptKey:d,observeTransaction:u,commitLedger:m,settleFailedLedger:f}){if(typeof u!="function")throw new TypeError("execution reconciliation observer is required");let p=Un(32).toString("hex"),w=a(g=>{let h=Oe(g,d);if(["completed","failed","partial"].includes(h.state)&&h.result)return{terminal:!0,attempt:h};if(h.executorLeaseId){let y={pid:h.executorLeaseOwnerPid,startToken:h.executorLeaseOwnerStartToken};if(!y.pid||!y.startToken||n(y))throw new Error("execution reconciliation refused while live executor lease is active");delete h.executorLeaseId,delete h.executorLeaseAcquiredAtMs,delete h.executorLeaseOwnerPid,delete h.executorLeaseOwnerStartToken,h.executorLeaseRecoveredAtMs=t()}if(h.recoveryLeaseId)throw new Error("execution recovery is already active");return h.recoveryLeaseId=p,h.recoveryLeaseAcquiredAtMs=t(),{terminal:!1}});if(w.terminal)return w.attempt;try{let g=await c.inspect(d);if(g.state==="reserved"&&g.transactions.length===0)return c.failPreSubmission({attemptKey:d,leaseId:p,error:"recovered before signing"});for(let R of g.transactions){if(!R||R.state==="confirmed"||R.state==="failed")continue;let $=await u(he(R),he(g));$&&await c.recordCanonicalReceipt({attemptKey:d,leaseId:p,txIndex:R.txIndex,receipt:$})}let h=await c.inspect(d),y=h.transactions.filter(Boolean);if(y.some(R=>R.state!=="confirmed"&&R.state!=="failed"))return h;let b=Number(h.transactionCount||y.length),x=y.filter(R=>R.state==="confirmed").length,A=y.filter(R=>R.state==="failed").length,k=Math.max(0,b-y.length);if(y.length===0)return h;let v=y.map(R=>({...he(R.receipt),transactionHash:R.receipt?.transactionHash??R.receipt?.hash,balanceDeltaVerified:!1,delta:{},reconciled:!0})),_=A>0?x>0?"partial":"failed":k>0?"partial":"success",C={status:_,receipts:v,confirmedCount:x,failedCount:A,unattemptedCount:k};_==="success"&&v.length===1&&(C.receipt=v[0]),(h.surface==="evm-bridge"||h.action==="bridge")&&(C.originStatus=_==="success"?"success":_,C.destinationStatus="unknown",C.destinationSuccess=!1,C.warning="Origin-chain receipts do not prove destination-chain settlement.");let z={tradeId:h.tradeId};if(!z.tradeId)throw new Error("execution reconciliation is missing ledger tradeId");let U=x>0?"committed":"failed-fee-settled";if(!h.ledgerDisposition){let R=x>0?m:f;if(typeof R!="function")throw new TypeError("execution reconciliation ledger settlement callback is required");await R(z)}return a(R=>{let $=Oe(R,d);return _t($,p),["completed","failed","partial"].includes($.state)&&$.result||($.ledgerDisposition=$.ledgerDisposition||U,$.state=_==="success"?"completed":_,$.result=he(C),$.completedAtMs=t()),$})}finally{a(g=>{let h=Oe(g,d);return h.recoveryLeaseId===p&&(delete h.recoveryLeaseId,delete h.recoveryLeaseAcquiredAtMs),null})}},async inspect(d){ds(s);let u=fs(i).attempts[String(d||"")];return u?he(u):null}};return Object.freeze(c)}import{createHash as jd}from"node:crypto";import{wordlists as Fd}from"ethers";var Lt="oracle.control-plane/1",je="0.28.26+control-plane.1",Rt=64*1024,xs=32,Md=32*1024,qd=2e3,Hd=512,zd=/^(?:0|[1-9][0-9]*)$/,Ud=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/,Wd=/^[a-f0-9]{64}$/,Vd=/(?:amount|quantity|value|notional|balance|price|fee|gas|slippage|bps|basispoints|limit|maximum|minimum|cap|allowance|decimals|confirmations|executions|sequence|count)(?:$|[A-Z_])/i,Jd=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,Kd=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Gd=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),Yd=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,Xd=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]),Zd=new Set([12,15,18,21,24]),S=class extends TypeError{constructor(t,r="CONTROL_PLANE_INVALID"){super(`control-plane: ${t}`),this.name="ControlPlaneValidationError",this.code=r}};function xe(e,t="value",{positive:r=!1}={}){if(typeof e!="string"||!zd.test(e))throw new S(`${t} must be a canonical integer string`);if(r&&e==="0")throw new S(`${t} must be a positive integer string`);return e}function V(e,t="id"){if(typeof e!="string"||!Ud.test(e))throw new S(`${t} must be a bounded explicit id`);return e}function Fe(e,t="timestamp"){if(typeof e!="string"||e.length>64)throw new S(`${t} must be an explicit ISO timestamp`);let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new S(`${t} must be a canonical ISO timestamp`);return e}function Te(e,t="hash",{nullable:r=!1}={}){if(r&&e===null)return e;if(typeof e!="string"||!Wd.test(e))throw new S(`${t} must be a lowercase sha256 hash`);return e}function Se(e,t,r,n="record"){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new S(`${n} must be a plain object`);let o=new Set(t);for(let i of Object.keys(e))if(!o.has(i))throw new S(`${n} has unexpected field ${i}`);for(let i of r)if(!Object.hasOwn(e,i))throw new S(`${n}.${i} is required`)}function Ne(e,t){return`${V(e,"tenantId")}\0${V(t,"workflowId")}`}function Jn(e,t,r){return`${Ne(e,t)}\0${V(r,"idempotencyKey")}`}function Es(e,t){return e==="quantities"||Vd.test(t)}function Ss(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Qd(e){let t=Ss(e);return[...Gd].some(r=>t.includes(r))}function ef(e){let t=Ss(e);return Xd.has(t)||Yd.test(t)}function tf(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Zd.has(t.length)&&t.every(r=>Fd.en.getWordIndex(r)>=0)}function rf(e,t,r){if(typeof t=="string"){if(Kd.some(n=>n.test(t))||tf(t))throw new S(`${r} contains secret or custody material`,"CONTROL_PLANE_SECRET");if(Jd.test(t)&&!ef(e))throw new S(`${r} contains secret or custody material`,"CONTROL_PLANE_SECRET")}}function nf(e){return[...new Set([...Object.getOwnPropertyNames(e),...Object.keys(e)])]}function Wn(e,t="record",r="",n=new WeakSet){if(!(e===null||typeof e=="boolean"||typeof e=="number")){if(typeof e=="string"){rf(r,e,t);return}if(!(typeof e=="bigint"||e===void 0)){if(typeof e=="function")throw new S(`${t} functions are not JSON-safe public data`,"CONTROL_PLANE_SECRET");if(typeof e!="object")throw new S(`${t} must contain JSON-safe plain objects only`,"CONTROL_PLANE_SECRET");if(n.has(e))throw new S(`${t} cyclic values are not JSON-safe`,"CONTROL_PLANE_SECRET");if(n.add(e),Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)throw new S(`${t} binary buffers and typed arrays are not JSON-safe public data`,"CONTROL_PLANE_SECRET");if(typeof e.toJSON=="function")throw new S(`${t} toJSON is not allowed on control-plane records`,"CONTROL_PLANE_SECRET");if(Array.isArray(e)){e.forEach((o,i)=>Wn(o,`${t}[${i}]`,r,n));return}if(Object.getPrototypeOf(e)!==Object.prototype)throw new S(`${t} must contain JSON-safe plain objects only`,"CONTROL_PLANE_SECRET");for(let o of nf(e)){let i=`${t}.${o}`;if(Qd(o))throw new S(`${i} contains secret or custody material`,"CONTROL_PLANE_SECRET");let s=Object.getOwnPropertyDescriptor(e,o);if(s&&(typeof s.get=="function"||typeof s.set=="function"))throw new S(`${i} getters are not JSON-safe public data`,"CONTROL_PLANE_SECRET");Wn(e[o],i,o,n)}}}}function Vn(e,t,r,n,o,i){if(o>xs)throw new S(`${t} exceeds depth limit`);if(e===null||typeof e=="boolean")return i.bytes+=e===null||e?4:5,e;if(typeof e=="string"){let a=Buffer.byteLength(e,"utf8");if(a>Md)throw new S(`${t} exceeds string size limit`);return Es(n,r)&&xe(e,t),i.bytes+=a+2,e}if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isSafeInteger(e))throw new S(`${t} must be a finite safe integer or an exact integer string`);if(Es(n,r))throw new S(`${t} financial quantity must be an exact integer string`);return i.bytes+=String(e).length,e}if(typeof e=="bigint")throw new S(`${t} bigint is not JSON-safe; use an exact integer string`);if(e===void 0)throw new S(`${t} undefined is not JSON-safe`);if(typeof e=="function")throw new S(`${t} functions are not JSON-safe public data`);if(Array.isArray(e)){if(e.length>qd)throw new S(`${t} exceeds array item limit`);i.bytes+=2;let a=e.map((c,d)=>Vn(c,`${t}[${d}]`,r,n,o+1,i));if(i.bytes>Rt)throw new S(`${t} exceeds size limit`);return a}if(Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)throw new S(`${t} binary buffers and typed arrays are not JSON-safe public data`);if(!e||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new S(`${t} must contain JSON-safe plain objects only`);if(typeof e.toJSON=="function")throw new S(`${t} toJSON is not allowed on control-plane records`);let s=Object.keys(e).sort();if(s.length>Hd)throw new S(`${t} exceeds object key limit`);let l={};i.bytes+=2;for(let a of s){let c=Object.getOwnPropertyDescriptor(e,a);if(c&&(typeof c.get=="function"||typeof c.set=="function"))throw new S(`${t}.${a} getters are not JSON-safe public data`);if(i.bytes+=Buffer.byteLength(a,"utf8")+3,l[a]=Vn(e[a],`${t}.${a}`,a,r,o+1,i),i.bytes>Rt)throw new S(`${t} exceeds size limit`)}return l}function Me(e,t="record"){try{Ct(e)}catch(i){throw new S(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}try{Wn(e,t)}catch(i){throw i instanceof S?i:new S(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}let n=Vn(e,t,"","",0,{bytes:0});if(Buffer.byteLength(_r(n),"utf8")>Rt)throw new S(`${t} exceeds size limit`);return n}function _r(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(_r).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${_r(e[t])}`).join(",")}}`}function it(e){return _r(Me(e))}function Rr(e){return jd("sha256").update(it(e),"utf8").digest("hex")}function se(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))se(t);Object.freeze(e)}return e}function rr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new S("record object required");let{recordHash:t,eventHash:r,...n}=e;return Rr(n)}function Kn(e,t){return Me({schemaVersion:Lt,buildVersion:je,recordType:e,execution:"prepare-only",custody:"none",...t})}function Gn(e,t){if(e.schemaVersion!==Lt)throw new S("schemaVersion mismatch");if(e.buildVersion!==je)throw new S("buildVersion mismatch");if(e.recordType!==t)throw new S(`recordType must be ${t}`);if(e.execution!=="prepare-only")throw new S("execution must be prepare-only");if(e.custody!=="none")throw new S("custody must be none")}var of=["schemaVersion","buildVersion","recordType","execution","custody"],eb=[...of,"recordHash"];var tb=Object.freeze({signed:new Set(["workflow.signed","legacy.signed"]),submitted:new Set(["workflow.submitted","legacy.broadcast"]),finalized:new Set(["workflow.finalized"]),reorged:new Set(["workflow.reorged"]),orphaned:new Set(["workflow.orphaned"]),compensating:new Set(["workflow.compensating"]),compensated:new Set(["workflow.compensated"])}),sf=new Set(["block","blockNumber","blockHash","inclusionBlock","inclusionBlockNumber","inclusionBlockHash","receipt","receiptHash","transactionIndex","logIndex","confirmations"]),af=/^(?:0x)?[a-f0-9]{64}$/,cf=/^(?:0x)[a-f0-9]{64}$/;function Lr(e,t=new WeakSet){if(!e||typeof e!="object"||t.has(e))return!1;if(t.add(e),Array.isArray(e))return e.some(r=>Lr(r,t));for(let[r,n]of Object.entries(e))if(sf.has(r)||Lr(n,t))return!0;return!1}function or(e,t,{min:r=1,max:n=4096}={}){if(typeof e!="string"||e.length<r||e.length>n)throw new S(`${t} must be an explicit bounded string`);return e}function vs(e,t){if(or(e,t,{min:66,max:66}),!cf.test(e))throw new S(`${t} must be a 0x-prefixed 32-byte hash`);return e}function nr(e,t){if(or(e,t,{min:64,max:66}),!af.test(e))throw new S(`${t} must be a 32-byte digest`);return e}function Is(e,t,{positive:r=!1}={}){return xe(e,t,{positive:r})}function lf(e,t){if(Lr(e))throw new S(`${t} signed proof must not require or carry inclusion block fields`);let r=e.artifactHash??e.signedArtifactHash??e.digest,n=e.signer??e.expectedSigner??e.from;nr(r,`${t}.artifactHash`),or(n,`${t}.signer`,{min:1,max:256})}function uf(e,t){if(Lr(e))throw new S(`${t} submitted proof must not require or carry inclusion block fields`);let r=e.transactionHash??e.txHash,n=e.endpoint??e.submissionEndpoint??e.provider;vs(r,`${t}.transactionHash`),or(n,`${t}.endpoint`,{min:1,max:4096})}function As(e,t,{requireReceiptStatus:r=!1}={}){let n=e.transactionHash??e.txHash,o=e.blockNumber,i=e.blockHash;vs(n,`${t}.transactionHash`),Is(o,`${t}.blockNumber`,{positive:!0}),nr(i,`${t}.blockHash`),e.receiptHash!=null&&nr(e.receiptHash,`${t}.receiptHash`),(r||e.receiptStatus!=null)&&or(e.receiptStatus,`${t}.receiptStatus`,{min:1,max:32})}function Yn(e,t,r){switch(e){case"workflow.signed":case"legacy.signed":lf(t,r);break;case"workflow.submitted":case"legacy.broadcast":uf(t,r);break;case"workflow.finalized":As(t,r,{requireReceiptStatus:!0}),t.confirmations!=null&&Is(t.confirmations,`${r}.confirmations`);break;case"workflow.reorged":case"workflow.orphaned":As(t,r),t.observedBlockHash!=null&&nr(t.observedBlockHash,`${r}.observedBlockHash`),t.replacementBlockHash!=null&&nr(t.replacementBlockHash,`${r}.replacementBlockHash`);break;default:break}}var df=Object.freeze(["draft","checked","approval","signed","submitted","finalized","reorged","orphaned","compensating","compensated","failed","cancelled"]),Ts=Object.freeze(["workflow.drafted","workflow.checked","workflow.approval_requested","workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated","workflow.failed","workflow.cancelled","workflow.annotated"]),Ns=new Set(Ts),ff=new Set(["workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated"]),Cs=new Set(["workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned"]),pf=new Set(["failed","cancelled","compensated"]),ks=["schemaVersion","buildVersion","recordType","execution","custody","tenantId","id","workflowId","sequence","previousEventHash","idempotencyKey","occurredAt","recordedAt","type","external","evidence","data","eventHash"],$r=["tenantId","id","workflowId","idempotencyKey","occurredAt","recordedAt","type","external","evidence","data"];function mf(e,t){return{status:e?.status,source:e?.source,reference:e?.reference,observedAt:e?.observedAt??t}}function _s(e,t="WorkflowEvent.evidence"){if(Se(e,["status","source","reference","observedAt"],["status","source","reference","observedAt"],t),!new Set(["known","verified","unknown"]).has(e.status))throw new S(`${t}.status is invalid`);if(e.status==="unknown")throw new S("UNKNOWN evidence fails closed");if(V(e.source,`${t}.source`),typeof e.reference!="string"||e.reference.length<1||e.reference.length>4096)throw new S(`${t}.reference must be an explicit bounded reference`);Fe(e.observedAt,`${t}.observedAt`)}function Rs(e){return ff.has(e)}function Xn(e={}){Se(e,$r,$r,"WorkflowEvent input");let t=Me({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:mf(e.evidence,e.recordedAt),data:e.data},"WorkflowEvent input");if(V(t.tenantId,"WorkflowEvent.tenantId"),V(t.id,"WorkflowEvent.id"),V(t.workflowId,"WorkflowEvent.workflowId"),V(t.idempotencyKey,"WorkflowEvent.idempotencyKey"),Fe(t.occurredAt,"WorkflowEvent.occurredAt"),Fe(t.recordedAt,"WorkflowEvent.recordedAt"),!Ns.has(t.type))throw new S(`unknown workflow event type ${String(t.type)}`);if(typeof t.external!="boolean")throw new S("WorkflowEvent.external must be boolean");if(_s(t.evidence),Rs(t.type)){if(t.external!==!0)throw new S(`${t.type} must be an explicitly external fact`);if(t.evidence.status!=="verified"||t.evidence.source!=="external")throw new S(`${t.type} requires verified external evidence; caller external:true is not proof`)}else if(t.external===!0)throw new S(`${t.type} is not an external fact; caller external:true is not proof`);return Me(t.data,"WorkflowEvent.data"),Cs.has(t.type)&&Yn(t.type,t.data,"WorkflowEvent.data"),se(t)}function Pr(e={}){let t=e.sequence,r=e.previousEventHash,n=Object.fromEntries($r.map(a=>[a,e[a]])),o=Object.keys(e).filter(a=>!$r.includes(a)&&a!=="sequence"&&a!=="previousEventHash");if(o.length)throw new S(`WorkflowEvent input has unexpected field ${o[0]}`);let i=Xn(n);if(xe(t,"WorkflowEvent.sequence",{positive:!0}),t==="1"){if(r!==null)throw new S("first WorkflowEvent previousEventHash must be null")}else Te(r,"WorkflowEvent.previousEventHash");let s=Kn("WorkflowEvent",{...i,sequence:t,previousEventHash:r}),l=se({...s,eventHash:rr(s)});return ir(l),l}function ir(e){if(Se(e,ks,ks,"WorkflowEvent"),Gn(e,"WorkflowEvent"),V(e.tenantId,"WorkflowEvent.tenantId"),V(e.id,"WorkflowEvent.id"),V(e.workflowId,"WorkflowEvent.workflowId"),V(e.idempotencyKey,"WorkflowEvent.idempotencyKey"),xe(e.sequence,"WorkflowEvent.sequence",{positive:!0}),e.sequence==="1"){if(e.previousEventHash!==null)throw new S("first WorkflowEvent previousEventHash must be null")}else Te(e.previousEventHash,"WorkflowEvent.previousEventHash");if(Fe(e.occurredAt,"WorkflowEvent.occurredAt"),Fe(e.recordedAt,"WorkflowEvent.recordedAt"),!Ns.has(e.type))throw new S(`unknown workflow event type ${String(e.type)}`);if(typeof e.external!="boolean")throw new S("WorkflowEvent.external must be boolean");if(_s(e.evidence),Rs(e.type)){if(e.external!==!0)throw new S(`${e.type} must be an explicitly external fact`);if(e.evidence.status!=="verified"||e.evidence.source!=="external")throw new S(`${e.type} requires verified external evidence; caller external:true is not proof`)}else if(e.external===!0)throw new S(`${e.type} is not an external fact; caller external:true is not proof`);if(Me(e.data,"WorkflowEvent.data"),Cs.has(e.type)&&Yn(e.type,e.data,"WorkflowEvent.data"),Te(e.eventHash,"WorkflowEvent.eventHash"),rr(e)!==e.eventHash)throw new S("WorkflowEvent hash mismatch");return!0}function ee(e,t){throw new S(`invalid workflow transition ${e??"NONE"} -> ${t.type}`)}function Br(e=[]){if(!Array.isArray(e)||e.length<1)throw new S("workflow replay requires at least one event");let t=null,r=null,n=null,o=null,i=!1,s=null,l=[];for(let a of e){if(ir(a),t===null&&(t=a.tenantId),r===null&&(r=a.workflowId),n===null&&(n=Ne(a.tenantId,a.workflowId)),a.tenantId!==t)throw new S("workflow replay cannot mix tenant ids");if(a.workflowId!==r)throw new S("workflow replay cannot mix workflow ids");if(Ne(a.tenantId,a.workflowId)!==n)throw new S("workflow replay cannot mix tenant-scoped streams");let c=String(BigInt(s?.sequence??"0")+1n);if(a.sequence!==c)throw new S(`workflow sequence gap at ${a.sequence}`);if(a.previousEventHash!==(s?.eventHash??null))throw new S(`workflow previous-event hash mismatch at ${a.sequence}`);if(s&&Date.parse(a.recordedAt)<Date.parse(s.recordedAt))throw new S(`workflow recordedAt is not monotonic at ${a.sequence}`);if(pf.has(o))throw new S(`workflow state ${o} is terminal`);switch(a.type){case"workflow.drafted":o!==null&&ee(o,a),o="draft";break;case"workflow.checked":if(o!=="draft"&&ee(o,a),a.evidence.status!=="verified"||a.data?.checksPassed!==!0)throw new S("workflow.checked requires verified evidence and checksPassed=true");o="checked";break;case"workflow.approval_requested":o!=="checked"&&ee(o,a),o="approval",i=!1;break;case"workflow.approval_granted":o!=="approval"&&ee(o,a),i=!0;break;case"workflow.signed":if(o!=="approval"&&ee(o,a),!i)throw new S("external approval must be granted before signed state");o="signed";break;case"workflow.submitted":o!=="signed"&&ee(o,a),o="submitted";break;case"workflow.finalized":o!=="submitted"&&ee(o,a),o="finalized";break;case"workflow.reorged":o!=="submitted"&&o!=="finalized"&&ee(o,a),o="reorged";break;case"workflow.orphaned":o!=="submitted"&&o!=="finalized"&&o!=="reorged"&&ee(o,a),o="orphaned";break;case"workflow.compensating":o!=="reorged"&&o!=="orphaned"&&ee(o,a),o="compensating";break;case"workflow.compensated":o!=="compensating"&&ee(o,a),o="compensated";break;case"workflow.failed":if(o==="finalized"||o==="compensated")throw new S("failed must not follow finalized");new Set(["draft","checked","approval","signed","submitted","reorged","orphaned","compensating"]).has(o)||ee(o,a),o="failed";break;case"workflow.cancelled":new Set(["draft","checked","approval","signed"]).has(o)||ee(o,a),o="cancelled";break;case"workflow.annotated":o===null&&ee(o,a);break;default:ee(o,a)}a.external&&l.push({id:a.id,type:a.type,eventHash:a.eventHash,occurredAt:a.occurredAt,evidence:a.evidence,data:a.data}),s=a}return se({schemaVersion:Lt,buildVersion:je,tenantId:t,workflowId:r,streamKey:n,state:o,approvalGranted:i,eventCount:String(e.length),headEventHash:s.eventHash,externalFacts:l,authority:"event-ledger",execution:"prepare-only",custody:"none"})}import{createHash as wf,randomUUID as Ps}from"node:crypto";import{chmodSync as Qn,closeSync as at,constants as ce,existsSync as st,fstatSync as hf,fsyncSync as Mr,lstatSync as gf,mkdirSync as yf,openSync as qr,readFileSync as jr,renameSync as bf,unlinkSync as Bs,writeSync as Ef}from"node:fs";import{dirname as Ds,resolve as xf}from"node:path";import{setTimeout as Sf}from"node:timers/promises";var eo="oracle.control-plane-ledger-checkpoint/1",to="oracle.control-plane-ledger-lock/1",ro=64*1024*1024,js=1e4,Fs=Rt,Ls=["schemaVersion","buildVersion","totalEvents","fileSize","ledgerHash","lastEventHash","workflowHeads","checkpointHash"],$s=["schemaVersion","token","pid","createdAt"],B=class extends Error{constructor(t,r="WORKFLOW_LEDGER_ERROR",n=null){super(`workflow-ledger: ${t}`),this.name="WorkflowLedgerError",this.code=r,this.detail=n}};function ct(e){if(typeof e!="string"||e.length<1||e.length>4096)throw new B("bounded path required","PATH_INVALID");let t=xf(e);return{ledger:t,checkpoint:`${t}.checkpoint`,lock:`${t}.lock`,directory:Ds(t)}}function Af(e){yf(e,{recursive:!0,mode:448})}function Fr(e,t){let r=gf(e);if(!r.isFile()||r.isSymbolicLink())throw new B(`${t} must be a regular non-symlink file`,"UNSAFE_FILE");if((r.mode&511)!==384)throw new B(`${t} permissions must be 0600`,"UNSAFE_PERMISSIONS");return r}function Hr(e){let t;try{t=qr(e,ce.O_RDONLY),Mr(t)}finally{t!==void 0&&at(t)}}function no(e,t){let r=0;for(;r<t.length;)r+=Ef(e,t,r,t.length-r)}function vf(e){let t=ce.O_WRONLY|ce.O_CREAT|ce.O_APPEND|(ce.O_NOFOLLOW||0),r=qr(e,t,384);if(!hf(r).isFile())throw at(r),new B("ledger target is not a regular file","UNSAFE_FILE");return r}function If(e){ir(e);let t=Pr({tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,sequence:e.sequence,previousEventHash:e.previousEventHash,idempotencyKey:e.idempotencyKey,occurredAt:e.occurredAt,recordedAt:e.recordedAt,type:e.type,external:e.external,evidence:e.evidence,data:e.data});if(t.eventHash!==e.eventHash)throw new S("WorkflowEvent hash mismatch");return t}function Zn(e){return Ne(e.tenantId,e.workflowId)}function kf(e){let t={};for(let r of e)t[Zn(r)]={tenantId:r.tenantId,workflowId:r.workflowId,sequence:r.sequence,eventHash:r.eventHash};return Object.fromEntries(Object.entries(t).sort(([r],[n])=>r.localeCompare(n)))}function Ms(e,t,r=null){let n=r??(st(e)?jr(e):Buffer.alloc(0));return Me({schemaVersion:eo,buildVersion:je,totalEvents:String(t.length),fileSize:String(n.length),ledgerHash:wf("sha256").update(n).digest("hex"),lastEventHash:t.at(-1)?.eventHash??null,workflowHeads:kf(t)},"workflow checkpoint")}function qs(e,t,r=null){let n=Ms(e,t,r);return se({...n,checkpointHash:Rr(n)})}function Of(e){if(Se(e,Ls,Ls,"workflow checkpoint"),e.schemaVersion!==eo)throw new B("checkpoint schema mismatch","CHECKPOINT_INVALID");if(e.buildVersion!==je)throw new B("checkpoint build mismatch","CHECKPOINT_INVALID");if(xe(e.totalEvents,"workflow checkpoint.totalEvents"),xe(e.fileSize,"workflow checkpoint.fileSize"),Te(e.ledgerHash,"workflow checkpoint.ledgerHash"),Te(e.lastEventHash,"workflow checkpoint.lastEventHash",{nullable:!0}),!e.workflowHeads||typeof e.workflowHeads!="object"||Array.isArray(e.workflowHeads))throw new B("checkpoint workflowHeads invalid","CHECKPOINT_INVALID");for(let[n,o]of Object.entries(e.workflowHeads)){if(Se(o,["tenantId","workflowId","sequence","eventHash"],["tenantId","workflowId","sequence","eventHash"],`workflow checkpoint.${n}`),V(o.tenantId,`workflow checkpoint.${n}.tenantId`),V(o.workflowId,`workflow checkpoint.${n}.workflowId`),Ne(o.tenantId,o.workflowId)!==n)throw new B("checkpoint workflowHeads stream key mismatch","CHECKPOINT_INVALID");xe(o.sequence,`workflow checkpoint.${n}.sequence`,{positive:!0}),Te(o.eventHash,`workflow checkpoint.${n}.eventHash`)}Te(e.checkpointHash,"workflow checkpoint.checkpointHash");let{checkpointHash:t,...r}=e;if(Rr(r)!==t)throw new B("checkpoint hash mismatch","CHECKPOINT_INVALID");if(e.totalEvents==="0"!=(e.lastEventHash===null))throw new B("checkpoint event count/head mismatch","CHECKPOINT_INVALID");return!0}function Tf(e,t,r=null,n=null){let{checkpoint:o,directory:i}=ct(e),s=n??qs(e,t,r),l=`${o}.${Ps()}.tmp`,a;try{a=qr(l,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),no(a,Buffer.from(`${JSON.stringify(s)}
10
+ `,"utf8")),Mr(a),at(a),a=void 0,bf(l,o),Qn(o,384),Hr(i)}catch(c){a!==void 0&&at(a);try{st(l)&&Bs(l)}catch{}throw c}return s}function Nf(e,t){let r=BigInt(e.totalEvents),n=BigInt(t.totalEvents);if(r>n)return{ok:!1,reason:"checkpoint-ahead",recoverable:!1};if(r<n)return{ok:!1,reason:"checkpoint-behind",recoverable:!0};let o=BigInt(e.fileSize),i=BigInt(t.fileSize);return o>i?{ok:!1,reason:"checkpoint-ahead",recoverable:!1}:o<i?{ok:!1,reason:"checkpoint-behind",recoverable:!0}:e.ledgerHash!==t.ledgerHash?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:e.lastEventHash!==t.lastEventHash?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:it(e.workflowHeads)!==it(t.workflowHeads)?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:{ok:!0}}function Cf({path:e,maxBytes:t=ro,checkCheckpoint:r=!0}={}){let n=ct(e);if(!Number.isSafeInteger(t)||t<1||t>1024*1024*1024)return{ok:!1,reason:"size-limit",count:0,workflows:0,events:[],paths:n};try{if(!st(n.ledger))return r&&st(n.checkpoint)?{ok:!1,reason:"checkpoint-ahead",recoverable:!1,count:0,workflows:0,events:[],paths:n}:{ok:!0,count:0,workflows:0,events:[],heads:new Map,paths:n,empty:!0};if(Fr(n.ledger,"ledger").size>t)return{ok:!1,reason:"size-limit",count:0,workflows:0,events:[],paths:n};let i=jr(n.ledger);if(i.length>0&&i.at(-1)!==10)return{ok:!1,reason:"truncated-line",count:0,workflows:0,events:[],paths:n};let s=i.toString("utf8"),l=i.length===0?[]:s.slice(0,-1).split(`
11
+ `),a=[],c=new Map,d=new Set,u=new Set;for(let f=0;f<l.length;f+=1){let p=l[f];if(Buffer.byteLength(p,"utf8")>Fs)return{ok:!1,reason:"event-size-limit",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};let w;try{w=JSON.parse(p)}catch{return{ok:!1,reason:"malformed-json",line:f+1,count:a.length,workflows:c.size,events:a,paths:n}}let g;try{g=If(w)}catch(A){return{ok:!1,reason:"event-invalid",line:f+1,detail:String(A?.message||A),count:a.length,workflows:c.size,events:a,paths:n}}if(d.has(g.id))return{ok:!1,reason:"duplicate-event-id",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};let h=Zn(g),y=Jn(g.tenantId,g.workflowId,g.idempotencyKey);if(u.has(y))return{ok:!1,reason:"duplicate-idempotency-key",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};let b=c.get(h)??null,x=String(BigInt(b?.sequence??"0")+1n);if(g.sequence!==x)return{ok:!1,reason:"sequence-gap",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};if(g.previousEventHash!==(b?.eventHash??null))return{ok:!1,reason:"previous-event-hash-mismatch",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};if(b&&Date.parse(g.recordedAt)<Date.parse(b.recordedAt))return{ok:!1,reason:"recorded-at-regression",line:f+1,count:a.length,workflows:c.size,events:a,paths:n};d.add(g.id),u.add(y),c.set(h,g),a.push(g)}let m=new Map;for(let f of a){let p=Zn(f);m.has(p)||m.set(p,[]),m.get(p).push(f)}for(let[f,p]of m)try{Br(p)}catch(w){return{ok:!1,reason:"workflow-invalid",streamKey:f,detail:String(w?.message||w),count:a.length,workflows:c.size,events:a,heads:c,paths:n}}if(r){if(!st(n.checkpoint))return a.length===0?{ok:!0,count:0,workflows:0,events:a,heads:c,paths:n,empty:!0}:{ok:!1,reason:"checkpoint-missing",recoverable:!0,count:a.length,workflows:c.size,events:a,heads:c,paths:n};let f;try{Fr(n.checkpoint,"checkpoint");let g=jr(n.checkpoint,"utf8");if(!g.endsWith(`
12
+ `))throw new B("checkpoint truncated","CHECKPOINT_INVALID");f=JSON.parse(g),Of(f)}catch(g){return{ok:!1,reason:"checkpoint-invalid",recoverable:!1,detail:String(g?.message||g),count:a.length,workflows:c.size,events:a,heads:c,paths:n}}let p=Ms(n.ledger,a,i),w=Nf(f,p);if(!w.ok)return{...w,count:a.length,workflows:c.size,events:a,heads:c,paths:n}}return{ok:!0,count:a.length,workflows:c.size,events:a,heads:c,paths:n,raw:i,lastEventHash:a.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 _f(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 se(t)}function Rf(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 Hs(e){let{lock:t}=ct(e);Fr(t,"lock");let r=JSON.parse(jr(t,"utf8"));if(Se(r,$s,$s,"workflow ledger lock"),r.schemaVersion!==to)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 Fe(r.createdAt,"workflow ledger lock.createdAt"),r}function zs({path:e}={}){let{lock:t}=ct(e);if(!st(t))return se({state:"unlocked",lock:null});try{let r=Hs(e);return se({state:Rf(r.pid),lock:r})}catch(r){return se({state:"invalid",lock:null,error:String(r?.message||r)})}}function Lf(e){let t=ct(e);Af(t.directory);let r={schemaVersion:to,token:Ps(),pid:process.pid,createdAt:new Date().toISOString()},n;try{return n=qr(t.lock,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),no(n,Buffer.from(`${JSON.stringify(r)}
13
+ `,"utf8")),Mr(n),at(n),n=void 0,Qn(t.lock,384),Hr(t.directory),r}catch(o){throw n!==void 0&&at(n),o}}async function $f(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 Lf(e)}catch(n){if(n?.code!=="EEXIST")throw n;if(Date.now()-r>=t){let o=zs({path:e});throw new B(`ledger busy (${o.state} lock); explicit token-bound recovery is required for stale locks`,"LEDGER_BUSY",o)}await Sf(10)}}function Dr(e,t){let r=Hs(e);if(r.token!==t||r.pid!==process.pid)throw new B("lock fencing token no longer owned","LOCK_FENCED");return!0}function Pf(e,t){let r=ct(e);Dr(e,t),Bs(r.lock),Hr(r.directory)}function Bf(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 oo(e={}){Se(e,["path","event","lockTimeoutMs","maxBytes"],["path","event"],"appendWorkflowEvent options");let t=ct(e.path).ledger,r=Xn(e.event),n=e.lockTimeoutMs??js,o=e.maxBytes??ro,i=await $f(t,n),s=null;try{Dr(t,i.token);let l=Cf({path:t,maxBytes:o});if(!l.ok)throw new B(`append refused until ledger recovery: ${l.reason}`,"LEDGER_CORRUPT",_f(l));let a=l.events.find(b=>b.tenantId===r.tenantId&&b.workflowId===r.workflowId&&b.idempotencyKey===r.idempotencyKey);if(a){if(it(Bf(a))!==it(r))throw new B("idempotency key reused with different payload","IDEMPOTENCY_CONFLICT");return se({event:a,duplicate:!0})}if(l.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=l.heads.get(c)??null,u=Pr({...r,sequence:String(BigInt(d?.sequence??"0")+1n),previousEventHash:d?.eventHash??null}),m=l.events.filter(b=>Ne(b.tenantId,b.workflowId)===c);Br([...m,u]);let f=Buffer.from(`${JSON.stringify(u)}
14
+ `,"utf8");if(f.length>Fs)throw new B("event exceeds size limit","EVENT_SIZE_LIMIT");let p=Buffer.concat([l.raw??Buffer.alloc(0),f]);if(p.length>o)throw new B("append would exceed ledger size limit","LEDGER_SIZE_LIMIT");let w=[...l.events,u],g=qs(t,w,p),h=st(t);h&&Fr(t,"ledger"),Dr(t,i.token);let y;try{y=vf(t),no(y,f),Mr(y)}finally{y!==void 0&&at(y)}return Qn(t,384),h||Hr(Ds(t)),Dr(t,i.token),Tf(t,w,p,g),se({event:u,duplicate:!1})}catch(l){throw s=l,l}finally{try{Pf(t,i.token)}catch(l){if(s===null)throw l}}}var pb=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),mb=Object.freeze(["read","simulate"]);var wb=1440*60;var vb=Object.freeze(["privkey","wif","xprv","seed"]);var Ib=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}]),kb=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);var io=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),Cb=Object.freeze(Object.fromEntries(io.map((e,t)=>[e,Object.freeze(t+1<io.length?[io[t+1]]:[])])));var Df=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 zf,randomBytes as Uf}from"node:crypto";var jf=Object.freeze(["owner","operator","agent","viewer"]),Ff=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),Mf=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),c0=Object.freeze(["owner"]),l0=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"}),u0=new Set(jf),d0=new Set(Ff),f0=new Set(Object.values(Mf));var qf=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;var Hf=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"])}),p0=Object.freeze(Object.fromEntries(Object.entries(Hf).map(([e,t])=>[e,Object.freeze([...t])]))),zr=class extends Error{constructor(t,r="invalid-context"){super(t),this.name="TenantContextError",this.code=r}};function Us(e,t){let r=String(e??"").trim();if(!qf.test(r))throw new zr(`${t} is invalid`);return r}function Ws(e,t){let r=Us(e,"tenantId"),n=Us(t,"workflowId");if(r.includes(":")||n.includes(":"))throw new zr("stream key parts must not contain ':'","invalid-stream-key");return`${r}:${n}`}var Xs=1,Zs=1,Wf=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),Vf=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),Qs=Object.freeze(["taskId","intentId","planId","runId","eventId"]);function Vs(e,t){return Ws(e,t)}var sr=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),Jf=new Set(Wf),Kf=new Set(Vf),Gf=new Set(Qs),Yf=/^[0-9a-f]{32}$/,Js=/^[0-9a-f]{16}$/;var Xf=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,95}$/,Zf=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Qf=/^[A-Za-z][A-Za-z0-9_.-]*$/,ep=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"]),tp=/(?:^|\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,rp=/(?:0x)?[0-9a-fA-F]{66,}/,np=/[A-Za-z0-9+/=_-]{96,}/,j=class extends Error{constructor(t,r="invalid-telemetry"){super(t),this.name="WorkflowTelemetryError",this.code=r}};function Ur(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Wr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Wr(t)}return e}function so(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(so).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${so(e[t])}`).join(",")}}`}function ea(e){return zf("sha256").update(so(e)).digest("hex")}function Ks(e,t,r){let n=r?r(e,t):Uf(e).toString("hex");return String(n??"").trim().toLowerCase()}function ta(e={}){if(e==null)return{};if(!Ur(e))throw new j("correlation must be a plain object");let t=Object.keys(e).filter(n=>!Gf.has(n));if(t.length)throw new j(`unknown correlation fields: ${t.sort().join(", ")}`);let r={};for(let n of Qs){if(e[n]==null)continue;let o=String(e[n]).trim();if(!Zf.test(o))throw new j(`${n} is invalid`);r[n]=o}return r}function ra(e){if(!Ur(e)||e.schemaVersion!==Xs)throw new j("trace context version is invalid","invalid-trace");if(!Yf.test(e.traceId||"")||!Js.test(e.spanId||"")||/^0+$/.test(e.traceId)||/^0+$/.test(e.spanId))throw new j("trace or span id is invalid","invalid-trace");if(e.parentSpanId!==null&&!Js.test(e.parentSpanId||""))throw new j("parent span id is invalid","invalid-trace");if(typeof e.sampled!="boolean")throw new j("sampled must be boolean","invalid-trace");return ta(e.correlation),e}function op({traceId:e,spanId:t,parentSpanId:r=null,sampled:n=!1,correlation:o={}}={},{idFactory:i}={}){let s=e==null?Ks(16,"trace",i):String(e).trim().toLowerCase(),l=t==null?Ks(8,"span",i):String(t).trim().toLowerCase(),a=r==null?null:String(r).trim().toLowerCase(),c=Wr({schemaVersion:Xs,traceId:s,spanId:l,parentSpanId:a,sampled:n===!0,correlation:ta(o)});return ra(c)}var na=op;var g0=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 Gs(e){let t=String(e).replace(/[^a-z0-9]/gi,"").toLowerCase();return ep.some(r=>t.includes(r))}function ip(e){return tp.test(e)||rp.test(e)||np.test(e)?{value:"[REDACTED]",redacted:!0,truncated:!1}:e.length>sr.maxStringLength?{value:`${e.slice(0,sr.maxStringLength-1)}\u2026`,redacted:!1,truncated:!0}:{value:e,redacted:!1,truncated:!1}}function oa(e){if(typeof e=="string")return ip(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,sr.maxArrayLength),r=[],n=!1,o=e.length>t.length;for(let i of t){if(!["string","boolean","number"].includes(typeof i))return null;let s=oa(i);if(!s)return null;r.push(s.value),n||=s.redacted,o||=s.truncated}return{value:r,redacted:n,truncated:o}}return null}function sp(e={}){if(!Ur(e))throw new j("telemetry attributes must be a plain object");let t={},r=0,n=0,o=0,i=Object.keys(e).sort();for(let s of i){if(Object.keys(t).length>=sr.maxAttributes){n+=1;continue}if(s.length>sr.maxKeyLength||!Qf.test(s)||Gs(s)){n+=1,Gs(s)&&(r+=1);continue}let l=oa(e[s]);if(!l){n+=1;continue}t[s]=l.value,l.redacted&&(r+=1),l.truncated&&(o+=1)}return Wr({attributes:t,redactedCount:r,droppedCount:n,truncatedCount:o})}function Ys(e,t){if(!Number.isSafeInteger(e)||e<0)throw new j(`${t} must be a non-negative integer milliseconds value`);return e}function ap(e){if(e==null)return null;let t=String(e).trim();if(!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(t))throw new j("outcomeCode is invalid");return t}function cp({streamKey:e,tenantId:t,workflowId:r,sourceEvent:n}){let o=e??n?.streamKey??null,i=t??n?.tenantId??null,s=r??n?.workflowId??null;if(o!=null){let l=String(o).trim();if(i!=null&&s!=null){let a=Vs(i,s);if(l!==a)throw new j("streamKey must equal tenantId:workflowId","invalid-stream-key");return a}if(!/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}:[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(l)||l.split(":").length!==2)throw new j("streamKey must be tenantId:workflowId","invalid-stream-key");return l}return i!=null&&s!=null?Vs(i,s):null}function lp({trace:e,name:t,kind:r,diagnosticOutcome:n=null,outcome:o=null,outcomeCode:i=null,startedAt:s,endedAt:l,attributes:a,authority:c,sourceEvent:d=null,streamKey:u=null,tenantId:m=null,workflowId:f=null}){ra(e);let p=String(t??"").trim();if(!Xf.test(p))throw new j("workflow telemetry name is invalid");if(!Kf.has(r))throw new j("workflow telemetry kind is invalid");let w=c==="ledger_projection"?o:n;if(!Jf.has(w))throw new j("workflow telemetry outcome is invalid");let g=Ys(s,"startedAt"),h=Ys(l,"endedAt");if(h<g)throw new j("endedAt must not be before startedAt");let y=sp(a),b=cp({streamKey:u,tenantId:m,workflowId:f,sourceEvent:d}),x={schemaVersion:Zs,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:ap(i),startedAt:g,endedAt:h,durationMs:h-g,attributes:{...y.attributes},attributePolicy:{redactedCount:y.redactedCount,droppedCount:y.droppedCount,truncatedCount:y.truncatedCount}};return Wr({...x,recordId:ea(x)})}function ao({trace:e,name:t,kind:r="workflow",outcome:n,outcomeCode:o=null,startedAt:i,endedAt:s,attributes:l={},tenantId:a=null,workflowId:c=null,streamKey:d=null}={}){return lp({trace:e,name:t,kind:r,diagnosticOutcome:n,outcomeCode:o,startedAt:i,endedAt:s,attributes:l,authority:"diagnostic",tenantId:a,workflowId:c,streamKey:d})}function co(e){if(!Ur(e)||!Object.isFrozen(e)||e.schemaVersion!==Zs||e.recordType!=="oracle.workflow.telemetry")return!1;let{recordId:t,...r}=e;return typeof t=="string"&&t===ea(r)}function lo({exporter:e=null}={}){if(e!=null&&typeof e!="function"&&typeof e?.export!="function")throw new j("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=co(r)?r:ao(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 up="ORACLE_LEDGER_DUAL_WRITE",ia=/^[a-f0-9]{64}$/,dp=/^0x[a-f0-9]{64}$/,fp=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"});function $t(e,t){return String(e??"").slice(0,t)}function sa(e=process.env){return String(e?.[up]??"")==="1"}function aa({path:e,tenantId:t="local-signer",nowMs:r=Date.now,onError:n=null,telemetry:o=null,append:i=oo}={}){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 s=typeof n=="function"?n:()=>{},l=new Map,a=Promise.resolve(),c=()=>new Date(r()).toISOString();function d(f,p,w){if(!(!o||typeof o.emit!="function"))try{let g=r(),h=ao({trace:f.trace,name:p,kind:"workflow",outcome:fp[p]??"succeeded",startedAt:g,endedAt:g,attributes:w,tenantId:t,workflowId:f.workflowId});a=a.then(()=>o.emit(h)).catch(y=>{s(`signer telemetry emit failed: ${$t(y?.message||y,200)}`)})}catch(g){s(`signer telemetry record failed: ${$t(g?.message||g,200)}`)}}function u(f,p,{external:w=!1,source:g="local-signer",reference:h=null,data:y={}}={}){let b=c(),x={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 a=a.then(()=>i({path:e,event:x})).catch(A=>{s(`workflow ledger dual-write failed for ${p}: ${$t(A?.message||A,200)}`)}),d(f,p,{digest:f.digest}),a}function m(f){let p=String(f??"").toLowerCase();return ia.test(p)?l.get(p)??null:null}return Object.freeze({queued({digest:f,createdAtMs:p}={}){let w=String(f??"").toLowerCase();if(!ia.test(w))return s("ledger observer: queued without a valid artifact digest"),a;let g=Number.isFinite(Number(p))?Number(p):r(),h={workflowId:`signer-${w}-${g}`,digest:w,trace:na()};return l.set(w,h),u(h,"workflow.drafted",{source:"local-signer-queue",reference:`artifact:${w}`,data:{intentSpecId:`${h.workflowId}:intent`}}),u(h,"workflow.checked",{source:"local-signer-policy",reference:`artifact:${w}`,data:{checksPassed:!0}}),u(h,"workflow.approval_requested",{source:"local-signer-queue",reference:`artifact:${w}`}),a},denied({digest:f}={}){let p=m(f);return p&&(l.delete(p.digest),u(p,"workflow.cancelled",{source:"owner-ack",reference:`deny:${p.digest}`})),a},approved({digest:f,channel:p="owner-ack"}={}){let w=m(f);return w&&u(w,"workflow.approval_granted",{external:!0,source:p,reference:`ack:${w.digest}`}),a},executed({digest:f,owner:p=null,result:w=null}={}){let g=m(f);if(!g)return a;l.delete(g.digest),u(g,"workflow.signed",{external:!0,reference:`signed:${g.digest}`,data:{artifactHash:g.digest,signer:$t(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&&dp.test(y)?u(g,"workflow.submitted",{external:!0,reference:`submitted:${g.digest}`,data:{transactionHash:y,endpoint:"local-signer-broadcast"}}):h&&u(g,"workflow.annotated",{reference:`submission:${g.digest}`,data:{note:"non-evm-submission-reference",reference:$t(h,512)}}),a},failed({digest:f,reason:p=""}={}){let w=m(f);return w&&(l.delete(w.digest),u(w,"workflow.failed",{reference:`failed:${w.digest}`,data:{reason:$t(p,300)}})),a},flush(){return a}})}import{appendFileSync as pp,existsSync as mp,mkdirSync as wp,renameSync as hp,statSync as gp}from"node:fs";import{dirname as yp}from"node:path";var bp="ORACLE_TELEMETRY_JSONL",Ep=32*1024*1024,ca=4096;function xp({path:e,maxBytes:t=Ep}={}){if(typeof e!="string"||e.trim().length===0)throw new j("jsonl exporter requires an explicit file path","invalid-exporter-path");let r=Number(t);if(!Number.isFinite(r)||r<ca)throw new j(`jsonl exporter maxBytes must be >= ${ca}`,"invalid-exporter-cap");let n=e;return Object.freeze({path:n,maxBytes:r,export(o){if(!co(o))throw new j("jsonl exporter accepts only sealed workflow telemetry records","invalid-record");let i=`${JSON.stringify(o)}
15
+ `;wp(yp(n),{recursive:!0,mode:448}),mp(n)&&gp(n).size+Buffer.byteLength(i)>r&&hp(n,`${n}.1`),pp(n,i,{mode:384})}})}function la(e=process.env,{maxBytes:t}={}){let r=String(e?.[bp]??"").trim();return r?lo({exporter:xp({path:r,...t===void 0?{}:{maxBytes:t}})}):lo({})}import{createCipheriv as O0,createDecipheriv as Sp,randomBytes as Ap,scryptSync as vp}from"node:crypto";import D from"node:fs";import Pt from"node:path";var Ip="ORACLE-LOCAL-VAULT",kp=1,Jr=Object.freeze({N:1<<17,r:8,p:1}),Op=256*1024*1024,Tp=16*1024;function Vr(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 Np(e,t,r=Jr){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 vp(n,t,32,{...r,maxmem:Op})}function ua(e,t){if(e?.magic!==Ip||e?.version!==kp)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!==Jr.N||e.kdf.r!==Jr.r||e.kdf.p!==Jr.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(u=>!["address","addresses","kind","createdAt"].includes(u))||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(u=>!r.includes(u)))throw new Error("local-vault: unexpected vault field");let n=Vr(e.kdf.salt,32,"salt"),o=Vr(e.cipher.iv,12,"iv"),i=Vr(e.tag,16,"tag"),s=Vr(e.ciphertext,1,"ciphertext",{max:Tp}),{ciphertext:l,tag:a,...c}=e,d=Np(t,n);try{let u=Sp("aes-256-gcm",d,o);return u.setAAD(Buffer.from(JSON.stringify(c))),u.setAuthTag(i),Buffer.concat([u.update(s),u.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function Cp(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 _p(e){let t=Pt.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 L(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(Cp(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 da(e){return JSON.parse(L(e))}function Ae(e,t){D.mkdirSync(Pt.dirname(e),{recursive:!0,mode:448}),_p(e);let r=Pt.join(Pt.dirname(e),`.${Pt.basename(e)}.${process.pid}.${Ap(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(Pt.dirname(e),"r");try{D.fsyncSync(o)}finally{D.closeSync(o)}}catch(n){try{D.unlinkSync(r)}catch{}throw n}}var fa=/^0x[0-9a-fA-F]+$/,Rp=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 Lp(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 $p(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=Rp[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=Lp(r),i=o||n.endpoints,s=o&&n.mode==="public-only"?"mempool-private":n.mode,l=i.length>0&&s!=="public-only";if(t&&!l)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:s,endpoints:[...i],source:o?"env":"builtin",hasPrivate:l}}async function pa(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!fa.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let s=$p(t,{requirePrivate:r}),l=o||globalThis.fetch;if(!l)throw new Error("submitPrivate: no fetch implementation available");let a=[];for(let c of s.endpoints){let d=new AbortController,u=setTimeout(()=>d.abort(),i);try{let m=await l(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&&fa.test(p.result))return{hash:p.result,endpoint:c,mode:s.mode,chainId:s.chainId,fellBack:!1};a.push({endpoint:c,error:p&&p.error&&p.error.message||`http ${m.status}`})}catch(m){a.push({endpoint:c,error:String(m&&m.message||m).slice(0,160)})}finally{clearTimeout(u)}}if(n&&!r)return{fellBack:!0,mode:s.mode,chainId:s.chainId,attempts:a};throw new Error(`submitPrivate: all private endpoints failed for chain ${s.chainId} (${a.map(c=>`${c.endpoint}:${c.error}`).join("; ")||"none configured"})`)}import{createHmac as Bp,randomBytes as Dp,timingSafeEqual as jp}from"node:crypto";import te from"node:fs";import lt from"node:path";import{homedir as uo}from"node:os";import{join as fo}from"node:path";var ma=process.env.ORACLE_PUBLIC_DESKTOP==="1",Pp=ma?process.env.ORACLE_CONFIG_DIR||fo(uo(),".config","oracle"):fo(uo(),".config","oracle"),$0=ma?Pp:fo(uo(),".config","mad-desk");var F0="0".repeat(64),M0=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 Kr(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Kr).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Kr(e[r])).join(",")+"}"}var q0=Promise.resolve();function ut(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=s=>{try{return te.realpathSync(s)}catch{return lt.resolve(s)}},n=r(lt.dirname(lt.resolve(e))),o=r(lt.dirname(lt.resolve(t))),i=(s,l)=>l===s||l.startsWith(s+lt.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var Fp=864e5,le=(e,t)=>Bp("sha256",t).update(Kr(e)).digest("hex"),Ce=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&jp(r,n)},Mp=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function qp(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(e.integrity.mac,le(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Yr(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=L(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,le(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 Hp(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 l=Yr(e,r);i=l.present&&l.ledgerInitialized===!0}catch{i=!1}let s={policySequence:Number(t),policyMac:String(n)};i&&(s.ledgerInitialized=!0),Ae(e,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:le(s,r)}})+`
16
+ `)}function zp(e,t){let r=Yr(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 Hp(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function Xr(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=L(t),o;try{o=JSON.parse(L(e))}catch(a){throw new Error(`policy: cannot read sealed policy: ${a?.message||a}`)}let i=qp(o,n);ut(r,e);let s=Yr(r,n),l=Number(i.policySequence||0);if(!s.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(l!==s.sequence)throw new Error("policy: rolled back to a superseded policy");if(s.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!Ce(s.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Dt(e,t,r,n,o){let i=`${e}.continuity`,s;try{let l=JSON.parse(L(e));if(l?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(l?.integrity?.mac,le(l.ledger,t)))throw new Error("integrity verification failed");if(s=l.ledger,!Number.isFinite(s?.windowStartMs)||!Array.isArray(s?.entries)||s.sequence!==void 0&&(!Number.isSafeInteger(s.sequence)||s.sequence<0))throw new Error("invalid ledger")}catch(l){if(l?.code==="ENOENT"){if(te.existsSync(i)||te.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let a=Yr(o,t);if(a.present&&a.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:r,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${l?.message||l}`)}try{let l=JSON.parse(L(i));if(l?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(l?.integrity?.mac,le(l.marker,t)))throw new Error("continuity verification failed");if(l.marker?.version===2&&(l.marker.sequence!==s.sequence||!Ce(l.marker.ledgerMac,le(s,t))))throw new Error("continuity rollback detected");if(l.marker?.version!==2&&s.sequence!==void 0)throw new Error("continuity rollback detected");if(te.existsSync(n)&&(l.marker?.version!==2||s.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(l.marker?.version===2){let a=JSON.parse(L(n));if(a?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Ce(a?.integrity?.mac,le(a.marker,t))||a.marker?.version!==1||a.marker.sequence!==s.sequence||!Ce(a.marker.ledgerMac,le(s,t)))throw new Error("checkpoint rollback detected")}}catch(l){throw new Error(`ledger: corrupt or unreadable: ${l?.message||l}`)}if(r-s.windowStartMs>=Fp){let l=new Date(r).toISOString().slice(0,10),a=d=>String(d||"").startsWith("cex:")&&String(d).endsWith(`:${l}`),c=s.entries.map(d=>{if(d.state==="reserved"||d.state==="consumed")return d;if(Array.isArray(d.units)){let u=d.units.map(f=>a(f.unit)?f:{...f,value:"0",notional:"0"}),m=u.some(f=>BigInt(f.value??0)>0n||BigInt(f.notional??0)>0n);return{...d,state:m?d.state:"consumed",units:u}}return a(d.unit)?d:{...d,state:"consumed",value:"0",notional:"0"}});return{windowStartMs:r,entries:c,sequence:s.sequence??0}}return{...s,sequence:s.sequence??0}}function Up(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=Up(o).find(s=>s.unit===r);return i?n+BigInt(i[t]??0):n},0n)}function Gr(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),s=BigInt(n.notional??0);if(i<0n||s<0n)throw new Error("ledger: unit value/notional must be non-negative");let l=n.fee===void 0?0n:BigInt(n.fee);if(l<0n)throw new Error("ledger: unit fee must be non-negative");return{unit:o,value:i.toString(),notional:s.toString(),fee:l.toString()}});return r.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),r}function Wp(e,t){let r=e[t];if(r==null||r==="")throw new Error(`ledger: ${t} required`);return ae(r,`ledger: ${t}`)}function Bt(e,t){if(String(t).startsWith("cex:")){let[,n,o,i,s,l]=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(s||"")||!/^\d{4}-\d{2}-\d{2}$/.test(l||""))throw new Error("ledger: invalid CEX accounting unit");let a=e.cexAccounts?.[n];if(!a||String(a.accountId)!==o||!Array.isArray(a.venues)||!a.venues.includes(i))throw new Error("ledger: CEX account/venue policy required");if(!a.symbolQuotes||!Object.values(a.symbolQuotes).includes(s))throw new Error("ledger: CEX quote policy required");let c=ae(a.dailyGrossQuoteCap,"ledger: dailyGrossQuoteCap"),d=ae(a.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(([s])=>String(s).toLowerCase()===n)?.[1];if(!o)throw new Error("ledger: ERC-20 token caps required");let i=["maxDailyValueRaw","maxDailyNotionalRaw","maxPerTradeRaw"];for(let s of i)if(o[s]===void 0||o[s]===null||o[s]==="")throw new Error(`ledger: ${s} required`);return i.map(s=>BigInt(o[s]))}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(a=>e[a]!==void 0&&e[a]!==null&&e[a]!=="");if(n.length===r.length)return r.map(a=>Wp(e,a));if(n.length>0){let a=r.filter(c=>!n.includes(c));throw new Error(`ledger: ${a[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 s=q(o,6,"ledger: maxDailyNotionalUsdc"),l=q(i,6,"ledger: maxPerTradeUsdc");return[s,s,l]}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 jt(e,t){let r=`${e}.lock`,n=Dp(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{L(r)===n&&te.unlinkSync(r)}catch{}}}function qe(e,t,r,n,o){let i=`${e}.continuity`,s={...t,sequence:(t.sequence??0)+1},l=le(s,r);Ae(e,JSON.stringify({ledger:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:l}})+`
17
+ `);let a={version:2,sequence:s.sequence,ledgerMac:l};Ae(i,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:le(a,r)}})+`
18
+ `);let c={version:1,sequence:s.sequence,ledgerMac:l};te.mkdirSync(lt.dirname(n),{recursive:!0,mode:448}),Ae(n,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:le(c,r)}})+`
19
+ `),o&&zp(o,r)}function ar({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:s=0,notional:l=0,fee:a,units:c,policy:d,retryReleasedTradeId:u,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=L(t);return jt(e,()=>{let w=Dt(e,p,m,r,n),g=w.entries.find(y=>String(y.tradeId)===f);if(g){if(g.state!=="released"||String(u||"")!==f)throw new Error("ledger: replayed tradeId");if(c!==void 0){let y=Gr(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[x,A,k]=Bt(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)>x||ge(w.entries,"notional",b.unit)+BigInt(b.notional)>A)throw new Error("ledger: daily cap exceeded")}}else{let y={unit:i,value:BigInt(s).toString(),notional:BigInt(l).toString(),fee:a===void 0?"0":BigInt(a).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,x,A]=Bt(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)>x)throw new Error("ledger: daily cap exceeded")}return g.state="reserved",g.atMs=m,g.retriedAtMs=m,delete g.releasedAtMs,qe(e,w,p,r,n),structuredClone(g)}let h;if(c!==void 0){let y=Gr(c);for(let b of y){let[x,A,k]=Bt(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>x||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(s),b=BigInt(l),[x,A,k]=Bt(d,i);if(y<0n||b<0n||b>k)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+y>x||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:a===void 0?"0":BigInt(a).toString(),state:"reserved",atMs:m}}return w.entries.push(h),qe(e,w,p,r,n),structuredClone(h)})}function wa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:s,nowMs:l=Date.now()}){ut(r,e);let a=L(t);return jt(e,()=>{let c=Dt(e,a,l,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=Gr(o.units);if(JSON.stringify(w)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(s){if(!Array.isArray(s.units))throw new Error("ledger: reserved units no longer match decoded economics");let g=Gr(s.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]=Bt(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(s){if(s.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(s.value)>BigInt(d.value)||BigInt(s.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let u=d.unit||"wei",[m,f,p]=Bt(i,u);if(BigInt(d.notional)>p)throw new Error("ledger: per-trade cap exceeded");if(ge(c.entries,"value",u)>m||ge(c.entries,"notional",u)>f)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function ha({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=L(t);return jt(e,()=>{let l=Dt(e,s,i,r,n),a=l.entries.find(c=>String(c.tradeId)===String(o??""));if(!a)throw new Error("ledger: reservation unavailable");if(a.state==="committed"&&["fee-only","no-fee"].includes(a.settledAs))throw new Error("ledger: reservation unavailable");if(a.state==="committed")return structuredClone(a);if(a.state!=="reserved")throw new Error("ledger: reservation unavailable");return a.state="committed",a.committedAtMs=i,qe(e,l,s,r,n),structuredClone(a)})}function ga({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=L(t);return jt(e,()=>{let l=Dt(e,s,i,r,n),a=l.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!a)throw new Error("ledger: reservation unavailable");let c=structuredClone(a);return a.state="released",a.releasedAtMs=i,qe(e,l,s,r,n),c})}function Vp(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 ya({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:s,disposition:l,nowMs:a=Date.now()}){if(ut(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(l))throw new Error("ledger: CEX settlement binding refused");let c=L(t);return jt(e,()=>{let d=Dt(e,c,a,r,n),u=d.entries.find(m=>m.tradeId===o&&m.state==="reserved"&&m.unit===i);if(!u)throw new Error("ledger: exact held CEX reservation unavailable");if(Vp(s,u.notional))throw new Error("ledger: CEX overfill refused; reservation retained");if(l==="release"){if(!/^0(?:\.0+)?$/.test(s))throw new Error("ledger: nonzero CEX fill cannot release");let m=structuredClone(u);return u.state="consumed",u.releasedAtMs=a,u.value="0",u.notional="0",u.fee="0",qe(e,d,c,r,n),m}return u.state="committed",u.committedAtMs=a,u.filledQuote=s,qe(e,d,c,r,n),structuredClone(u)})}function ba({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=L(t);return jt(e,()=>{let l=Dt(e,s,i,r,n),a=l.entries.find(d=>String(d.tradeId)===String(o??""));if(!a)throw new Error("ledger: reservation unavailable");if(a.state==="committed"&&["fee-only","no-fee"].includes(a.settledAs))return structuredClone(a);if(a.state!=="reserved")throw new Error("ledger: reservation unavailable");if(Array.isArray(a.units))return a.state="committed",a.committedAtMs=i,a.units=a.units.map(d=>{let u=BigInt(d.fee??0);return{...d,value:"0",notional:u.toString()}}),a.settledAs=a.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",qe(e,l,s,r,n),structuredClone(a);let c=BigInt(a.fee??0);return c<=0n?(a.state="committed",a.committedAtMs=i,a.value="0",a.notional="0",a.settledAs="no-fee",qe(e,l,s,r,n),structuredClone(a)):(a.state="committed",a.committedAtMs=i,a.value="0",a.notional=c.toString(),a.settledAs="fee-only",qe(e,l,s,r,n),structuredClone(a))})}function Ea(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:G(Mp(t))};return Ce(e.mac,le(o,L(r)))}function Jp(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function xa(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:G(Jp(t))};return Ce(e.mac,le(o,L(r)))}import{spawnSync as Kp}from"node:child_process";function Sa(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=Kp(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}import{Wallet as po}from"ethers";import{base58 as mo}from"@scure/base";import{ed25519 as Oa}from"@noble/curves/ed25519.js";import{NETWORK as Ta,TEST_NETWORK as Na,WIF as Gp,p2wpkh as Aa}from"@scure/btc-signer";import{pubECDSA as Yp}from"@scure/btc-signer/utils.js";var Zr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Xp=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},va=e=>{let t=String(e||"").trim();try{let r=Buffer.from(mo.decode(t));return mo.encode(r)===t?r:null}catch{return null}},wo=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(Oa.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},Ia=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),He=(e,t)=>{if(t==="sol")return wo(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`)},Zp=(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 He(r,t)};function ho(e,t){let r=String(t||"").trim();if(e==="evm")return new po(r).privateKey;if(e==="btc")for(let i of[Ta,Na])try{return Buffer.from(Gp(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let c=Zr(r.slice(4));if(!c)throw new Error("sol: invalid explicit hex private key");return He(c,"sol")}if(/^base58:/i.test(r)){let c=va(r.slice(7));if(!Ia(c))throw new Error("sol: invalid explicit base58 private key");return wo(c)}if(/^0x/i.test(r)){let c=Zr(r);if(!c)throw new Error("sol: invalid explicit hex private key");return He(c,"sol")}let i=Zr(r),s=i&&(i.length===32||i.length===64)?He(i,"sol"):null,l=va(r),a=Ia(l);if(s&&a&&!s.equals(a))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(a)return wo(l);if(i)return He(i,"sol")}let n=Zr(r);if(n)return e==="evm"?new po(`0x${n.toString("hex")}`).privateKey:He(n,e);let o=Xp(r);if(o)return He(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Zp(i,e);let s=i.privateKey??i.secretKey??i.key;if(s)return ho(e,Array.isArray(s)?JSON.stringify(s):String(s))}throw new Error(`${e}: unsupported private key format`)}function ka(e,t){if(e==="evm"){let r=new po(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=He(t,"btc"),n=Yp(r);return{kind:e,secret:r.toString("hex"),addresses:[Aa(n,Ta).address,Aa(n,Na).address]}}if(e==="sol"){let r=He(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[mo.encode(Oa.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function Ca(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:ka(t.kind||"evm",ho(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=ka(i,ho(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,s]of Object.entries(n.cex)){if(!/^[A-Za-z0-9._-]{1,64}$/.test(i)||!s||typeof s!="object")throw new Error("local-vault: cex credential record invalid");if(!/^(?:binance|bybit|okx|coinbase)$/.test(s.venue)||!/^[A-Za-z0-9._-]{1,64}$/.test(s.accountId||""))throw new Error("local-vault: cex credential binding invalid");let l=(c,d=!0)=>{let u=s[c];if(!(!d&&u===void 0)){if(!Array.isArray(u)||u.length<4||u.some(m=>!Number.isInteger(m)||m<0||m>255))throw new Error("local-vault: cex credential bytes invalid");return Buffer.from(u)}},a=s.apiSecretEncoding;if(a!==(s.venue==="coinbase"?"base64":"raw"))throw new Error("local-vault: explicit cex secret encoding refused");o.cex[i]=Object.freeze({venue:s.venue,accountId:s.accountId,apiKeyBytes:l("apiKeyBytes"),apiSecretBytes:l("apiSecretBytes"),apiSecretEncoding:a,passphraseBytes:l("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 go(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Qp=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),em=Object.freeze(["binance","bybit","okx","coinbase"]),tm=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),rm=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),nm=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),sE=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),om=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),aE=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),cE=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),lE=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),uE=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function yo(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 ue(e,t,r){let n=String(e??"");if(!r.test(n))throw new Error(`cex-policy: bounded ${t} required`);return n}function _a(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 im(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function sm(e){return new Date(e).toISOString().slice(0,10)}function am(e,t){let r=ue(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 Qr(e={},t={},r=Date.now()){for(let C of Object.keys(e)){let z=C.toLowerCase();if(om.some(U=>U.toLowerCase()===z))throw new Error(`cex-policy: envelope field ${C} forbidden`);if(!nm.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(!Qp.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=ue(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!em.includes(o)||!tm[o]||!rm[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:s}=am(e,t);if(!Array.isArray(s.venues)||!s.venues.includes(o))throw new Error(`cex-policy: venue ${o} not allowlisted`);let l=ue(e.symbol,"symbol",/^[A-Z0-9._/-]{1,32}$/);if(!Array.isArray(s.symbols)||!s.symbols.includes(l))throw new Error(`cex-policy: symbol ${l} not allowlisted`);let a=ue(e.quote,"quote",/^[A-Z0-9._-]{1,24}$/);if(!s.symbolQuotes||typeof s.symbolQuotes!="object"||s.symbolQuotes[l]!==a)throw new Error("cex-policy: quote does not match sealed symbol policy");let c=ue(s.accountId,"accountId",/^[A-Za-z0-9._-]{1,64}$/);if(!Array.isArray(s.allowedOperations)||!s.allowedOperations.includes(n))throw new Error("cex-policy: operation not in sealed allowlist");let d=ue(e.base,"base",/^[A-Z0-9._-]{1,24}$/);if(s.base!==d||s.quote!==a)throw new Error("cex-policy: base/quote do not match sealed account policy");if(s.credentialRecordRef!==i)throw new Error("cex-policy: credential record reference mismatch");let u=s.filters?.[l];if(!u||typeof u.tickSize!="string"||typeof u.stepSize!="string"||typeof u.minNotional!="string")throw new Error("cex-policy: sealed symbol filters required");ue(e.nonce,"nonce",/^[A-Za-z0-9._:-]{1,128}$/),ue(e.grantId,"grantId",/^[A-Za-z0-9._:-]{1,128}$/),ue(e.artifactHash,"artifactHash",/^[A-Za-z0-9._:-]{1,128}$/);let m=e.clientOrderId===void 0?void 0:ue(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=ue(e.side,"side",/^(?:buy|sell)$/),p=ue(e.timeInForce,"timeInForce",/^GTC$/),w=_a(e.baseSize,"baseSize"),g=_a(e.limitPrice,"limitPrice"),!m)throw new Error("cex-policy: clientOrderId required");if(h=yo(e.maxQuoteNotional,"maxQuoteNotional"),y=im(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:ue(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 x=yo(s.perOrderQuoteCap,"sealed perOrderQuoteCap"),A=yo(s.dailyGrossQuoteCap,"sealed dailyGrossQuoteCap");if(h>x)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}:${a}:${sm(r)}`;return Object.freeze({kind:n,venue:o,symbol:l,base:d,quote:a,side:f,timeInForce:p,baseSize:w?.text,limitPrice:g?.text,clientOrderId:m,venueOrderId:b,filter:Object.freeze({...u}),accountId:c,credentialRef:i,tradeId:v,unit:_,notional:h.toString(),impliedNotional:y.toString()})}function Ra({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Xr(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Qr(e,n,r);return ar({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 cm,randomBytes as lm,timingSafeEqual as um}from"node:crypto";var en=(e,t)=>cm("sha256",e).update(JSON.stringify(t)).digest("hex"),La=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&um(r,n)},$a=e=>Buffer.from(L(e));function Pa({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),s=d=>{if(!Number.isSafeInteger(d.pid)||d.pid<1||typeof d.processStart!="string"||!d.processStart)return null;try{process.kill(d.pid,0)}catch(u){return u?.code==="ESRCH"?!1:null}try{return J.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},l=d=>{J.mkdirSync(dt.dirname(n),{recursive:!0,mode:448});let u=lm(16).toString("hex"),m=Date.now()+5e3,f=`${n}.${process.pid}.${u}.tmp`,p=JSON.stringify({version:1,pid:process.pid,processStart:o,token:u,createdAtMs:Date.now()})+`
20
+ `;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(s(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!==u||w.pid!==process.pid||w.processStart!==o)throw new Error("cex-state: lock ownership lost");J.unlinkSync(n)}},a=()=>{let d=$a(t);try{if(!J.existsSync(e)){if(J.existsSync(r))throw new Error("cex-state: rollback detected");return{version:1,sequence:0,orders:[]}}let u=JSON.parse(L(e));if(!La(u.mac,en(d,u.state)))throw new Error("cex-state: integrity failed");let m=JSON.parse(L(r));if(!La(m.mac,en(d,m.marker))||m.marker.sequence!==u.state.sequence||m.marker.stateMac!==u.mac)throw new Error("cex-state: rollback detected");return u.state}finally{d.fill(0)}},c=d=>{let u=$a(t);try{let m={...d,sequence:d.sequence+1},f=en(u,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:en(u,p)})+`
21
21
  `),Ae(e,JSON.stringify({state:m,mac:f})+`
22
- `),m}finally{l.fill(0)}};return Object.freeze({getByTradeId(d){return u(()=>a().orders.find(l=>l.tradeId===d)||null)},prepare(d){return u(()=>{let l=a(),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=a(),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=a().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 xm}from"node:crypto";import{createHash as dm}from"node:crypto";var xo=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}"]})}),cr=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),fm=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,pm=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/,Ba=(e,t)=>{let r=String(e??"");if(!fm.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 bo=(e,t)=>{let r=String(e??"");if(!pm.test(r))throw new Error(`cex: bounded ${t} required`);return r},Eo=e=>{if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Eo).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Eo(e[t])}`).join(",")}}`;throw new Error("cex: non-canonical request fact refused")};function mm(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");Ba(e.baseSize,"baseSize"),Ba(e.limitPrice,"limitPrice"),bo(e.clientOrderId,"clientOrderId")}else bo(e.venueOrderId,"venueOrderId");return e}function wm(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 Da({venue:e,order:t,timestamp:r,recvWindow:n=5e3}){mm(t);let o=xo[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[s,u]=o;u.includes("{order_id}")&&(u=u.replace("{order_id}",encodeURIComponent(bo(t.venueOrderId,"venueOrderId"))));let a={venue:e,operation:t.operation,method:s,path:u,timestamp:i,recvWindow:n,...wm(e,t)};return Object.freeze({...a,params:a.params&&Object.freeze(a.params),body:a.body&&Object.freeze(a.body),requestDigest:dm("sha256").update(Eo(a)).digest("hex")})}import{createHmac as hm}from"node:crypto";var tn=(e,t,r="hex")=>hm("sha256",e).update(t).digest(r),Fa=e=>new URLSearchParams(Object.entries(e||{})).toString(),gm=e=>e===void 0?"":JSON.stringify(e),So=(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 ym(e,t){let r=So(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 ja(e,t){if(t?.venue!==e.venue)throw new Error("cex: credential venue mismatch");let r=So(t.apiKeyBytes,"credential"),n=ym(t,e.venue),o=t.passphraseBytes?So(t.passphraseBytes,"credential"):null;try{let i={accept:"application/json"},s=gm(e.body);s&&(i["content-type"]="application/json");let u=Fa(e.params),a=e.path;if(e.venue==="binance"){let c=Fa({...e.params,timestamp:e.timestamp,recvWindow:String(e.recvWindow)});u=`${c}&signature=${tn(n,c)}`,i["X-MBX-APIKEY"]=ft(r)}else if(e.venue==="bybit"){let c=e.method==="GET"?u:s;Object.assign(i,{"X-BAPI-API-KEY":ft(r),"X-BAPI-TIMESTAMP":e.timestamp,"X-BAPI-RECV-WINDOW":String(e.recvWindow),"X-BAPI-SIGN":tn(n,e.timestamp+ft(r)+e.recvWindow+c)})}else if(e.venue==="okx"){let c=a+(u?`?${u}`:"");Object.assign(i,{"OK-ACCESS-KEY":ft(r),"OK-ACCESS-SIGN":tn(n,e.timestamp+e.method+c+s,"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":tn(n,e.timestamp+e.method+a+s,"base64"),"CB-ACCESS-TIMESTAMP":e.timestamp,"CB-ACCESS-PASSPHRASE":ft(o||Buffer.alloc(0))});return{url:cr[e.venue]+a+(u?`?${u}`:""),method:e.method,headers:i,body:s||void 0}}finally{r.fill(0),n.fill(0),o?.fill(0)}}var Ma=256*1024,bm=/^(?=[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),s;try{s=decodeURIComponent(i)}catch{return!1}if(!bm.test(s)||encodeURIComponent(s)!==i)return!1;try{return new URL(r,e).pathname===r&&r===`${n}${i}${o}`}catch{return!1}}async function Ao(e,t){let r=xo[e.venue]?.[e.operation],n=cr[e.venue];if(!r||!n||r[0]!==e.method||!Em(n,r[1],e.path))throw new Error("cex transport refused");let o=ja(e,t),i=new AbortController,s=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 a=new URL(u.url||o.url),c=new URL(cr[e.venue]);if(a.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>Ma)throw new Error("size");let l=new Uint8Array(await u.arrayBuffer());if(l.length>Ma)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(s);for(let u of Object.values(o.headers));o.headers=null,o.body=void 0}}var Sm=e=>xm("sha256").update(e).digest("hex"),Am=(e,t)=>e==="okx"?new Date(t).toISOString():String(e==="coinbase"?t/1e3:t),vo=e=>/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/.test(String(e||""))?String(e):null,ur=e=>typeof e=="string"&&/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e)?e:null;var qa=e=>/^0(?:\.0+)?$/.test(String(e));function vm(e,t){if(!ur(e)||!ur(t))throw new Error("cex authoritative decimal refused");let[r,n=""]=e.split("."),[o,i=""]=t.split("."),s=n.length+i.length,u=BigInt(r+n)*BigInt(o+i);if(!s)return u.toString();let a=u.toString().padStart(s+1,"0");return`${a.slice(0,-s)}.${a.slice(-s)}`}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:vo(n)}function km(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),vo(n)===r.venueOrderId}function Om(e,t,r){let n=t,o,i,s,u,a;if(e==="binance"?(o=t?.orderId,i=t?.clientOrderId,s=t?.symbol,u={CANCELED:"cancelled",REJECTED:"rejected",FILLED:"filled",PARTIALLY_FILLED:"partial",NEW:"open",PENDING_CANCEL:"open"}[t?.status],a=t?.cummulativeQuoteQty):e==="bybit"&&t?.retCode===0&&t?.result?.list?.length===1?(n=t.result.list[0],o=n.orderId,i=n.orderLinkId,s=n.symbol,u={Cancelled:"cancelled",Rejected:"rejected",Filled:"filled",PartiallyFilled:"partial",New:"open"}[n.orderStatus],a=n.cumExecValue):e==="okx"&&t?.code==="0"&&t?.data?.length===1?(n=t.data[0],o=n.ordId,i=n.clOrdId,s=n.instId,u={canceled:"cancelled",filled:"filled",partially_filled:"partial",live:"open"}[n.state],ur(n.accFillSz)&&ur(n.avgPx)&&(qa(n.accFillSz)||!qa(n.avgPx))&&(a=vm(n.accFillSz,n.avgPx))):e==="coinbase"&&(o=t?.id,i=t?.client_oid,s=t?.product_id,u=t?.status==="done"?t?.done_reason==="canceled"?"cancelled":"filled":{rejected:"rejected",open:"open",pending:"open",active:"open"}[t?.status],a=t?.executed_value),vo(o)!==r.venueOrderId||String(s||"")!==r.symbol||r.clientOrderId&&String(i||"")!==r.clientOrderId||!u||!ur(a))throw new Error("cex authoritative status identity refused");return{status:u,filledQuote:a}}async function Tm(e,t){let r=t?.nowMs?.()??Date.now(),n=t?.transport||Ao,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,s=i?.tradeId||e.tradeId,u=Da({venue:e.venue,order:e.order,timestamp:Am(e.venue,r),recvWindow:5e3}),a;e.order.operation==="create"?a=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}):a=e.store.transition(s,["open","uncertain","sent","cancel-pending","settlement-pending"],"prepared",{operation:e.order.operation,requestDigest:u.requestDigest,nowMs:r}),e.store.transition(s,"prepared","sent",{sentAtMs:r});let c;try{c=await n(u,o)}catch{throw e.store.transition(s,"sent","uncertain",{uncertainAtMs:r}),new Error("cex transport refused; order is uncertain and requires status reconciliation")}let d=Sm(c.responseBodyBytes);if(e.order.operation==="create"){let f=Im(e.venue,c.value,e.order);if(!f)throw e.store.transition(s,"sent","uncertain",{responseDigest:d}),new Error("cex response refused; order is uncertain and requires status reconciliation");return e.store.transition(s,"sent","open",{venueOrderId:f,responseDigest:d,openedAtMs:r})}if(e.order.operation==="cancel")return e.store.transition(s,"sent",km(e.venue,c.value,i)?"cancel-pending":"uncertain",{responseDigest:d,observedAtMs:r});let l;try{l=Om(e.venue,c.value,i)}catch{return e.store.transition(s,"sent","uncertain",{responseDigest:d,observedAtMs:r})}let m=["cancelled","rejected","filled"].includes(l.status);if(m||l.status==="partial"){e.store.transition(s,"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(s,"settlement-pending","terminal",{settledAtMs:r})}return e.store.transition(s,"sent","open",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote})}function Ha(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||Ao,nowMs:e.nowMs||Date.now,settleLedger:e.settleLedger});return Object.freeze({execute:r=>Tm(r,t)})}import{createHash as Nm,createHmac as za,randomBytes as Cm,timingSafeEqual as _m}from"node:crypto";var Ua="oracle-local-signer-cex-owner-allow-v1",jt=e=>/^(?:0|[1-9]\d{0,19})$/.test(String(e||""))?String(e):null,Wa=e=>JSON.stringify(e),Rm=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&_m(r,n)};function Va({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(jt).filter(Boolean));if(!n.size)throw new Error("cex owner proof: approved owner context required");let o=new Set,i=u=>{let a=Buffer.from(L(e));try{return u(a)}finally{a.fill(0)}},s=i(u=>Nm("sha256").update("cex-owner-instance\0").update(u).digest("hex"));return Object.freeze({mint({digest:u,senderId:a,chatId:c,platform:d,ttlMs:l=15e3}={}){let m=jt(a),f=jt(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:Ua,instance:s,nonce:Cm(16).toString("hex"),issuedAtMs:p,expiresAtMs:p+l},g=i(h=>za("sha256",h).update(Wa(w)).digest("hex"));return{claims:w,mac:g}},verify(u,{digest:a}={}){let c=u?.claims,d=r();if(!c||c.version!==1||c.decision!=="Allow"||c.digest!==a||c.audience!==Ua||c.instance!==s||!/^[0-9a-f]{32}$/.test(c.nonce||"")||jt(c.ownerSenderId)!==jt(c.telegramChatId)||!n.has(jt(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=>za("sha256",m).update(Wa(c)).digest("hex"));return Rm(u.mac,l)?(o.add(c.nonce),!0):!1}})}var Re=new Co(["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"]),Ja=new Co(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),ko=new Co(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function Mm({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 s=n.then(i,i);return n=s.then(()=>{},()=>{}),s};return Object.freeze({armGeneration:()=>r,disarm:()=>o(()=>(r+=1,t(),!0)),broadcastWithArmFence:(i,s)=>o(async()=>{if(i!==r||!e())throw new Error("signer: disarmed generation changed before broadcast handoff");return s()})})}function qm(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||re.join(process.env.XDG_STATE_HOME||re.join(Lm.homedir(),".local","state"),"oracle"),r=$m("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 Hm(e){try{return L(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=Pm(32).toString("hex");return Ae(e,t+`
23
- `),t}function Oo(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 Ga(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function J(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 Ya(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function zm(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 Um(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 s=n?.transactions;if(!Array.isArray(s)||s.length!==1)throw new Error("signer: exact Anvil action transaction required");let u=t==="buy"?"buySpecificNFT":"sellNFT",a;try{if(a=Re.decodeFunctionData(u,s[0].data),Re.encodeFunctionData(u,[a[0],a[1]]).toLowerCase()!==String(s[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${t} calldata required`)}if(BigInt(a[0])!==BigInt(e.tokenId)||BigInt(a[1])!==i)throw new Error(`signer: exact Anvil ${t} calldata limit mismatch`);return i}async function ze(e,t,r,n,o,i=[]){let s=await e.send("eth_call",[{to:t,data:r.encodeFunctionData(n,i)},o]);return r.decodeFunctionResult(n,s)[0]}async function Wm(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"),s=_e(t.contract,"Anvil collection"),u=_e(t.paymentToken,"Anvil payment token"),a=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=zm(t,f),w=Um(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(Ya(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=Ya(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=Fm(C).toLowerCase();if(z!==h)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[U,R,$]=await Promise.all([ze(e,i,Re,"collection",_),ze(e,i,Re,"token",_),ze(e,i,Re,"robinhoodSwapFeeWei",_)]),Je=_e(U,"live Anvil collection"),pt=_e(R,"live Anvil payment token"),Mt=BigInt($).toString();if(Je!==s)throw new Error("signer: live Anvil collection mismatch");if(pt!==u)throw new Error("signer: live Anvil payment token mismatch");if(Mt!==a.toString())throw new Error("signer: live Anvil native swap fee mismatch");let qt=Number(await ze(e,pt,Ja,"decimals",_));if(!Number.isSafeInteger(qt)||qt!==c)throw new Error("signer: live Anvil payment token decimals mismatch");let mt=_e(await ze(e,Je,ko,"ownerOf",_,[m]),"live Anvil token owner"),Ge=null,Ye=null,Xe=null,Ze=null,M;if(f==="buy"){let[Ue,wt,E]=await Promise.all([ze(e,i,Re,"inventory",_,[m]),ze(e,pt,Ja,"allowance",_,[d,i]),e.send("eth_call",[{to:i,data:Re.encodeFunctionData("quoteSpecificBuy",[m])},_])]);Ge=!!Ue,Ye=BigInt(wt).toString();let I=Re.decodeFunctionResult("quoteSpecificBuy",E);if(M=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(M)!==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(!M.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(M.totalCostRaw)!==w)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(M.totalCostRaw)!==BigInt(M.baseCostRaw)+BigInt(M.feeRaw)+BigInt(M.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[Ue,wt,E]=await Promise.all([ze(e,Je,ko,"getApproved",_,[m]),ze(e,Je,ko,"isApprovedForAll",_,[d,i]),e.send("eth_call",[{to:i,data:Re.encodeFunctionData("quoteSellNFT")},_])]);Xe=_e(Ue,"live Anvil token approval"),Ze=!!wt;let I=Re.decodeFunctionResult("quoteSellNFT",E);if(M=Object.freeze({netPayoutRaw:BigInt(I[0]).toString(),grossPayoutRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString()}),JSON.stringify(M)!==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(M.netPayoutRaw)!==w)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(M.netPayoutRaw)+BigInt(M.feeRaw)+BigInt(M.protocolFeeRaw)!==BigInt(M.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:Je,paymentToken:pt,paymentTokenDecimals:qt,nativeSwapFeeWei:Mt,signerAddress:d,nftAction:f,tokenId:m.toString(),tokenOwner:mt,inventoryMember:Ge,allowanceRaw:Ye,approvedAddress:Xe,approvedForAll:Ze,quote:M,blockNumber:A.toString(),blockHash:v,runtimeCodeHash:z,verifiedAtMs:Number(n)})}function Xa(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 Vm(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:s}={}){let u=Dm(new URL("./anvil-attestation-worker.mjs",import.meta.url)),a={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},c;try{c=Bm(process.execPath,[u],{input:JSON.stringify({rpcUrl:e,chainId:t,envelope:r,policy:a,nowMs:Number(o),signerAddress:s}),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)}async function lr(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 No(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 To(e,t){let r=Array.isArray(t)?t:[t],n=No(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 Km({provider:e=null,readPolicy:t,rpc:r=lr,fetchImpl:n=fetch}={}){if(typeof t!="function")throw new TypeError("signer: execution observer requires readPolicy");return async o=>{let i=String(o?.surface||""),s=String(o?.signedTransactionId||"");if(!s)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 a=await e.getTransactionReceipt(s);return a?{transactionHash:s,status:a.status}:null}let u=t();if(i==="sol"){let a=String(u.solRpcUrl||u.solanaRpcUrl||"");if(!a)return null;let d=(await r(a,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[s],{searchTransactionHistory:!0}]}))?.value?.[0];return d?d.err?{transactionHash:s,status:0}:d.confirmationStatus==="confirmed"||d.confirmationStatus==="finalized"||d.confirmations===null?{transactionHash:s,status:1}:null:null}if(i==="btc"){let a=String(u.btcRpcUrl||u.bitcoinRpcUrl||"").replace(/\/$/,"");if(!a)return null;try{let c=a.endsWith("/tx")?a.slice(0,-3):a,d=await n(`${c}/tx/${s}/status`);if(d.ok)return(await d.json())?.confirmed===!0?{transactionHash:s,status:1}:null}catch{}try{let c=await r(a,{jsonrpc:"1.0",id:"oracle",method:"getrawtransaction",params:[s,!0]});return Number(c?.confirmations||0)>0?{transactionHash:s,status:1}:null}catch{return null}}return null}}async function Qa(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 lr(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function Jm(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 s=await fetch(`${o}/tx/${t}/outspend/${r}`);if(s.ok){let u=await s.json();if(u?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(u?.spent===!1)return!0}}catch(s){if(/already spent/.test(String(s?.message||s)))throw s}if(!await Qa(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Gm(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 Ym(e,t){return{simulate:async(r,n)=>(Pe(n,e()),!0),sign:async(r,n)=>{Pe(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).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?(qi(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Hi({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{Pe(o,e());let{Signature:i,keccak256:s}=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:s(r),status:1}}}}function Xm(e){return{simulate:async(t,r)=>(De(r,e()),!0),sign:async(t,r)=>{De(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 er(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=De(n,e()),i=er(r,t),s=Wi(i),u=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s}),a=await u.json().catch(()=>({}));if(!u.ok||Number(a?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(a?.tx_hash||a?.txHash||"lighter"),status:1}}}}function Zm(e,t){return{simulate:async(r,n)=>(rt(n,e()),!0),sign:async(r,n)=>{rt(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 s=r.domain||r.typedData.domain,u=r.types||r.typedData.types,a=r.message||r.typedData.message;return t.signTypedData(s,u,a)},broadcast:async(r,n,o)=>{let i=rt(o,e()),{keccak256:s}=await import("ethers"),u=n.message||n.typedData.message,a=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(a)}),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:s(r),status:1,orderHash:i.digest,uid:typeof d=="string"?d:d?.uid||null}}}}function Qm(e,t){return{simulate:async(r,n)=>(Be(n,e()),!0),sign:async(r,n)=>{Be(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).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(),s=Be(o,i),u=En(i),{keccak256:a}=await import("ethers"),c=di({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:u.key}),d=JSON.stringify(c),l=ui({creds:u,address:o.owner,method:"POST",path:"/order",body:d}),m=await fetch(s.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:a(r),status:1}}}}function ew(e,t){let r=go(t);return{simulate:async n=>{let o=e(),i=Io.fromPSBT(Buffer.from(n.psbt,"base64"));return await Promise.all(Array.from({length:i.inputsLength},(s,u)=>{let a=i.getInput(u),c=Buffer.from(a.txid||[]).toString("hex");return Jm(o,c,a.index)})),!0},sign:n=>{let o=Io.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 s=Io.fromPSBT(Buffer.from(n,"base64"));s.finalize(),s.extract();let u;try{let c=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:s.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 Qa(o,"sendrawtransaction",[s.hex])}if(u&&String(u).toLowerCase()!==s.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let a=null;try{let c=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${c}/tx/${s.id}/status`);d.ok&&(a=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:s.id,status:a}}}}function tw(e,t){let r=go(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 s=Buffer.from(n.messageBase64,"base64"),u=No(s),a=To(s,Array.from({length:u},()=>new Uint8Array(64))),c=await lr(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[a,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Gm(c)},sign:n=>{let o=Buffer.from(n.messageBase64,"base64"),i=No(o),s=jm.sign(o,r);if(i===1)return To(o,[s]);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 To(o,[s,...u.map(a=>Buffer.from(String(a),"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 s=await lr(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),a=(await lr(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[s],{searchTransactionHistory:!0}]}))?.value?.[0];if(a?.err)return{hash:s,status:0};let c=a?.confirmationStatus==="confirmed"||a?.confirmationStatus==="finalized"||a?.confirmations===null;return{hash:s,status:c?1:null}}}}function rw(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 nw(e,t,r,n,{submitPrivate:o}={}){if((await e.getNetwork()).chainId!==BigInt(r.chainId))throw new Error("signer: RPC chain mismatch");let s={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:s,verifiedAfter:p,submission:{path:"private",mode:m.mode,endpoint:m.endpoint}}}}catch(m){if(l)throw m}}let a=await e.broadcastTransaction(t),c=await a.wait(),d={native:(await e.getBalance(r.from)).toString()};return{hash:c?.hash??a.hash,status:c?.status??null,verifiedBefore:s,verifiedAfter:d,submission:{path:"public"}}}async function ec({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:s=12e4}={}){let{JsonRpcProvider:u,Wallet:a}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(s<1e3||s>12e4)throw new Error("signer: session must be at most 120 seconds");let c=qm(e),d=()=>Object.freeze(Xr(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?Va({keyFile:c.policyKey,approvedTelegramOwners:m}):null;if(J(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(J(l,"poly")&&(En(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(J(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(J(l,"cex")&&(!l.cexAccounts||Object.keys(l.cexAccounts).length===0))throw new Error("signer: cexAccounts allowlist is empty");if(J(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?Sa(r):L(t),g=da(c.vault),h=la(g,w),y;try{y=Ca(h,g.meta)}finally{h.fill(0)}if((Ga(l)||J(l,"hl")||J(l,"poly"))&&Oo("evm",y.evm,l.owners),J(l,"btc")&&Oo("btc",y.btc,l.owners),J(l,"sol")&&Oo("sol",y.sol,l.owners),J(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=Ga(l);if(S&&(b.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(J(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(J(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||J(l,"hl")||J(l,"poly"))?A?new a(y.evm.secret).connect(A):new a(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)=>nw(A,E,I,T,{submitPrivate:pa})}:null,_=A?async E=>ow(A,E):void 0,C=new Map,z=E=>E?.surface==="evm-nft"&&String(E?.provider).toLowerCase()==="anvil-nft",U=async(E,I=d(),T="execution")=>{if(!z(E))return null;let j=await Wm(A,E,I,{nowMs:Date.now(),signerAddress:k.address}),Y=C.get(G(E));return Y&&Xa(Y,j,T),j},R={...v?{evm:v,"evm-swap":v,"evm-bridge":v,"evm-nft":v}:{},...k&&J(l,"evm-order")?{"evm-order":Zm(d,k)}:{},...y.btc?{btc:ew(d,y.btc)}:{},...y.sol?{sol:tw(d,y.sol)}:{},...k&&J(l,"hl")?{hl:Ym(d,k)}:{},...k&&J(l,"poly")?{poly:Qm(d,k)}:{},...J(l,"lighter")?{lighter:Xm(d)}:{}};rw(R,n);let $=ji({...R,...n}),Je=new Set(Object.keys(R)),pt=new Set(Object.keys(n||{})),Mt=l.surfaces.filter(E=>E!=="cex"&&!Je.has(E)&&!pt.has(E));if(Mt.length)throw new Error(`signer: ${Mt.join(",")} require local keys or injected surface transports`);let qt=Date.now(),mt=qt+s,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:Ka.existsSync(c.lock)?(Ge=!0,!1):Ka.existsSync(c.vault)&&Date.now()<mt,M=Mm({isArmed:Ze,disarmNow:()=>{Ge=!0,Xe(),Ae(c.lock,`disarmed ${new Date().toISOString()}
24
- `)}}),Ue=os({host:o,port:i,token:Hm(c.token),policy:l,readPolicy:d,isArmed:Ze,disarm:M.disarm,armGeneration:M.armGeneration,broadcastWithArmFence:M.broadcastWithArmFence,sessionExpiresAtMs:mt,executionOutbox:bs({path:c.executionOutbox,now:Date.now}),observeExecutionTransaction:Km({provider:A,readPolicy:d}),nowMs:Date.now,simulate:async(E,I)=>(await U(I,d(),"before simulation"),vr(I,$).simulate(E,I)),estimateNetworkFees:_,sign:async(E,I)=>(await U(I,d(),"before signing"),vr(I,$).sign(E,I)),verifySigned:(E,I,T)=>Yi(T?.surface||"evm",E,I,T),broadcast:async(E,I,T)=>(await U(T,d(),"before broadcast"),vr(T,$).broadcast(E,I,T)),confirmArtifact:async(E,I,T)=>{let j=await U(E,T),Y=await sw(E,I,T,j);return Y===!0&&j&&C.set(I,j),Y},decodeEconomics:(E,I)=>Cn(E,I),reserveLedger:(E,I,T={})=>{let j=E?.version===1&&E?.surface?E:null,Y=j?.artifact||E;if(z(j)){let Qe=G(j),We=C.get(Qe);if(!We||Date.now()-Number(We.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let Ht=Vm(I.rpcUrl,Y.chainId,j,I,{nowMs:Date.now(),signerAddress:k.address});Xa(We,Ht,"before reservation"),C.set(Qe,Ht)}let dr=j?.tradeId||Y?.tradeId;if(!dr)throw new Error("ledger: executable artifact requires a tradeId");let ye;if(j)ye=Cn(j,I);else{if(Y?.value===void 0)throw new Error("ledger: executable artifact value required");let Qe=BigInt(Y.value),We=BigInt(Y.gasLimit??0),Ht=BigInt(Y.maxFeePerGas??Y.gasPrice??0);if(We<=0n||Ht<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let _o=We*Ht+BigInt(Y.l1FeeWei??0)+BigInt(Y.operatorFeeWei??0);ye={unit:"wei",value:Qe.toString(),notional:(Qe+_o).toString(),fee:_o.toString()}}if(Array.isArray(ye.units))return ar({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:dr,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 ar({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:dr,...ye,policy:I,retryReleasedTradeId:T.retryReleasedTradeId})},commitLedger:E=>ha({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),releaseLedger:E=>ga({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),settleFailedLedger:E=>ba({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),validateReservation:(E,I,T)=>wa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,reservation:E,policy:I,economics:T}),verifyFeeWaiver:(E,I)=>xa(E,I,c.policyKey),verifyTriggerAttestation:(E,I,T)=>Ea(E,I,c.policyKey,T),inspectCex:Qr,verifyOwnerProof:f?(E,I)=>f.verify(E,I):void 0,verifyCexOwnerProof:f?(E,I)=>f.verify(E,I):void 0,cexExecute:J(l,"cex")?async E=>{let I=d(),T=Qr(E,I,Date.now()),j=T.kind==="spot-limit-create"?"create":T.kind==="spot-limit-cancel"?"cancel":"status";j==="create"&&Ra({envelope:E,paths:c,nowMs:Date.now()});let Y=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 Ha({credential:ye=>y.cex[ye],settleLedger:({tradeId:ye,disposition:Qe,filledQuote:We})=>ya({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ye,expectedUnit:T.unit,filledQuote:We,disposition:Qe})}).execute({venue:T.venue,accountId:T.accountId,credentialRef:T.credentialRef,tradeId:T.tradeId,reservedNotional:T.notional,order:Y,store:Pa({file:c.cexOrders,keyFile:c.policyKey,anchorFile:c.cexOrdersAnchor})})}:void 0,ledgerObserver:sa(process.env)?aa({path:c.workflowLedger,telemetry:ua(process.env),onError:E=>{try{console.error(`signer: ${E}`)}catch{}}}):null,autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),wt=setTimeout(()=>Ue.close(),s);return wt.unref(),Ue.on("close",()=>{clearTimeout(wt),Xe()}),Ue.listen(i,o),Ue}var rn="0x420000000000000000000000000000000000000F";function Za(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 ow(e,t){if(!ke(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 s;try{let u=await e.call({to:rn,data:o.encodeFunctionData("getL1Fee",[i])});s=o.decodeFunctionResult("getL1Fee",u)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:s,operatorFeeWei:await iw(e,o,t.gasLimit)}}async function iw(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:rn,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Za(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:rn,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:rn,data:t.encodeFunctionData("operatorFeeConstant")}),s=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),u=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*s/1000000n+u).toString()}catch(o){if(!Za(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function sw(e,t,r,n=null){return process.stdin.isTTY?(process.stderr.write(br(e,t,r,n)),process.stdin.resume(),new Promise(o=>{let i=s=>{process.stdin.off("data",i),process.stdin.pause(),o(String(s).trim()===t)};process.stdin.once("data",i)})):!1}var tc=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
22
+ `),m}finally{u.fill(0)}};return Object.freeze({getByTradeId(d){return l(()=>a().orders.find(u=>u.tradeId===d)||null)},prepare(d){return l(()=>{let u=a(),m=u.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({...u,orders:[...u.orders,f]}),Object.freeze(f)})},transition(d,u,m,f={}){return l(()=>{let p=a(),w=p.orders.findIndex(h=>h.tradeId===d);if(w<0)throw new Error("cex-state: durable prior order required");if(![].concat(u).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:u,credentialRef:m,symbol:f,venueOrderId:p}){return l(()=>{let w=a().orders.find(g=>g.venue===d&&g.accountId===u&&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 xm}from"node:crypto";import{createHash as dm}from"node:crypto";var xo=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}"]})}),cr=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),fm=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,pm=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/,Ba=(e,t)=>{let r=String(e??"");if(!fm.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 bo=(e,t)=>{let r=String(e??"");if(!pm.test(r))throw new Error(`cex: bounded ${t} required`);return r},Eo=e=>{if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Eo).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Eo(e[t])}`).join(",")}}`;throw new Error("cex: non-canonical request fact refused")};function mm(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");Ba(e.baseSize,"baseSize"),Ba(e.limitPrice,"limitPrice"),bo(e.clientOrderId,"clientOrderId")}else bo(e.venueOrderId,"venueOrderId");return e}function wm(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 Da({venue:e,order:t,timestamp:r,recvWindow:n=5e3}){mm(t);let o=xo[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[s,l]=o;l.includes("{order_id}")&&(l=l.replace("{order_id}",encodeURIComponent(bo(t.venueOrderId,"venueOrderId"))));let a={venue:e,operation:t.operation,method:s,path:l,timestamp:i,recvWindow:n,...wm(e,t)};return Object.freeze({...a,params:a.params&&Object.freeze(a.params),body:a.body&&Object.freeze(a.body),requestDigest:dm("sha256").update(Eo(a)).digest("hex")})}import{createHmac as hm}from"node:crypto";var tn=(e,t,r="hex")=>hm("sha256",e).update(t).digest(r),ja=e=>new URLSearchParams(Object.entries(e||{})).toString(),gm=e=>e===void 0?"":JSON.stringify(e),So=(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 ym(e,t){let r=So(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 Fa(e,t){if(t?.venue!==e.venue)throw new Error("cex: credential venue mismatch");let r=So(t.apiKeyBytes,"credential"),n=ym(t,e.venue),o=t.passphraseBytes?So(t.passphraseBytes,"credential"):null;try{let i={accept:"application/json"},s=gm(e.body);s&&(i["content-type"]="application/json");let l=ja(e.params),a=e.path;if(e.venue==="binance"){let c=ja({...e.params,timestamp:e.timestamp,recvWindow:String(e.recvWindow)});l=`${c}&signature=${tn(n,c)}`,i["X-MBX-APIKEY"]=ft(r)}else if(e.venue==="bybit"){let c=e.method==="GET"?l:s;Object.assign(i,{"X-BAPI-API-KEY":ft(r),"X-BAPI-TIMESTAMP":e.timestamp,"X-BAPI-RECV-WINDOW":String(e.recvWindow),"X-BAPI-SIGN":tn(n,e.timestamp+ft(r)+e.recvWindow+c)})}else if(e.venue==="okx"){let c=a+(l?`?${l}`:"");Object.assign(i,{"OK-ACCESS-KEY":ft(r),"OK-ACCESS-SIGN":tn(n,e.timestamp+e.method+c+s,"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":tn(n,e.timestamp+e.method+a+s,"base64"),"CB-ACCESS-TIMESTAMP":e.timestamp,"CB-ACCESS-PASSPHRASE":ft(o||Buffer.alloc(0))});return{url:cr[e.venue]+a+(l?`?${l}`:""),method:e.method,headers:i,body:s||void 0}}finally{r.fill(0),n.fill(0),o?.fill(0)}}var Ma=256*1024,bm=/^(?=[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),s;try{s=decodeURIComponent(i)}catch{return!1}if(!bm.test(s)||encodeURIComponent(s)!==i)return!1;try{return new URL(r,e).pathname===r&&r===`${n}${i}${o}`}catch{return!1}}async function Ao(e,t){let r=xo[e.venue]?.[e.operation],n=cr[e.venue];if(!r||!n||r[0]!==e.method||!Em(n,r[1],e.path))throw new Error("cex transport refused");let o=Fa(e,t),i=new AbortController,s=setTimeout(()=>i.abort(),5e3);try{let l=await fetch(o.url,{method:o.method,headers:o.headers,body:o.body,redirect:"manual",signal:i.signal});if(l.status<200||l.status>=300)throw new Error("http status");if(l.status>=300&&l.status<400)throw new Error("redirect");let a=new URL(l.url||o.url),c=new URL(cr[e.venue]);if(a.origin!==c.origin)throw new Error("origin");if(!String(l.headers.get("content-type")||"").toLowerCase().startsWith("application/json"))throw new Error("content type");let d=Number(l.headers.get("content-length"));if(Number.isFinite(d)&&d>Ma)throw new Error("size");let u=new Uint8Array(await l.arrayBuffer());if(u.length>Ma)throw new Error("size");let m;try{m=JSON.parse(new TextDecoder().decode(u))}catch{throw new Error("json")}return{statusCode:l.status,value:m,responseBodyBytes:u}}catch{throw new Error("cex transport refused")}finally{clearTimeout(s);for(let l of Object.values(o.headers));o.headers=null,o.body=void 0}}var Sm=e=>xm("sha256").update(e).digest("hex"),Am=(e,t)=>e==="okx"?new Date(t).toISOString():String(e==="coinbase"?t/1e3:t),vo=e=>/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/.test(String(e||""))?String(e):null,lr=e=>typeof e=="string"&&/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e)?e:null;var qa=e=>/^0(?:\.0+)?$/.test(String(e));function vm(e,t){if(!lr(e)||!lr(t))throw new Error("cex authoritative decimal refused");let[r,n=""]=e.split("."),[o,i=""]=t.split("."),s=n.length+i.length,l=BigInt(r+n)*BigInt(o+i);if(!s)return l.toString();let a=l.toString().padStart(s+1,"0");return`${a.slice(0,-s)}.${a.slice(-s)}`}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:vo(n)}function km(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),vo(n)===r.venueOrderId}function Om(e,t,r){let n=t,o,i,s,l,a;if(e==="binance"?(o=t?.orderId,i=t?.clientOrderId,s=t?.symbol,l={CANCELED:"cancelled",REJECTED:"rejected",FILLED:"filled",PARTIALLY_FILLED:"partial",NEW:"open",PENDING_CANCEL:"open"}[t?.status],a=t?.cummulativeQuoteQty):e==="bybit"&&t?.retCode===0&&t?.result?.list?.length===1?(n=t.result.list[0],o=n.orderId,i=n.orderLinkId,s=n.symbol,l={Cancelled:"cancelled",Rejected:"rejected",Filled:"filled",PartiallyFilled:"partial",New:"open"}[n.orderStatus],a=n.cumExecValue):e==="okx"&&t?.code==="0"&&t?.data?.length===1?(n=t.data[0],o=n.ordId,i=n.clOrdId,s=n.instId,l={canceled:"cancelled",filled:"filled",partially_filled:"partial",live:"open"}[n.state],lr(n.accFillSz)&&lr(n.avgPx)&&(qa(n.accFillSz)||!qa(n.avgPx))&&(a=vm(n.accFillSz,n.avgPx))):e==="coinbase"&&(o=t?.id,i=t?.client_oid,s=t?.product_id,l=t?.status==="done"?t?.done_reason==="canceled"?"cancelled":"filled":{rejected:"rejected",open:"open",pending:"open",active:"open"}[t?.status],a=t?.executed_value),vo(o)!==r.venueOrderId||String(s||"")!==r.symbol||r.clientOrderId&&String(i||"")!==r.clientOrderId||!l||!lr(a))throw new Error("cex authoritative status identity refused");return{status:l,filledQuote:a}}async function Tm(e,t){let r=t?.nowMs?.()??Date.now(),n=t?.transport||Ao,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,s=i?.tradeId||e.tradeId,l=Da({venue:e.venue,order:e.order,timestamp:Am(e.venue,r),recvWindow:5e3}),a;e.order.operation==="create"?a=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:l.requestDigest,nowMs:r}):a=e.store.transition(s,["open","uncertain","sent","cancel-pending","settlement-pending"],"prepared",{operation:e.order.operation,requestDigest:l.requestDigest,nowMs:r}),e.store.transition(s,"prepared","sent",{sentAtMs:r});let c;try{c=await n(l,o)}catch{throw e.store.transition(s,"sent","uncertain",{uncertainAtMs:r}),new Error("cex transport refused; order is uncertain and requires status reconciliation")}let d=Sm(c.responseBodyBytes);if(e.order.operation==="create"){let f=Im(e.venue,c.value,e.order);if(!f)throw e.store.transition(s,"sent","uncertain",{responseDigest:d}),new Error("cex response refused; order is uncertain and requires status reconciliation");return e.store.transition(s,"sent","open",{venueOrderId:f,responseDigest:d,openedAtMs:r})}if(e.order.operation==="cancel")return e.store.transition(s,"sent",km(e.venue,c.value,i)?"cancel-pending":"uncertain",{responseDigest:d,observedAtMs:r});let u;try{u=Om(e.venue,c.value,i)}catch{return e.store.transition(s,"sent","uncertain",{responseDigest:d,observedAtMs:r})}let m=["cancelled","rejected","filled"].includes(u.status);if(m||u.status==="partial"){e.store.transition(s,"sent","settlement-pending",{responseDigest:d,observedAtMs:r,status:u.status,filledQuote:u.filledQuote});let f=m&&(u.status==="cancelled"||u.status==="rejected")&&/^0(?:\.0+)?$/.test(u.filledQuote)?"release":"commit";return await t.settleLedger({tradeId:i.tradeId,filledQuote:u.filledQuote,disposition:f}),e.store.transition(s,"settlement-pending","terminal",{settledAtMs:r})}return e.store.transition(s,"sent","open",{responseDigest:d,observedAtMs:r,status:u.status,filledQuote:u.filledQuote})}function Ha(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||Ao,nowMs:e.nowMs||Date.now,settleLedger:e.settleLedger});return Object.freeze({execute:r=>Tm(r,t)})}import{createHash as Nm,createHmac as za,randomBytes as Cm,timingSafeEqual as _m}from"node:crypto";var Ua="oracle-local-signer-cex-owner-allow-v1",Ft=e=>/^(?:0|[1-9]\d{0,19})$/.test(String(e||""))?String(e):null,Wa=e=>JSON.stringify(e),Rm=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&_m(r,n)};function Va({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(Ft).filter(Boolean));if(!n.size)throw new Error("cex owner proof: approved owner context required");let o=new Set,i=l=>{let a=Buffer.from(L(e));try{return l(a)}finally{a.fill(0)}},s=i(l=>Nm("sha256").update("cex-owner-instance\0").update(l).digest("hex"));return Object.freeze({mint({digest:l,senderId:a,chatId:c,platform:d,ttlMs:u=15e3}={}){let m=Ft(a),f=Ft(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(l||""))||!Number.isSafeInteger(u)||u<1||u>3e4)throw new Error("cex owner proof: binding refused");let w={version:1,decision:"Allow",digest:l,ownerSenderId:m,telegramChatId:f,audience:Ua,instance:s,nonce:Cm(16).toString("hex"),issuedAtMs:p,expiresAtMs:p+u},g=i(h=>za("sha256",h).update(Wa(w)).digest("hex"));return{claims:w,mac:g}},verify(l,{digest:a}={}){let c=l?.claims,d=r();if(!c||c.version!==1||c.decision!=="Allow"||c.digest!==a||c.audience!==Ua||c.instance!==s||!/^[0-9a-f]{32}$/.test(c.nonce||"")||Ft(c.ownerSenderId)!==Ft(c.telegramChatId)||!n.has(Ft(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 u=i(m=>za("sha256",m).update(Wa(c)).digest("hex"));return Rm(l.mac,u)?(o.add(c.nonce),!0):!1}})}var Re=new Co(["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"]),Ka=new Co(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),ko=new Co(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function Mm({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 s=n.then(i,i);return n=s.then(()=>{},()=>{}),s};return Object.freeze({armGeneration:()=>r,disarm:()=>o(()=>(r+=1,t(),!0)),broadcastWithArmFence:(i,s)=>o(async()=>{if(i!==r||!e())throw new Error("signer: disarmed generation changed before broadcast handoff");return s()})})}function qm(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||re.join(process.env.XDG_STATE_HOME||re.join(Lm.homedir(),".local","state"),"oracle"),r=$m("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 Hm(e){try{return L(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=Pm(32).toString("hex");return Ae(e,t+`
23
+ `),t}function Oo(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 Ga(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 Ya(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function zm(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 Um(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 s=n?.transactions;if(!Array.isArray(s)||s.length!==1)throw new Error("signer: exact Anvil action transaction required");let l=t==="buy"?"buySpecificNFT":"sellNFT",a;try{if(a=Re.decodeFunctionData(l,s[0].data),Re.encodeFunctionData(l,[a[0],a[1]]).toLowerCase()!==String(s[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${t} calldata required`)}if(BigInt(a[0])!==BigInt(e.tokenId)||BigInt(a[1])!==i)throw new Error(`signer: exact Anvil ${t} calldata limit mismatch`);return i}async function ze(e,t,r,n,o,i=[]){let s=await e.send("eth_call",[{to:t,data:r.encodeFunctionData(n,i)},o]);return r.decodeFunctionResult(n,s)[0]}async function Wm(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"),s=_e(t.contract,"Anvil collection"),l=_e(t.paymentToken,"Anvil payment token"),a=BigInt(t.nativeSwapFeeWei),c=Number(t.paymentTokenDecimals),d=_e(o,"Anvil signer identity"),u=_e(t.owner,"Anvil envelope owner");if(d!==u)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=zm(t,f),w=Um(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(Ya(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=Ya(r.nftPaymentTokenCaps,l);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 x=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(x))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let A=BigInt(x),k=await e.send("eth_getBlockByNumber",[x,!1]),v=String(k?.hash||"").toLowerCase();if(String(k?.number||"").toLowerCase()!==x||!/^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=jm(C).toLowerCase();if(z!==h)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[U,R,$]=await Promise.all([ze(e,i,Re,"collection",_),ze(e,i,Re,"token",_),ze(e,i,Re,"robinhoodSwapFeeWei",_)]),Ke=_e(U,"live Anvil collection"),pt=_e(R,"live Anvil payment token"),Mt=BigInt($).toString();if(Ke!==s)throw new Error("signer: live Anvil collection mismatch");if(pt!==l)throw new Error("signer: live Anvil payment token mismatch");if(Mt!==a.toString())throw new Error("signer: live Anvil native swap fee mismatch");let qt=Number(await ze(e,pt,Ka,"decimals",_));if(!Number.isSafeInteger(qt)||qt!==c)throw new Error("signer: live Anvil payment token decimals mismatch");let mt=_e(await ze(e,Ke,ko,"ownerOf",_,[m]),"live Anvil token owner"),Ge=null,Ye=null,Xe=null,Ze=null,M;if(f==="buy"){let[Ue,wt,E]=await Promise.all([ze(e,i,Re,"inventory",_,[m]),ze(e,pt,Ka,"allowance",_,[d,i]),e.send("eth_call",[{to:i,data:Re.encodeFunctionData("quoteSpecificBuy",[m])},_])]);Ge=!!Ue,Ye=BigInt(wt).toString();let I=Re.decodeFunctionResult("quoteSpecificBuy",E);if(M=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(M)!==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(!M.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(M.totalCostRaw)!==w)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(M.totalCostRaw)!==BigInt(M.baseCostRaw)+BigInt(M.feeRaw)+BigInt(M.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[Ue,wt,E]=await Promise.all([ze(e,Ke,ko,"getApproved",_,[m]),ze(e,Ke,ko,"isApprovedForAll",_,[d,i]),e.send("eth_call",[{to:i,data:Re.encodeFunctionData("quoteSellNFT")},_])]);Xe=_e(Ue,"live Anvil token approval"),Ze=!!wt;let I=Re.decodeFunctionResult("quoteSellNFT",E);if(M=Object.freeze({netPayoutRaw:BigInt(I[0]).toString(),grossPayoutRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString()}),JSON.stringify(M)!==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(M.netPayoutRaw)!==w)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(M.netPayoutRaw)+BigInt(M.feeRaw)+BigInt(M.protocolFeeRaw)!==BigInt(M.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:qt,nativeSwapFeeWei:Mt,signerAddress:d,nftAction:f,tokenId:m.toString(),tokenOwner:mt,inventoryMember:Ge,allowanceRaw:Ye,approvedAddress:Xe,approvedForAll:Ze,quote:M,blockNumber:A.toString(),blockHash:v,runtimeCodeHash:z,verifiedAtMs:Number(n)})}function Xa(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 Vm(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:s}={}){let l=Dm(new URL("./anvil-attestation-worker.mjs",import.meta.url)),a={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},c;try{c=Bm(process.execPath,[l],{input:JSON.stringify({rpcUrl:e,chainId:t,envelope:r,policy:a,nowMs:Number(o),signerAddress:s}),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)}async function ur(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 No(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 To(e,t){let r=Array.isArray(t)?t:[t],n=No(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 Jm({provider:e=null,readPolicy:t,rpc:r=ur,fetchImpl:n=fetch}={}){if(typeof t!="function")throw new TypeError("signer: execution observer requires readPolicy");return async o=>{let i=String(o?.surface||""),s=String(o?.signedTransactionId||"");if(!s)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 a=await e.getTransactionReceipt(s);return a?{transactionHash:s,status:a.status}:null}let l=t();if(i==="hl"){let{owner:a,cloid:c}=o;if(!/^0x[0-9a-f]{40}$/i.test(String(a))||!/^0x[0-9a-f]{32}$/i.test(String(c)))return null;let d=o.hlTestnet===!0?"https://api.hyperliquid-testnet.xyz/info":"https://api.hyperliquid.xyz/info",u=await n(d,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"orderStatus",user:a,oid:c})});if(!u.ok)return null;let m=await u.json();if(m?.status!=="order"||m.order?.order?.cloid!==c)return null;let{status:f,order:p}=m.order;if(f==="filled")return{transactionHash:s,status:1,order:{orderId:String(p.oid),status:"filled",cloid:c}};let w=y=>/^\d+(?:\.\d+)?$/.test(String(y))?String(y).replace(/^0+(?=\d)/,"").replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""):null,g=w(p.origSz),h=w(p.sz);return(/^(?:canceled|rejected|scheduledCancel)$/.test(f)||/(?:Canceled|Rejected)$/.test(f))&&g!==null&&Number(g)>0&&g===h?{transactionHash:s,status:0}:null}if(i==="sol"){let a=String(l.solRpcUrl||l.solanaRpcUrl||"");if(!a)return null;let d=(await r(a,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[s],{searchTransactionHistory:!0}]}))?.value?.[0];return d?d.err?{transactionHash:s,status:0}:d.confirmationStatus==="confirmed"||d.confirmationStatus==="finalized"||d.confirmations===null?{transactionHash:s,status:1}:null:null}if(i==="btc"){let a=String(l.btcRpcUrl||l.bitcoinRpcUrl||"").replace(/\/$/,"");if(!a)return null;try{let c=a.endsWith("/tx")?a.slice(0,-3):a,d=await n(`${c}/tx/${s}/status`);if(d.ok)return(await d.json())?.confirmed===!0?{transactionHash:s,status:1}:null}catch{}try{let c=await r(a,{jsonrpc:"1.0",id:"oracle",method:"getrawtransaction",params:[s,!0]});return Number(c?.confirmations||0)>0?{transactionHash:s,status:1}:null}catch{return null}}return null}}async function Qa(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 ur(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function Km(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 s=await fetch(`${o}/tx/${t}/outspend/${r}`);if(s.ok){let l=await s.json();if(l?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(l?.spent===!1)return!0}}catch(s){if(/already spent/.test(String(s?.message||s)))throw s}if(!await Qa(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Gm(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 Ym(e,t,{fetchImpl:r=fetch}={}){return{simulate:async(n,o)=>(Pe(o,e()),!0),sign:async(n,o)=>{Pe(o,e());let i=e();if(!(Array.isArray(i.owners)?i.owners:[]).some(l=>String(l).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(o.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return n?.typedData?(qi(n),t.signTypedData(n.typedData.domain,n.typedData.types,n.typedData.message)):Hi({wallet:t,action:n.action,nonce:n.nonce,isMainnet:!String(n.submitTo||"").includes("testnet")})},broadcast:async(n,o,i)=>{Pe(i,e());let{Signature:s,keccak256:l}=await import("ethers"),a=s.from(n),c=await r(o.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:o.action,nonce:o.nonce,signature:{r:a.r,s:a.s,v:a.v}})});if(!c.ok)throw new Error("signer: Hyperliquid exchange rejected the action");let d=await c.json().catch(()=>{throw new Error("signer: Hyperliquid exchange rejected the action")});if(d?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");let u=o.action.type==="order"?d.response?.data?.statuses?.[0]:null;if(u&&Object.hasOwn(u,"error"))throw new Error("signer: Hyperliquid rejected the order");let m=u?.filled?"filled":u?.resting?"resting":null,f=m?u[m]:null;return{hash:l(n),status:1,...f?.oid!=null?{order:{orderId:String(f.oid),status:m,cloid:o.action.orders[0].c??null}}:{}}}}}function Xm(e){return{simulate:async(t,r)=>(De(r,e()),!0),sign:async(t,r)=>{De(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 er(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=De(n,e()),i=er(r,t),s=Wi(i),l=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s}),a=await l.json().catch(()=>({}));if(!l.ok||Number(a?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(a?.tx_hash||a?.txHash||"lighter"),status:1}}}}function Zm(e,t){return{simulate:async(r,n)=>(rt(n,e()),!0),sign:async(r,n)=>{rt(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 s=r.domain||r.typedData.domain,l=r.types||r.typedData.types,a=r.message||r.typedData.message;return t.signTypedData(s,l,a)},broadcast:async(r,n,o)=>{let i=rt(o,e()),{keccak256:s}=await import("ethers"),l=n.message||n.typedData.message,a=i.kind==="cow"?{sellToken:l.sellToken,buyToken:l.buyToken,receiver:l.receiver,sellAmount:l.sellAmount,buyAmount:l.buyAmount,validTo:l.validTo,appData:l.appData,feeAmount:l.feeAmount,kind:l.kind,partiallyFillable:l.partiallyFillable,sellTokenBalance:l.sellTokenBalance,buyTokenBalance:l.buyTokenBalance,from:o.owner,signature:r,signingScheme:"eip712",quoteId:n.quoteId??void 0}:{orderHash:i.digest,signature:r,data:l},c=await fetch(i.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a)}),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:s(r),status:1,orderHash:i.digest,uid:typeof d=="string"?d:d?.uid||null}}}}function Qm(e,t){return{simulate:async(r,n)=>(Be(n,e()),!0),sign:async(r,n)=>{Be(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).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(),s=Be(o,i),l=En(i),{keccak256:a}=await import("ethers"),c=di({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:l.key}),d=JSON.stringify(c),u=li({creds:l,address:o.owner,method:"POST",path:"/order",body:d}),m=await fetch(s.submitTo,{method:"POST",headers:u,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:a(r),status:1}}}}function ew(e,t){let r=go(t);return{simulate:async n=>{let o=e(),i=Io.fromPSBT(Buffer.from(n.psbt,"base64"));return await Promise.all(Array.from({length:i.inputsLength},(s,l)=>{let a=i.getInput(l),c=Buffer.from(a.txid||[]).toString("hex");return Km(o,c,a.index)})),!0},sign:n=>{let o=Io.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 s=Io.fromPSBT(Buffer.from(n,"base64"));s.finalize(),s.extract();let l;try{let c=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:s.hex});if(l=(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;l=await Qa(o,"sendrawtransaction",[s.hex])}if(l&&String(l).toLowerCase()!==s.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let a=null;try{let c=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${c}/tx/${s.id}/status`);d.ok&&(a=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:s.id,status:a}}}}function tw(e,t){let r=go(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 s=Buffer.from(n.messageBase64,"base64"),l=No(s),a=To(s,Array.from({length:l},()=>new Uint8Array(64))),c=await ur(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[a,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Gm(c)},sign:n=>{let o=Buffer.from(n.messageBase64,"base64"),i=No(o),s=Fm.sign(o,r);if(i===1)return To(o,[s]);let l=Array.isArray(n.cosignatures)?n.cosignatures:[];if(l.length!==i-1)throw new Error(`signer: Solana message needs ${i-1} cosignature(s), got ${l.length}`);return To(o,[s,...l.map(a=>Buffer.from(String(a),"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 s=await ur(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),a=(await ur(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[s],{searchTransactionHistory:!0}]}))?.value?.[0];if(a?.err)return{hash:s,status:0};let c=a?.confirmationStatus==="confirmed"||a?.confirmationStatus==="finalized"||a?.confirmations===null;return{hash:s,status:c?1:null}}}}function rw(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 nw(e,t,r,n,{submitPrivate:o}={}){if((await e.getNetwork()).chainId!==BigInt(r.chainId))throw new Error("signer: RPC chain mismatch");let s={native:(await e.getBalance(r.from)).toString()},l=n&&n.privateRelay;if(l&&typeof o=="function"){let u=l==="require"||l?.mode==="require";try{let m=await o(t,{chainId:Number(r.chainId),requirePrivate:u,allowPublicFallback:!u});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:s,verifiedAfter:p,submission:{path:"private",mode:m.mode,endpoint:m.endpoint}}}}catch(m){if(u)throw m}}let a=await e.broadcastTransaction(t),c=await a.wait(),d={native:(await e.getBalance(r.from)).toString()};return{hash:c?.hash??a.hash,status:c?.status??null,verifiedBefore:s,verifiedAfter:d,submission:{path:"public"}}}async function ec({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:s=12e4}={}){let{JsonRpcProvider:l,Wallet:a}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(s<1e3||s>12e4)throw new Error("signer: session must be at most 120 seconds");let c=qm(e),d=()=>Object.freeze(Xr(c.policy,c.policyKey,{sequenceAnchorFile:c.policyAnchor})),u=d(),m=String(process.env.ORACLE_OWNER_TELEGRAM||"").split(",").map(E=>E.trim()).filter(Boolean),f=m.length?Va({keyFile:c.policyKey,approvedTelegramOwners:m}):null;if(K(u,"cex")&&!f)throw new Error("signer: cex requires an approved Telegram owner context");if(!["exact-human","auto-within-rails"].includes(u.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(u.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"];u.surfaces.some(E=>String(E).startsWith("evm"))&&p.push("chains","spenders");for(let E of p)if(!Array.isArray(u[E])||u[E].length===0)throw new Error(`signer: ${E} allowlist is empty`);if(u.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-nft"||E==="evm-order")){for(let E of["providers"])if(!Array.isArray(u[E])||u[E].length===0)throw new Error(`signer: ${E} allowlist is empty`)}if(u.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-order")&&(!Array.isArray(u.tokens)||u.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(u.surfaces.some(E=>String(E).startsWith("evm")&&E!=="evm-order")&&(!Array.isArray(u.selectors)||u.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(u.surfaces.includes("sol")&&(!Array.isArray(u.programs)||u.programs.length===0))throw new Error("signer: programs allowlist is empty");if(K(u,"poly")&&(En(u),!Array.isArray(u.polyTokens)||u.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(K(u,"lighter")&&(!Array.isArray(u.lighterMarkets)||u.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(K(u,"cex")&&(!u.cexAccounts||Object.keys(u.cexAccounts).length===0))throw new Error("signer: cexAccounts allowlist is empty");if(K(u,"hl")){let E=Array.isArray(u.coins)?u.coins.map(String):[],I=Array.isArray(u.hlMarkets)?u.hlMarkets:[];if(E.filter(F=>F!=="*"&&F!=="#*").length&&!E.includes("*")&&I.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let w=r?Sa(r):L(t),g=da(c.vault),h=ua(g,w),y;try{y=Ca(h,g.meta)}finally{h.fill(0)}if((Ga(u)||K(u,"hl")||K(u,"poly"))&&Oo("evm",y.evm,u.owners),K(u,"btc")&&Oo("btc",y.btc,u.owners),K(u,"sol")&&Oo("sol",y.sol,u.owners),K(u,"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(u.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(u.chains)?u.chains.filter(E=>Number.isInteger(Number(E))&&String(E).trim()!==""):[],x=Ga(u);if(x&&(b.length!==1||!u.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(K(u,"btc")&&!(u.btcRpcUrl||u.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(K(u,"sol")&&!(u.solRpcUrl||u.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let A=x?new l(u.rpcUrl,Number(b[0])):null,k=y.evm&&(x||K(u,"hl")||K(u,"poly"))?A?new a(y.evm.secret).connect(A):new a(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)=>nw(A,E,I,T,{submitPrivate:pa})}:null,_=A?async E=>ow(A,E):void 0,C=new Map,z=E=>E?.surface==="evm-nft"&&String(E?.provider).toLowerCase()==="anvil-nft",U=async(E,I=d(),T="execution")=>{if(!z(E))return null;let F=await Wm(A,E,I,{nowMs:Date.now(),signerAddress:k.address}),Y=C.get(G(E));return Y&&Xa(Y,F,T),F},R={...v?{evm:v,"evm-swap":v,"evm-bridge":v,"evm-nft":v}:{},...k&&K(u,"evm-order")?{"evm-order":Zm(d,k)}:{},...y.btc?{btc:ew(d,y.btc)}:{},...y.sol?{sol:tw(d,y.sol)}:{},...k&&K(u,"hl")?{hl:Ym(d,k)}:{},...k&&K(u,"poly")?{poly:Qm(d,k)}:{},...K(u,"lighter")?{lighter:Xm(d)}:{}};rw(R,n);let $=Fi({...R,...n}),Ke=new Set(Object.keys(R)),pt=new Set(Object.keys(n||{})),Mt=u.surfaces.filter(E=>E!=="cex"&&!Ke.has(E)&&!pt.has(E));if(Mt.length)throw new Error(`signer: ${Mt.join(",")} require local keys or injected surface transports`);let qt=Date.now(),mt=qt+s,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:Ja.existsSync(c.lock)?(Ge=!0,!1):Ja.existsSync(c.vault)&&Date.now()<mt,M=Mm({isArmed:Ze,disarmNow:()=>{Ge=!0,Xe(),Ae(c.lock,`disarmed ${new Date().toISOString()}
24
+ `)}}),Ue=os({host:o,port:i,token:Hm(c.token),policy:u,readPolicy:d,isArmed:Ze,disarm:M.disarm,armGeneration:M.armGeneration,broadcastWithArmFence:M.broadcastWithArmFence,sessionExpiresAtMs:mt,executionOutbox:bs({path:c.executionOutbox,now:Date.now}),observeExecutionTransaction:Jm({provider:A,readPolicy:d}),nowMs:Date.now,simulate:async(E,I)=>(await U(I,d(),"before simulation"),vr(I,$).simulate(E,I)),estimateNetworkFees:_,sign:async(E,I)=>(await U(I,d(),"before signing"),vr(I,$).sign(E,I)),verifySigned:(E,I,T)=>Yi(T?.surface||"evm",E,I,T),broadcast:async(E,I,T)=>(await U(T,d(),"before broadcast"),vr(T,$).broadcast(E,I,T)),confirmArtifact:async(E,I,T)=>{let F=await U(E,T),Y=await sw(E,I,T,F);return Y===!0&&F&&C.set(I,F),Y},decodeEconomics:(E,I)=>Cn(E,I),reserveLedger:(E,I,T={})=>{let F=E?.version===1&&E?.surface?E:null,Y=F?.artifact||E;if(z(F)){let Qe=G(F),We=C.get(Qe);if(!We||Date.now()-Number(We.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let Ht=Vm(I.rpcUrl,Y.chainId,F,I,{nowMs:Date.now(),signerAddress:k.address});Xa(We,Ht,"before reservation"),C.set(Qe,Ht)}let dr=F?.tradeId||Y?.tradeId;if(!dr)throw new Error("ledger: executable artifact requires a tradeId");let ye;if(F)ye=Cn(F,I);else{if(Y?.value===void 0)throw new Error("ledger: executable artifact value required");let Qe=BigInt(Y.value),We=BigInt(Y.gasLimit??0),Ht=BigInt(Y.maxFeePerGas??Y.gasPrice??0);if(We<=0n||Ht<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let _o=We*Ht+BigInt(Y.l1FeeWei??0)+BigInt(Y.operatorFeeWei??0);ye={unit:"wei",value:Qe.toString(),notional:(Qe+_o).toString(),fee:_o.toString()}}if(Array.isArray(ye.units))return ar({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:dr,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 ar({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:dr,...ye,policy:I,retryReleasedTradeId:T.retryReleasedTradeId})},commitLedger:E=>ha({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),releaseLedger:E=>ga({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),settleFailedLedger:E=>ba({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),validateReservation:(E,I,T)=>wa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,reservation:E,policy:I,economics:T}),verifyFeeWaiver:(E,I)=>xa(E,I,c.policyKey),verifyTriggerAttestation:(E,I,T)=>Ea(E,I,c.policyKey,T),inspectCex:Qr,verifyOwnerProof:f?(E,I)=>f.verify(E,I):void 0,verifyCexOwnerProof:f?(E,I)=>f.verify(E,I):void 0,cexExecute:K(u,"cex")?async E=>{let I=d(),T=Qr(E,I,Date.now()),F=T.kind==="spot-limit-create"?"create":T.kind==="spot-limit-cancel"?"cancel":"status";F==="create"&&Ra({envelope:E,paths:c,nowMs:Date.now()});let Y=F==="create"?{operation:F,symbol:T.symbol,side:T.side,baseSize:T.baseSize,limitPrice:T.limitPrice,clientOrderId:T.clientOrderId}:{operation:F,symbol:T.symbol,venueOrderId:T.venueOrderId};return Ha({credential:ye=>y.cex[ye],settleLedger:({tradeId:ye,disposition:Qe,filledQuote:We})=>ya({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ye,expectedUnit:T.unit,filledQuote:We,disposition:Qe})}).execute({venue:T.venue,accountId:T.accountId,credentialRef:T.credentialRef,tradeId:T.tradeId,reservedNotional:T.notional,order:Y,store:Pa({file:c.cexOrders,keyFile:c.policyKey,anchorFile:c.cexOrdersAnchor})})}:void 0,ledgerObserver:sa(process.env)?aa({path:c.workflowLedger,telemetry:la(process.env),onError:E=>{try{console.error(`signer: ${E}`)}catch{}}}):null,autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),wt=setTimeout(()=>Ue.close(),s);return wt.unref(),Ue.on("close",()=>{clearTimeout(wt),Xe()}),Ue.listen(i,o),Ue}var rn="0x420000000000000000000000000000000000000F";function Za(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 ow(e,t){if(!ke(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 s;try{let l=await e.call({to:rn,data:o.encodeFunctionData("getL1Fee",[i])});s=o.decodeFunctionResult("getL1Fee",l)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:s,operatorFeeWei:await iw(e,o,t.gasLimit)}}async function iw(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:rn,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Za(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:rn,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:rn,data:t.encodeFunctionData("operatorFeeConstant")}),s=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),l=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*s/1000000n+l).toString()}catch(o){if(!Za(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function sw(e,t,r,n=null){return process.stdin.isTTY?(process.stderr.write(br(e,t,r,n)),process.stdin.resume(),new Promise(o=>{let i=s=>{process.stdin.off("data",i),process.stdin.pause(),o(String(s).trim()===t)};process.stdin.once("data",i)})):!1}var tc=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
25
25
  Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,nn=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function cw(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(tc+`
26
26
  `),0;let r=nn(e,"--passphrase-file"),n=await ec({configDir:aw.join(t.configDir||pr(),"signer"),passphraseFile:r,credentialService:nn(e,"--credential-service"),port:Number(nn(e,"--port",9462)),sessionMs:Number(nn(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
27
27
  `),await new Promise(o=>n.on("close",o)),0}var bx={name:"signer",summary:"run the short-lived loopback signer",usage:tc,run:e=>cw(e.argv||[])};export{bx as default,cw as run};