@oracle-agent/oracle 0.35.39 → 0.35.41
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.
- package/dist/agent-sessions.mjs +11 -11
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +28 -28
- package/dist/bin/oracle-data-mcp.mjs +19 -19
- package/dist/bin/oracle-gateway.mjs +43 -43
- package/dist/bin/oracle-investigate.mjs +5 -5
- package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-shadow.mjs +6 -6
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +18 -18
- package/dist/bin/oracle-scan.mjs +11 -11
- package/dist/cli/commands/agent-session.mjs +18 -18
- package/dist/cli/commands/airdrop.mjs +8 -8
- package/dist/cli/commands/chat.mjs +207 -207
- package/dist/cli/commands/doctor.mjs +9 -9
- package/dist/cli/commands/eval.mjs +147 -197
- package/dist/cli/commands/farm.mjs +17 -17
- package/dist/cli/commands/follow.mjs +17 -17
- package/dist/cli/commands/mint.mjs +10 -10
- package/dist/cli/commands/model.mjs +211 -211
- package/dist/cli/commands/quickstart.mjs +6 -6
- package/dist/cli/commands/receipt.mjs +12 -12
- package/dist/cli/commands/resolve.mjs +7 -7
- package/dist/cli/commands/sign.mjs +4 -4
- package/dist/cli/commands/signer.mjs +14 -14
- package/dist/cli/commands/snipe.mjs +9 -9
- package/dist/cli/commands/strategy.mjs +4 -4
- package/dist/cli/commands/swap.mjs +14 -14
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +26 -26
- package/dist/data/names.mjs +3 -3
- package/dist/data/providers/farming.mjs +2 -2
- package/dist/data/providers/lp-destination-discovery.mjs +4 -4
- package/dist/index.mjs +44 -44
- package/dist/investigator/index.mjs +2 -2
- package/dist/launch-radar/index.mjs +5 -5
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/index.mjs +2 -2
- package/dist/local-signer/runtime.mjs +8 -8
- package/dist/nft/universal-mint-router.mjs +4 -4
- package/dist/notifications/index.mjs +7 -7
- package/dist/router/index.mjs +3 -3
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/router/prepare-route.mjs +3 -3
- package/dist/scanner/index.mjs +4 -4
- package/dist/strategy/index.mjs +3 -3
- package/dist/teams/index.mjs +6 -6
- package/dist/tui/standalone-client.mjs +82 -82
- package/package.json +4 -4
- package/public/eval-report.json +3 -3
- package/public/oracle-splash/_variants/ice.html +2 -4
- package/public/oracle-splash/_variants/ivory.html +2 -4
- package/public/oracle-splash/assets/fonts/LICENSE-Cormorant-Garamond.txt +93 -0
- package/public/oracle-splash/assets/fonts/LICENSE-IBM-Plex-Mono.txt +93 -0
- package/public/oracle-splash/assets/fonts/LICENSE-Outfit.txt +93 -0
- package/public/oracle-splash/assets/fonts/LICENSE-UnifrakturCook.txt +94 -0
- package/public/oracle-splash/assets/fonts/font-provenance.json +426 -0
- package/public/oracle-splash/assets/fonts/oracle-font-00.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-01.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-02.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-03.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-04.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-05.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-06.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-07.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-08.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-09.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-10.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-11.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-12.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-13.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-14.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-15.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-16.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-17.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-18.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-19.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-20.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-21.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-22.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-23.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-24.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-25.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-26.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-font-27.woff2 +0 -0
- package/public/oracle-splash/assets/fonts/oracle-fonts.css +504 -0
- package/public/oracle-splash/assets/transport-probe-sw.js +2 -0
- package/public/oracle-splash/docs/browser-and-web/index.html +6 -6
- package/public/oracle-splash/docs/connectors/index.html +5 -5
- package/public/oracle-splash/docs/docs.css +4 -4
- package/public/oracle-splash/docs/docs.js +119 -7
- package/public/oracle-splash/docs/getting-started/index.html +5 -5
- package/public/oracle-splash/docs/index.html +6 -6
- package/public/oracle-splash/docs/reference/index.html +5 -5
- package/public/oracle-splash/docs/security/index.html +5 -5
- package/public/oracle-splash/docs/using-oracle/index.html +5 -5
- package/public/oracle-splash/download/index.html +8 -10
- package/public/oracle-splash/downloads/index.html +3 -5
- package/public/oracle-splash/eval/index.html +96 -0
- package/public/oracle-splash/index.html +16 -18
- package/public/oracle-splash/mesh-graph.svg +1 -1
- package/public/oracle-splash/pricing/index.html +6 -8
- package/public/oracle-splash/security/index.html +3 -5
- package/public/oracle-splash/what-it-does/index.html +4 -6
- package/public/oracle-splash/where-it-works/index.html +3 -5
- package/server.json +2 -2
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
var Za=(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 Qa from"node:os";import gt from"node:path";import{fileURLToPath as ec}from"node:url";function No(){return process.env.ORACLE_FAKE_HOME||Qa.homedir()}function rc(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function pr(){return rc()?process.env.ORACLE_CONFIG_DIR||gt.join(No(),".config","oracle"):gt.join(No(),".config","oracle")}function nc(){return gt.join(pr(),"desk.json")}function oc(){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=oc();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=nc();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 tc,dw,Co=Za(()=>{tc=gt.dirname(ec(import.meta.url)),dw=gt.resolve(tc,"../..");try{ht()}catch{}});Co();import ow from"node:path";import za from"node:fs";import re from"node:path";import Nm from"node:os";import{createHash as Cm,randomBytes as _m}from"node:crypto";import{execFileSync as Lm}from"node:child_process";import{fileURLToPath as Rm}from"node:url";import{Interface as Oo,keccak256 as $m}from"ethers";import{Transaction as So}from"@scure/btc-signer";import{ed25519 as Pm}from"@noble/curves/ed25519.js";import Bl from"node:http";import{timingSafeEqual as Dl}from"node:crypto";import{createHash as Sl,randomBytes as Al,timingSafeEqual as vl}from"node:crypto";import{base58 as qi}from"@scure/base";import{Interface as bi}from"ethers";import{Interface as Ec,MaxUint256 as xc,isAddress as Sc,keccak256 as Gw,toUtf8Bytes as Yw}from"ethers";import{Interface as yc,isAddress as Cw}from"ethers";import{isAddress as vw}from"ethers";import{createHash as uc,createHmac as lc,timingSafeEqual as dc}from"node:crypto";import{readFileSync as ic}from"node:fs";import{homedir as sc}from"node:os";import{join as mr}from"node:path";function ac(){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=sc();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 ac())try{let i=ic(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 ${cc(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 cc(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 rn(e){return Array.isArray(e)?`[${e.map(rn).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${rn(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function fc(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 pc(e){let{signature:t,...r}=e;return r}function mc(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 uc("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function wc(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:dc(r,n)}function hc(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 nn(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=fc(o,{required:s});if(s&&!u)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(u){let p=lc("sha256",u).update(rn(pc(e))).digest("hex");if(!wc(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=hc(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==mc(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 $w=new yc(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as bc,isAddress as Dw}from"ethers";var Mw=new bc(["function approve(address spender,uint256 amount) returns (bool)"]),Hw=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function U(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=U(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 M(e,t,r="amount"){let n=U(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 rh=new Ec(["function approve(address spender,uint256 amount) returns (bool)"]);function Lo(e,t){let r=String(e||"").trim();if(!Sc(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Ac(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>=xc)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var Ro=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),vc=new Set(["0x39509351","0xf9255c1f"]);function oe(e){let t=String(e||"").toLowerCase();return t.length<10?!1:Ro.has(t.slice(0,10))}function Re(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:Lo(s,"approval spender"),token:a==null?null:Lo(a,"approval token"),amount:Ac(u,"approval amount",{allowZero:!0}),selector:r,additive:vc.has(r)}}import{createHash as Ic,createHmac as ih,timingSafeEqual as sh}from"node:crypto";var kc=2,on=300*1e3,$o=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function Oc(e){let t=e==null||e===""?on:Number(e);return!Number.isFinite(t)||t<0?on:Math.min(t,$o)}function sn(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(sn).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${sn(e[r])}`).join(",")}}`}function Tc(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function Nc(e){let t=Tc(e);return Ic("sha256").update(sn(t)).digest("hex")}function Po(e,{maxAgeMs:t=on,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)!==kc)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=Nc(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=Oc(t),d=r-u,l=a-u;if(!Number.isFinite(d)||!Number.isFinite(a)||!Number.isFinite(l)||d<0||l<=0||l>$o||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 Wt=e=>String(e||"").toLowerCase(),Cc=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","authorizationList","slippageBps","expiresAtMs"]),_c=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function ve(e){try{return _c.has(BigInt(e))}catch{return!1}}var fe=(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`)}},Bo=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},bt=(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 wr(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=>!Cc.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`);bt(p.address,t.destinations,"destination",Wt);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(fe(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(bt(e.to,t.destinations,"destination",Wt),bt(String(e.data||"0x").slice(0,10),t.selectors,"selector",f=>String(f).toLowerCase()),bt(e.from,t.owners,"owner",Wt),oe(e.data)){let f;try{f=Re(e.data)}catch(w){throw new Error(`policy: malformed approval calldata: ${w?.message||w}`)}bt(f.spender,t.spenders,"spender",Wt),bt(f.token||e.to,t.erc20Tokens,"ERC-20 token",Wt);let p=fe(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(fe(e.value,"value")>fe(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=fe(e.gasLimit,"gasLimit");if(s>fe(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let u=e.maxFeePerGas??e.gasPrice,a=fe(u,"feePerGas")*s,c=0n;try{if(ve(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+=fe(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(c+=fe(e.operatorFeeWei,"operatorFeeWei")),ve(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=fe(n.l1FeeWei,"estimated l1FeeWei")+fe(n.operatorFeeWei,"estimated operatorFeeWei");if(c<f)throw new Error("policy: rollup fee attestation understates estimate")}if(a+c>fe(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=Bo(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=Bo(t.maxTtlMs??12e4,"maxTtlMs");if(m<=0||e.expiresAtMs-r>m)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as Do}from"node:crypto";import{Address as Lc,NETWORK as Rc,OutScript as Fo,RawTx as $c,SigHash as jo,TEST_NETWORK as Pc,Transaction as Bc}from"@scure/btc-signer";var qo=(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`)}},Dc=(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},Fc=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,jc=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),et=e=>jc(e)?String(e).toLowerCase():String(e),an=(e,t)=>Array.isArray(t)&&t.some(r=>et(r)===et(e)),qc=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function Mc(e){let t=Buffer.from($c.encode(e)),r=Do("sha256").update(t).digest();return Buffer.from(Do("sha256").update(r).digest()).reverse().toString("hex")}function Hc(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(Mc(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)||!qc(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function cn(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(!an(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?Rc:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?Pc:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Bc.fromPSBT(Dc(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=Lc(n);for(let l=0;l<o.inputsLength;l++){let m=o.getInput(l);for(let w of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(Fc(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=Hc(m),p;try{let w=Fo.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(!an(p,t.owners)||et(p)!==et(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let s=new Set([e.owner,...t.changeAddresses||[]].map(l=>et(l))),u=0n,a=!1,c=[];for(let l=0;l<o.outputsLength;l++){let m=o.getOutput(l),f;try{f=i.encode(Fo.decode(m.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let p=et(f);if(c.push(`${f}:${m.amount}`),p===et(e.destination)){a=!0,u+=m.amount;continue}if(an(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>qo(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(u>qo(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 un(e,t){let{unit:r,value:n,notional:o,fee:i}=cn(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as dn}from"node:crypto";import{base58 as Vo}from"@scure/base";import{getCompiledTransactionMessageDecoder as zc}from"@solana/transaction-messages";var yr="11111111111111111111111111111111",Jo="ComputeBudget111111111111111111111111111111",Wc="So11111111111111111111111111111111111111112",Ko="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var Go="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Uc=5000n,Vc=2039280n,Jc=37095705934669439343138083508754565189542113879843219016388785533085940283555n,X=57896044618658097711785492504343953926634992332820282019728792003956564819949n,Mo=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Ho=e=>dn("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Kc=new Map([[Ho("route"),{name:"route",prefixBytes:0}],[Ho("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`)}},Gc=(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},we=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),H=e=>String(e||""),Yc=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,gr=e=>dn("sha256").update(e).digest("hex");function hr(e,t){try{let r=Buffer.from(Vo.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function pe(e){let t=e%X;return t>=0n?t:X+t}function Ie(e,t){let r=e;for(;t-- >0n;)r=r*r%X;return r}function Xc(e){let r=e*e%X*e%X,n=Ie(r,2n)*r%X,o=Ie(n,1n)*e%X,i=Ie(o,5n)*o%X,s=Ie(i,10n)*i%X,u=Ie(s,20n)*s%X,a=Ie(u,40n)*u%X,c=Ie(a,80n)*a%X,d=Ie(c,80n)*a%X,l=Ie(d,10n)*i%X;return Ie(l,2n)*e%X}function Zc(e,t){let r=pe(t*t*t),n=pe(r*r*t),o=Xc(e*n),i=pe(e*r*o),s=pe(t*i*i),u=i,a=pe(i*Mo),c=s===e,d=s===pe(-e),l=s===pe(-e*Mo);return c&&(i=u),(d||l)&&(i=a),(pe(i)&1n)===1n&&(i=pe(-i)),!c&&!d?null:i}function Qc(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=pe(t*t),n=Zc(pe(r-1n),pe(Jc*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function eu(e,t){let r=Buffer.concat([...e,hr(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=dn("sha256").update(r).digest();if(Qc(n))throw new Error("envelope: derived Solana program address is on curve");return Vo.encode(n)}function fn(e,t,r=Ko){let n=[hr(e,"owner"),hr(r,"token program"),hr(t,"mint")];for(let o=255;o>=0;o--)try{return eu([...n,Buffer.from([o])],Go)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function tu(e,t){return(t.accountIndices||[]).map(r=>H(e.staticAccounts[r]))}function Ut(e){return Buffer.from(e.data||[])}function ru(e,t){return H(e.staticAccounts[t.programAddressIndex])}function Yo(e,t){return Number(t)<e.header.numSignerAccounts}function nu(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 Vt(e){return e.accountIndices||[]}function ln(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=Vt(t).map(n=>{let o=Yo(e,n)?"s":"n",i=nu(e,n)?"w":"r";return`${n}:${H(e.staticAccounts[n])}:${o}:${i}`});return gr(Buffer.from(r.join(`
|
|
1
|
+
var Za=(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 Qa from"node:os";import gt from"node:path";import{fileURLToPath as ec}from"node:url";function No(){return process.env.ORACLE_FAKE_HOME||Qa.homedir()}function rc(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function pr(){return rc()?process.env.ORACLE_CONFIG_DIR||gt.join(No(),".config","oracle"):gt.join(No(),".config","oracle")}function nc(){return gt.join(pr(),"desk.json")}function oc(){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=oc();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=nc();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 tc,dw,Co=Za(()=>{tc=gt.dirname(ec(import.meta.url)),dw=gt.resolve(tc,"../..");try{ht()}catch{}});Co();import ow from"node:path";import za from"node:fs";import re from"node:path";import Nm from"node:os";import{createHash as Cm,randomBytes as _m}from"node:crypto";import{execFileSync as Rm}from"node:child_process";import{fileURLToPath as Lm}from"node:url";import{Interface as Oo,keccak256 as $m}from"ethers";import{Transaction as So}from"@scure/btc-signer";import{ed25519 as Pm}from"@noble/curves/ed25519.js";import Bl from"node:http";import{timingSafeEqual as Dl}from"node:crypto";import{createHash as Sl,randomBytes as Al,timingSafeEqual as vl}from"node:crypto";import{base58 as qi}from"@scure/base";import{Interface as bi}from"ethers";import{Interface as Ec,MaxUint256 as xc,isAddress as Sc,keccak256 as Gw,toUtf8Bytes as Yw}from"ethers";import{Interface as yc,isAddress as Cw}from"ethers";import{isAddress as vw}from"ethers";import{createHash as uc,createHmac as lc,timingSafeEqual as dc}from"node:crypto";import{readFileSync as ic}from"node:fs";import{homedir as sc}from"node:os";import{join as mr}from"node:path";function ac(){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=sc();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 ac())try{let i=ic(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 ${cc(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 cc(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 rn(e){return Array.isArray(e)?`[${e.map(rn).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${rn(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function fc(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 pc(e){let{signature:t,...r}=e;return r}function mc(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 uc("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function wc(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:dc(r,n)}function hc(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 nn(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=fc(o,{required:s});if(s&&!u)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(u){let p=lc("sha256",u).update(rn(pc(e))).digest("hex");if(!wc(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=hc(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==mc(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 $w=new yc(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as bc,isAddress as Dw}from"ethers";var Mw=new bc(["function approve(address spender,uint256 amount) returns (bool)"]),Hw=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function U(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=U(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 M(e,t,r="amount"){let n=U(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 rh=new Ec(["function approve(address spender,uint256 amount) returns (bool)"]);function Ro(e,t){let r=String(e||"").trim();if(!Sc(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Ac(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>=xc)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var Lo=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),vc=new Set(["0x39509351","0xf9255c1f"]);function oe(e){let t=String(e||"").toLowerCase();return t.length<10?!1:Lo.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:Ro(s,"approval spender"),token:a==null?null:Ro(a,"approval token"),amount:Ac(u,"approval amount",{allowZero:!0}),selector:r,additive:vc.has(r)}}import{createHash as Ic,createHmac as ih,timingSafeEqual as sh}from"node:crypto";var kc=2,on=300*1e3,$o=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function Oc(e){let t=e==null||e===""?on:Number(e);return!Number.isFinite(t)||t<0?on:Math.min(t,$o)}function sn(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(sn).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${sn(e[r])}`).join(",")}}`}function Tc(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function Nc(e){let t=Tc(e);return Ic("sha256").update(sn(t)).digest("hex")}function Po(e,{maxAgeMs:t=on,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)!==kc)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=Nc(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=Oc(t),d=r-u,l=a-u;if(!Number.isFinite(d)||!Number.isFinite(a)||!Number.isFinite(l)||d<0||l<=0||l>$o||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 Wt=e=>String(e||"").toLowerCase(),Cc=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","authorizationList","slippageBps","expiresAtMs"]),_c=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function ve(e){try{return _c.has(BigInt(e))}catch{return!1}}var fe=(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`)}},Bo=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},bt=(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 wr(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=>!Cc.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`);bt(p.address,t.destinations,"destination",Wt);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(fe(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(bt(e.to,t.destinations,"destination",Wt),bt(String(e.data||"0x").slice(0,10),t.selectors,"selector",f=>String(f).toLowerCase()),bt(e.from,t.owners,"owner",Wt),oe(e.data)){let f;try{f=Le(e.data)}catch(w){throw new Error(`policy: malformed approval calldata: ${w?.message||w}`)}bt(f.spender,t.spenders,"spender",Wt),bt(f.token||e.to,t.erc20Tokens,"ERC-20 token",Wt);let p=fe(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(fe(e.value,"value")>fe(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=fe(e.gasLimit,"gasLimit");if(s>fe(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let u=e.maxFeePerGas??e.gasPrice,a=fe(u,"feePerGas")*s,c=0n;try{if(ve(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+=fe(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(c+=fe(e.operatorFeeWei,"operatorFeeWei")),ve(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=fe(n.l1FeeWei,"estimated l1FeeWei")+fe(n.operatorFeeWei,"estimated operatorFeeWei");if(c<f)throw new Error("policy: rollup fee attestation understates estimate")}if(a+c>fe(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=Bo(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=Bo(t.maxTtlMs??12e4,"maxTtlMs");if(m<=0||e.expiresAtMs-r>m)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as Do}from"node:crypto";import{Address as Rc,NETWORK as Lc,OutScript as Fo,RawTx as $c,SigHash as jo,TEST_NETWORK as Pc,Transaction as Bc}from"@scure/btc-signer";var qo=(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`)}},Dc=(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},Fc=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,jc=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),et=e=>jc(e)?String(e).toLowerCase():String(e),an=(e,t)=>Array.isArray(t)&&t.some(r=>et(r)===et(e)),qc=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function Mc(e){let t=Buffer.from($c.encode(e)),r=Do("sha256").update(t).digest();return Buffer.from(Do("sha256").update(r).digest()).reverse().toString("hex")}function Hc(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(Mc(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)||!qc(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function cn(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(!an(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?Lc:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?Pc:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Bc.fromPSBT(Dc(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=Rc(n);for(let l=0;l<o.inputsLength;l++){let m=o.getInput(l);for(let w of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(Fc(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=Hc(m),p;try{let w=Fo.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(!an(p,t.owners)||et(p)!==et(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let s=new Set([e.owner,...t.changeAddresses||[]].map(l=>et(l))),u=0n,a=!1,c=[];for(let l=0;l<o.outputsLength;l++){let m=o.getOutput(l),f;try{f=i.encode(Fo.decode(m.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let p=et(f);if(c.push(`${f}:${m.amount}`),p===et(e.destination)){a=!0,u+=m.amount;continue}if(an(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>qo(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(u>qo(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 un(e,t){let{unit:r,value:n,notional:o,fee:i}=cn(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as dn}from"node:crypto";import{base58 as Vo}from"@scure/base";import{getCompiledTransactionMessageDecoder as zc}from"@solana/transaction-messages";var yr="11111111111111111111111111111111",Jo="ComputeBudget111111111111111111111111111111",Wc="So11111111111111111111111111111111111111112",Ko="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var Go="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Uc=5000n,Vc=2039280n,Jc=37095705934669439343138083508754565189542113879843219016388785533085940283555n,X=57896044618658097711785492504343953926634992332820282019728792003956564819949n,Mo=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Ho=e=>dn("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Kc=new Map([[Ho("route"),{name:"route",prefixBytes:0}],[Ho("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`)}},Gc=(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},we=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),H=e=>String(e||""),Yc=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,gr=e=>dn("sha256").update(e).digest("hex");function hr(e,t){try{let r=Buffer.from(Vo.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function pe(e){let t=e%X;return t>=0n?t:X+t}function Ie(e,t){let r=e;for(;t-- >0n;)r=r*r%X;return r}function Xc(e){let r=e*e%X*e%X,n=Ie(r,2n)*r%X,o=Ie(n,1n)*e%X,i=Ie(o,5n)*o%X,s=Ie(i,10n)*i%X,u=Ie(s,20n)*s%X,a=Ie(u,40n)*u%X,c=Ie(a,80n)*a%X,d=Ie(c,80n)*a%X,l=Ie(d,10n)*i%X;return Ie(l,2n)*e%X}function Zc(e,t){let r=pe(t*t*t),n=pe(r*r*t),o=Xc(e*n),i=pe(e*r*o),s=pe(t*i*i),u=i,a=pe(i*Mo),c=s===e,d=s===pe(-e),l=s===pe(-e*Mo);return c&&(i=u),(d||l)&&(i=a),(pe(i)&1n)===1n&&(i=pe(-i)),!c&&!d?null:i}function Qc(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=pe(t*t),n=Zc(pe(r-1n),pe(Jc*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function eu(e,t){let r=Buffer.concat([...e,hr(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=dn("sha256").update(r).digest();if(Qc(n))throw new Error("envelope: derived Solana program address is on curve");return Vo.encode(n)}function fn(e,t,r=Ko){let n=[hr(e,"owner"),hr(r,"token program"),hr(t,"mint")];for(let o=255;o>=0;o--)try{return eu([...n,Buffer.from([o])],Go)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function tu(e,t){return(t.accountIndices||[]).map(r=>H(e.staticAccounts[r]))}function Ut(e){return Buffer.from(e.data||[])}function ru(e,t){return H(e.staticAccounts[t.programAddressIndex])}function Yo(e,t){return Number(t)<e.header.numSignerAccounts}function nu(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 Vt(e){return e.accountIndices||[]}function ln(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=Vt(t).map(n=>{let o=Yo(e,n)?"s":"n",i=nu(e,n)?"w":"r";return`${n}:${H(e.staticAccounts[n])}:${o}:${i}`});return gr(Buffer.from(r.join(`
|
|
2
2
|
`)))}function Wo(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function ou(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function iu(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function su(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 au(e,t){let r=Ut({data:e}),n=r.subarray(0,8).toString("hex"),o=Kc.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=iu(r,u,"route plan length"),l=r.subarray(a,c),m=su(l,d,t);return Object.freeze({instruction:o.name,routeId:s,routePlanSteps:d,routePlan:m,routePlanHash:gr(l),inAmount:Wo(r,c,"in_amount"),quotedOutAmount:Wo(r,c+8,"quoted_out_amount"),slippageBps:ou(r,c+16,"slippage_bps"),platformFeeBps:r[c+18],instructionHash:gr(r)})}function cu(e,t,r){let n=tu(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 Uo(e,t){return e&&e!==t?e:null}function me(e,t,r){let n=H(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function uu(e,t){let r=Ut(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 lu(e,t,r,n,o,i){let s=Ut(t);if(s.length!==1||s[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let u=Vt(t);if(u.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let a=me(e,u[0],"ATA payer"),c=me(e,u[1],"ATA account"),d=me(e,u[2],"ATA owner"),l=me(e,u[3],"ATA mint"),m=me(e,u[4],"ATA system program"),f=me(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!==fn(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:c,debit:i}}function du(e,t,r,n,o){let i=Vt(t),s=Ut(t);if(i.length!==2||s.length!==12||s.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let u=me(e,i[0],"wrap payer"),a=me(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 fu(e,t,r,n){let o=Vt(t),i=Ut(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||me(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=me(e,o[0],"closeAccount source"),u=me(e,o[1],"closeAccount destination"),a=me(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=fn(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<Vc)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=ru(e,f);if(p===Jo)uu(f,r);else if(p===Go){let{ata:w,debit:g}=lu(e,f,t,t.artifact,s,a);c.set(w,g)}else if(p===yr)d+=du(e,f,t,u,i);else if(p===s){let w=fu(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 mu(e){let t;try{t=zc().decode(Gc(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 wu(e,t,r,n=1){if(e.header.numSignerAccounts!==n||H(e.staticAccounts[0])!==t.owner||!we(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||!we(s,r.programs))throw new Error("policy: Solana program not allowed");o.push(s)}return o}function hu(e,t,r){let n=ie(r.lamportsPerSignature,"lamportsPerSignature");if(n<Uc)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 gu(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||!we(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 yu(e,t,r,n){let o=t.artifact,i=H(o.mintProgram);if(!we(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(we(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!==Jo){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(!we(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 bu(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!==Wc)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!we(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Yc(r);if(!we(o.inputMint,i)||!we(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||!we(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=au(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(!ln(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=Vt(l),g=m.instruction==="shared_accounts_route"?2:1;if(!Yo(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:[Ko];if(!we(p.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let y=fn(t.owner,o.outputMint,p.tokenProgram);if(p.userDestinationTokenAccount!==y)throw new Error("envelope: Jupiter destination token account is not owner ATA");let b=Uo(p.destinationTokenAccount,c);if(b&&b!==y)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(Uo(p.platformFeeAccount,c))throw new Error("policy: Jupiter platform fee account not allowed");if(!ln(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(!ln(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 pn(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(!we(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=mu(r),i=wu(o,e,t,e.action==="mint"?o.header.numSignerAccounts:1),s=e.action==="transfer"?gu(o,e,t,i):e.action==="mint"?yu(o,e,t,i):bu(o,e,t,i),u=hu(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 mn(e,t){let{unit:r,value:n,notional:o,fee:i,unverifiableProgramSpend:s,visibleSpendLamports:u}=pn(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})}var Ah=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,vh=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Ih=AbortSignal.prototype.throwIfAborted,kh=EventTarget.prototype.addEventListener,Oh=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null;var Th=64*1024,Nh=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});var xu=1e8;var jh=Object.freeze({tradexyz:"xyz",ventuals:"vntl",hypernova:"hyna",paradex:"para",entropy:"io",entropyio:"io"});function wn(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=xu+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var Su=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),Au=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),vu=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"}),Iu=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"}),ze=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function ku(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 Xo(e,t){let r=U(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 ke(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=>ke(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)}:${ke(e[n],t)}`).join(",")}}`}function Ou(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)||ke(r,"declared order type")!==ke({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(ke(r,"declared order type")!==ke({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||ke(r,"declared order type")!==ke({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 Tu(e,t,r){let n=Xo(e.s,"signed size"),o=Xo(e.p,"signed price"),i=n.decimals+o.decimals,s=n.raw*o.raw,u=M(t.notionalUsd,i,"hl: notionalUsd");if(u<=0n||s!==u)throw new Error("hl: signed notional must match");let a=M(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>a)throw new Error("hl: notional exceeds cap")}function Nu(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=ze(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=M(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function Zo(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(U(e.s,"hl: signed size")!==U(t.size,"hl: size"))throw new Error("hl: signed size must match");if(U(e.p,"hl: signed price")!==U(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(ke(e.t,"signed order type")!==ke(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 Qo(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(U(e.s,"hl: bracket protection size")!==U(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(U(e.p,"hl: bracket protection price")!==U(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(U(i.triggerPx,"hl: triggerPx")!==U(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function Cu(e){let t=String(e||"").replace(/\/$/,"");if(!Su.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function hn(e){return wn(e)!=null}function _u(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(hn(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 Lu(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(hn(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 We(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=ze(r.kind,"kind",48),o=vu[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=Cu(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!==Iu[n])throw new Error("hl: action type must match kind");let u=r.notionalUsd??0;if(Au.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let a=ze(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=wn(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(_u(a,t),Lu(a,c,t),n==="hip4-order"&&!hn(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");Ou(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");Zo(d[0],r,c);let p=1;l!=null&&Qo(d[p++],r,c,l,"tp"),m!=null&&Qo(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");Zo(d[0],r,c)}Tu(d[0],r,t),Nu(r,t),u=U(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=ze(r.usd,"margin usd",64),l=M(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=M(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),p=l<0n?-l:l;if(p>f)throw new Error("hl: margin notional exceeds cap");u=ku(p,6)}}if(n==="builder-fee-approval"){let a=ze(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(a))throw new Error("hl: builder address required");if(ze(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=ze(r.maxFeeRate,"maxFeeRate",32);if(ze(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=M(d.slice(0,-1),12,"hl: builder fee percent"),m=M(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 Ru}from"node:crypto";var Et="0x"+"00".repeat(32);function gn(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 ei({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=Ru("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 $u(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 Pu(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 ti(e,t){let r=de(e.makerAmount,"poly: makerAmount"),n=de(e.takerAmount,"poly: takerAmount");return Pu(t==="BUY"?r:n)}function Bu(e){let t=typeof e=="bigint"?e.toString(10):U(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 ri({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=$u(e,t);if(ne(e.metadata||Et,"poly: metadata").toLowerCase()!==Et)throw new Error("poly: metadata must be zero");if(ne(e.builder||Et,"poly: builder").toLowerCase()!==Et)throw new Error("poly: builder must be zero");let s=Bu(e.salt);return{deferExec:!1,order:{builder:Et,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:Et,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 Du=new Set(["https://clob.polymarket.com/order"]),Jt=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Gh=Object.freeze(Jt.map(e=>e[0])),Fu=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),ju="0xe111180000d2663c0091e4f400237545b87b996b",qu="0xe2222d279d744050d28e00520010520000310f59",ni=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function oi(e){let t=String(e||"").replace(/\/$/,"");if(!Du.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function ii(e){let t=ne(e,"poly: exchange").toLowerCase();if(!Fu.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function Ue(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=ni(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(oi(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(ii(o.verifyingContract),ii(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?qu:ju;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!==Jt.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let v=0;v<Jt.length;v+=1)if(u[v]?.name!==Jt[v][0]||u[v]?.type!==Jt[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=ni(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=M(r.quantity,6,"poly: quantity");if(y<=0n||y!==h)throw new Error("poly: quantity must match CLOB v2 amounts");let b=M(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(M(r.notionalUsdc,6,"poly: notionalUsdc")!==g)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let A=ti(s,l);if(M(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=M(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:oi(r.submitTo)})}var Mu=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),yn=14,si=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function xt(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function bn(e){let t=String(e||"").replace(/\/$/,"");if(!Mu.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function Ve(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=si(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=bn(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");xt(r.orderType,0,"orderType"),xt(r.timeInForce,1,"timeInForce"),xt(r.reduceOnly,0,"reduceOnly"),xt(r.triggerPrice,0,"triggerPrice"),xt(r.orderExpiry,-1,"orderExpiry");let a=si(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=M(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=M(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,g,"lighter: maxNotionalUsd");if(h>b)throw new Error("lighter: notional exceeds cap");let S=U(r.notionalUsd,"lighter: notionalUsd");return xt(r.txType,yn,"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)})}import{TypedDataEncoder as ui,getAddress as be}from"ethers";import{TypedDataEncoder as eg,getAddress as tg,isAddress as rg}from"ethers";var ai=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),En=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 pg,getAddress as mg,isAddress as wg}from"ethers";var ig=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});var ci=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Sg=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var xn=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"}]}),Ag=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});var zu=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"]),Wu="0x0000000000000000000000000000000000000000";function Sn(e,t,r=256){if(typeof e!="string"||!e||e.length>r)throw new Error(`evm-order: bounded ${t} required`);return e}function li(e,t){let r=String(e||"").replace(/\/$/,"");if(!zu.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 di(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 fi(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 pi(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 mi(e,t,{allowZero:r=!1}={}){let n=String(t||"").toLowerCase();if(!n)throw new Error("evm-order: receiver required");if(n===Wu){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 tt(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=Sn(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(di(r.submitTo,l),Sn(e.destination,"destination",32)!=="cowswap")throw new Error("evm-order: cow destination must be cowswap");let m=ci[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(!fi(p,xn))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();mi(g,w.receiver),pi(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:di(r.submitTo,l),digest:ui.hash(f,{Order:xn.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(Sn(e.destination,"destination",32)!=="1inch-lop")throw new Error("evm-order: destination must be 1inch-lop");let o=Number(r.chainId??e.chainId),i=ai[o];if(!i)throw new Error(`evm-order: unsupported chainId ${o}`);li(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(!fi(u,En))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");mi(c,a.receiver,{allowZero:!0}),pi(t,a.makerAsset,a.takerAsset);let d=ui.hash(s,{Order:En.Order},a);return Object.freeze({unit:`erc20:${be(a.makerAsset).toLowerCase()}`,value:String(a.makingAmount),notional:String(a.makingAmount),fee:"0",submitTo:li(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 Ei=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]);var An=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}),Uu=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),xi=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"}}),Vu=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),br=new bi(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),wi=new bi(["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"]),Ju=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 Gt=(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`)}},hi=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ku=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},Y=(e,t,r)=>{if(!Ku(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Kt=(e,t,r)=>{Array.isArray(t)&&t.length&&Y(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},rt=e=>String(e||"0x").slice(0,10).toLowerCase(),Si=e=>N(e.gasLimit,"gasLimit")*N(e.maxFeePerGas??e.gasPrice,"feePerGas")+N(e.l1FeeWei??0,"l1FeeWei")+N(e.operatorFeeWei??0,"operatorFeeWei");function St(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 Z(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 Gu(e){if(rt(e)!=="0x095ea7b3")return null;let t=St(e,2,"approval");return{kind:"approval",spender:Z(t.word(0),"approval spender"),amount:Ee(t.word(1),"approval amount")}}function Ai(e,t){let r=t==="router02-exact-input-single"?7:8,n=St(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:Z(n.word(0),"input token"),outputToken:Z(n.word(1),"output token"),recipient:Z(n.word(3),"recipient"),amountIn:Ee(n.word(o),"amountIn"),minimumOut:Ee(n.word(o+1),"amountOutMinimum")}}function Yu(e){let t=St(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:Z(t.word(0),"depositor"),recipient:Z(t.word(1),"recipient"),inputToken:Z(t.word(2),"input token"),outputToken:Z(t.word(3),"output token"),amountIn:Ee(t.word(4),"inputAmount"),minimumOut:Ee(t.word(5),"outputAmount"),destinationChainId:Ee(t.word(6),"destinationChainId")}}function Xu(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 gi(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}=Xu(`0x${f}`);return{kind:"action",action:"swap",inputToken:p,outputToken:w,recipient:Z(a,"recipient"),amountIn:c,minimumOut:d}}function Zu(e){let t=St(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:Z(t.word(0),"input token"),outputToken:Z(t.word(1),"output token"),recipient:Z(t.word(3),"recipient"),amountIn:Ee(t.word(5),"amountIn"),minimumOut:Ee(t.word(6),"amountOutMinimum")}}function Qu(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=rt(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Ai(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function el(e,t){let r=rt(e),n=xi[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{...Ai(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...gi(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...gi(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...Qu(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Zu(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...Yu(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function tl(e){let t=St(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:Z(t.word(0),"mint NFT contract"),feeRecipient:Z(t.word(1),"mint fee recipient"),recipient:Z(t.word(2),"mint recipient"),quantity:Ee(t.word(3),"mint quantity")}}function rl(e){let t;try{t=wi.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(wi.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 nl(e,t){let r=rt(e);if(String(t).toLowerCase()==="nft-mint")return ol(e);let n=Vu[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{...tl(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 ol(e){let t=rt(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=Ju[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=St(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 Er(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 vi(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??Er(e)[0]?.chainId);if(!Number.isSafeInteger(a)||a<=0)throw new Error("envelope: explicit batch chainId required");if(Y(a,t.chains,"chain"),u?.owner!==void 0&&P(u.owner,"batch owner")!==s)throw new Error("envelope: explicit batch owner mismatch");let c=Er(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(Y(rt(f.data),t.selectors,"selector"),d+=N(f.value??0,"value"),l+=N(f.gasLimit,"gasLimit"),m+=Si(f),ve(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 Ii(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=Gt(e.provider,"provider",64).toLowerCase();Y(i,t.providers,"provider");let s=vi(e,t,o,{nowMs:r}),u=[],a=-1;for(let p=0;p<s.transactions.length;p++){let w=s.transactions[p],g=Gu(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(Y(S,t.tokens,"token"),Y(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");Y(w.to,t.destinations,"destination"),h={...el(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:Si(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(Y(c.inputToken,t.tokens,"input token"),Y(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(nn(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([...Uu,...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 il(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 yi(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 ki(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=Gt(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Kt(n,t.providers,"provider");let o=vi(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");Y(p,t.destinations,"destination");let w=P(e.contract??e.artifact?.contract,"NFT contract");if(Kt(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");Kt(h,t.erc20Tokens,"ERC20 token");let y=il(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=Gt(e.nftAction,"nftAction",8).toLowerCase(),k;if(A==="buy"){let v=yi(e,A),_=Object.entries(t.nftPaymentTokenCaps||{}).find(([W])=>W.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=br.decodeFunctionData("buySpecificNFT",f.data);if(br.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=yi(e,A),z=br.decodeFunctionData("sellNFT",f.data);if(br.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&&Po(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=rt(s.data);Y(u,t.selectors,"selector"),Y(s.to,t.destinations,"destination");let a=nl(s.data,n),c=P(e.contract??e.artifact?.contract,"NFT contract");if(Kt(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&&Kt(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 sl(e,{localsWaiver:t=!1}={}){if(!(e in An))throw new Error("fee: unknown action");return t?0:An[e]}function Yt(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=Gt(e.surface,"surface",16);if(!Ei.has(u))throw new Error("envelope: unsupported public surface");let a=Gt(e.action,"action",32);Y(u,t.surfaces,"surface"),Y(a,t.actions,"action"),Y(e.owner,t.owners,"owner"),Y(e.destination,t.destinations,"destination");let c=hi(t.maxTtlMs,"maxTtlMs"),d=hi(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")Ii(e,t,{nowMs:r,routeAttestationSecret:o});else if(u==="evm-nft")ki(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");wr({...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"?un(e,t):u==="sol"?mn(e,t):u==="hl"?We(e,t):u==="poly"?Ue(e,t):u==="lighter"?Ve(e,t):u==="evm-order"&&tt(e,t);let m=Number(e.fee?.oracleFeeBps)===0&&An[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=sl(a,{localsWaiver:m});if(Number(e.fee?.oracleFeeBps)!==f)throw new Error("fee: final artifact fee mismatch");return!0}var vn=Object.freeze([...Ei]),qg=Object.freeze({...xi});function In(e,t){if(e.surface==="hl")return We(e,t);if(e.surface==="poly")return Ue(e,t);if(e.surface==="lighter")return Ve(e,t);if(e.surface==="evm-order")return tt(e,t);if(e.surface==="btc")return un(e,t);if(e.surface==="sol")return mn(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Ii(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=ki(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 Oi(e={}){let t={};for(let r of vn){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 xr(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 $i}from"node:crypto";import{ed25519 as gl}from"@noble/curves/ed25519.js";import{base58 as Bi}from"@scure/base";import{RawTx as _n,SigHash as nt,Transaction as Ln}from"@scure/btc-signer";import{Transaction as Rn,keccak256 as Nn,verifyTypedData as Cn}from"ethers";import{encode as al}from"@msgpack/msgpack";import{keccak256 as cl,verifyTypedData as ul}from"ethers";var At=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),kn=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Ti(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 ll(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(al(e)),Ti(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]),Ti(n)),cl(Buffer.concat(i))}function On(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:ll(e,t,{vaultAddress:n,expiresAfter:o})}}function Ni(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=On(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==At.name||String(t.domain?.version)!==At.version||Number(t.domain?.chainId)!==At.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(At.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(kn.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 Ci({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=On(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(At,kn,s)}function _i({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:s=null}){try{let u=On(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:s}),a=ul(At,kn,u,e);return String(a).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var dl=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function Tn(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)Tn(t);return}for(let t of Object.values(e))Tn(t)}}}function fl(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 Tn(e),JSON.parse(JSON.stringify(e))}function Sr(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 pl(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 Li(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 It(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=>Li(e[s],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function ml(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 vt(e,t,r,n){let o=It(e,t,n);if(BigInt(o)!==Sr(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function wl(e,t,r,n){let o=It(e,t,n,{signed:!0});if(BigInt(o)!==pl(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function hl(e){let t={};for(let[r,n]of dl.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 Li(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 Xt(e,t){let r=fl(t),n=vt(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=vt(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=vt(r,["Type","type"],e.orderType,"Type"),s=vt(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),u=vt(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),a=vt(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),c=wl(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=It(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=It(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),m=It(r,["Price","price"],"Price");if(BigInt(d)!==Sr(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==Sr(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(m)!==Sr(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let f=ml(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=It(r,["txType","tx_type","TxType"],"txType");if(g!==yn)throw new Error("lighter: signed txType must be official create-order");let h={...hl(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:bn(e.submitTo)}}function Ri(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var kt=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},Ar=e=>String(e||"").toLowerCase();function yl(e,t){if(typeof e!="string")return!1;let r,n;try{r=Rn.from(e),n=Rn.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 Ar(r.from)!==Ar(t.from)||Ar(r.to)!==Ar(t.to)?!1:r.unsignedHash===n.unsignedHash}function bl(e){let t=Buffer.from(_n.encode(e)),r=$i("sha256").update(t).digest();return Buffer.from($i("sha256").update(r).digest()).reverse().toString("hex")}function Pi(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||bl(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 El(e,t){let r=kt(e),n=kt(t.psbt);if(!r||!n)return!1;try{let o=Ln.fromPSBT(n),i=Ln.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(!Pi(a)||!Pi(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(_n.encode(h)).equals(Buffer.from(_n.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!==nt.DEFAULT&&u.sighashType!==nt.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===nt.ALL,m=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===nt.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]===nt.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]!==nt.ALL&&b[64]!==nt.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 Di(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=kt(e),o=kt(t.messageBase64);if(!n||!o)return!1;let i=Di(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=Bi.decode(String(r));return c.length===32&&gl.verify(u,a,c)}catch{return!1}}function Fi(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(Cn(o,i,s,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}}if(String(e).startsWith("evm"))return yl(t,r);if(e==="btc")return El(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(Cn(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return _i({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(Cn(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Xt(r,t),!0}catch{return!1}return!1}function ji(e,t){try{if(e==="evm-order")return Nn(t);if(String(e).startsWith("evm"))return Rn.from(t).hash;if(e==="btc"){let r=kt(t);if(!r)return null;let n=Ln.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=kt(t);if(!r)return null;let n=Di(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Bi.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return Nn(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return Nn(t)}catch{}return null}var Il=e=>String(e||"").toLowerCase();function Q(e){return Sl("sha256").update(JSON.stringify(e)).digest("hex")}function kr(e,t,r={}){return wr(e,t,r)}async function kl(e,t={}){if(!ve(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 Mi(e,t,r=!1){if(!ve(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 Hi(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 vr=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=Al(32).toString("hex");return this.#e.set(i,{digest:Q(t),owner:Il(r),expiresAtMs:this.now()+n,binding:Hi(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(Q(r),"hex");if(!vl(i,s))throw new Error("confirmation: artifact mismatch");if(JSON.stringify(o.binding)!==JSON.stringify(Hi(n)))throw new Error("confirmation: execution binding mismatch");return this.#e.delete(String(t)),o}clear(){this.#e.clear()}};function Ol(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 Tl(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 Nl(e){return e==="evm"||e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Ir(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=qi.decode(r);return n.length===64&&qi.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 zi(e,t,r){return!Ir(e,t)||!Ir(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function Cl(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 $n({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:s,nowMs:u}){let a=Cl(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 _l(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Ll(e,t){return e&&_l(e.surface)?Er(e):[t]}function Rl(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!zi(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function $l(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:Tl(r,n)}}function Pl(e){return Number.isSafeInteger(e)&&e>0?"commit":"settle-failed"}async function Pn(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=Ll(s,u),c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,d=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),l=await $n({artifact:e,envelope:s,nonce:t,deps:r,policy:c,confirmation:null,consumeNonce:!0,nowMs:d}),m=Q(e),f=(b={})=>{s?Yt(s,c,b):(kr(u,c,{nowMs:b.nowMs,networkFees:b.networkFees,requireNetworkFees:b.requireNetworkFees}),Ol(u))},p=async b=>{let S=!s||Nl(s.surface),A=S?await kl(b,r):void 0;return{nowMs:d(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:A,requireNetworkFees:S&&ve(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)&&Mi(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 $n({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",_=ji(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(Q(e)!==m)throw new Error("signer: artifact mutated after signing");c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,l=await $n({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)&&Mi(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),W=o?await r.broadcastWithArmFence(i,z):await z(),L=W?.status,$=Rl(W,v);if(!zi(v,$,_))throw new Error("signer: receipt transaction hash does not match signed bytes");if(L===0||L==="0x0")throw Ir(v,$)?(r.executionAttempt&&await r.executionAttempt.recordCanonicalReceipt({txIndex:b,receipt:W}),Pl(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(L!==1&&L!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Ir(v,$))throw new Error("signer: successful broadcast requires a valid transaction hash");r.executionAttempt&&await r.executionAttempt.recordCanonicalReceipt({txIndex:b,receipt:W}),h.push($l(W,$))}}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 Wi=new Set(["127.0.0.1","::1","localhost"]),Fl=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Dl(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 jl(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 Ot=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)}),Ui=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},ql=e=>e==="btc"||e==="sol"||["evm","evm-swap","evm-bridge","evm-nft"].includes(e);function Vi(e={}){let t=e.host||"127.0.0.1";if(!Wi.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 vr,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 Bl.createServer(async(c,d)=>{try{let l=String(c.headers.authorization||"").replace(/^Bearer /i,"");if(!Fl(l,e.token))return O(d,401,{error:"unauthorized"});let m=jl(c.headers.host);if(!Wi.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(vn),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 Ot(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)Yt(p,w,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:b,...S}=p||{};kr(S,w,{nowMs:g})}let h=Q(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 Ot(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 Pn(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 Ot(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 Ot(c);if(f.artifact?.surface==="cex")return O(d,403,{error:"cex requires pending owner ack"});let p=Q(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)Yt(f.artifact,w,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:h,...y}=f.artifact||{};kr(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:Ui(f)})})}if(c.method==="POST"&&c.url==="/execute/reconcile"){let f=await Ot(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 Ot(c);if(f.artifact?.surface==="cex")return O(d,403,{error:"cex requires pending owner ack"});let p=typeof e.executeArtifact=="function"?e.executeArtifact:Pn;if(f.idempotencyKey!==void 0){if(!ql(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 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:Ui(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}),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 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 Or,constants as Je,fchmodSync as Ki,fsyncSync as Dn,lstatSync as ts,mkdirSync as Zl,openSync as Fn,readFileSync as rs,renameSync as Ql,rmSync as Gi,writeFileSync as Yi}from"node:fs";import{randomBytes as jn}from"node:crypto";import{dirname as ed,resolve as td}from"node:path";import{wordlists as Ml}from"ethers";var Hl=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),zl=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Wl=new Set([12,15,18,21,24]);function Ul(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Wl.has(t.length)&&t.every(r=>Ml.en.getWordIndex(r)>=0)}var Vl=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,Jl=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,Kl=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function Gl(e){let t=Ji(e);return Kl.has(t)||Jl.test(t)}var Zt=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function Ji(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Yl(e){let t=Ji(e);return[...Hl].some(r=>t.includes(r))}function Xl(e,t,r){if(typeof t=="string"){if(zl.some(n=>n.test(t))||Ul(t))throw new Zt(r);if(Vl.test(t)&&!Gl(e))throw new Zt(r)}}function Bn(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return Xl(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)=>Bn(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(Yl(o))throw new Zt(i);e[o]!==void 0&&(n[o]=Bn(e[o],i,o))}return n}function Tt(e){return Bn(e)}var ns=2,Xi=Je.O_NOFOLLOW??0;function he(e){return e==null?e:structuredClone(e)}function Zi(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function os(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 Qi(e){Zl(e,{recursive:!0,mode:448}),os(ts(e),"execution outbox directory",!0)}function rd(){return{version:ns,attempts:{}}}function is(e){if(!e||e.version!==ns||!e.attempts||typeof e.attempts!="object"||Array.isArray(e.attempts))throw new Error("execution outbox is invalid");return Tt(e),he(e)}function es(e){try{let t=ts(e);if(os(t,"execution outbox file"),t.size>16*1024*1024)throw new Error("execution outbox is too large");return is(JSON.parse(rs(e,"utf8")))}catch(t){if(t?.code==="ENOENT")return rd();throw t}}function nd(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 od(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 Nt(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 ss(e){if(!Number.isSafeInteger(e)||e<1)return null;try{let t=rs(`/proc/${e}/stat`,"utf8");return t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[19]||null}catch{return null}}function id(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=ss(t);return n===null?!1:n===r}function sd(e){return e.transactions.length>0&&e.transactions.length===e.transactionCount&&e.transactions.every(t=>t?.state==="confirmed"||t?.state==="failed")}function ad(e,t){sd(e)&&(e.state=e.transactions.some(r=>r.state==="failed")?"failed":"receipts-confirmed",e.receiptsRecordedAtMs=t())}function as({path:e,now:t=Date.now,leaseOwner:r,isLeaseOwnerAlive:n=id}={}){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:ss(process.pid)||"pid-only"};if(!Number.isSafeInteger(Number(o.pid))||!String(o.startToken||""))throw new Error("execution lease owner identity is unavailable");let i=td(e),s=ed(i),u=`${i}.lock`;function a(d){Qi(s);let l,m=!1,f=`${i}.${process.pid}.${jn(8).toString("hex")}.tmp`,p;try{l=Fn(u,Je.O_CREAT|Je.O_EXCL|Je.O_WRONLY|Xi,384),m=!0,Yi(l,`${process.pid}
|
|
3
|
+
`)));if(!ln(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 pn(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(!we(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=mu(r),i=wu(o,e,t,e.action==="mint"?o.header.numSignerAccounts:1),s=e.action==="transfer"?gu(o,e,t,i):e.action==="mint"?yu(o,e,t,i):bu(o,e,t,i),u=hu(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 mn(e,t){let{unit:r,value:n,notional:o,fee:i,unverifiableProgramSpend:s,visibleSpendLamports:u}=pn(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})}var Ah=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,vh=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Ih=AbortSignal.prototype.throwIfAborted,kh=EventTarget.prototype.addEventListener,Oh=EventTarget.prototype.removeEventListener,Th=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null;var Nh=64*1024,Ch=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});var xu=1e8;var qh=Object.freeze({tradexyz:"xyz",ventuals:"vntl",hypernova:"hyna",paradex:"para",entropy:"io",entropyio:"io"});function wn(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=xu+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var Su=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),Au=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),vu=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"}),Iu=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"}),ze=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function ku(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 Xo(e,t){let r=U(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 ke(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=>ke(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)}:${ke(e[n],t)}`).join(",")}}`}function Ou(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)||ke(r,"declared order type")!==ke({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(ke(r,"declared order type")!==ke({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||ke(r,"declared order type")!==ke({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 Tu(e,t,r){let n=Xo(e.s,"signed size"),o=Xo(e.p,"signed price"),i=n.decimals+o.decimals,s=n.raw*o.raw,u=M(t.notionalUsd,i,"hl: notionalUsd");if(u<=0n||s!==u)throw new Error("hl: signed notional must match");let a=M(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>a)throw new Error("hl: notional exceeds cap")}function Nu(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=ze(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=M(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function Zo(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(U(e.s,"hl: signed size")!==U(t.size,"hl: size"))throw new Error("hl: signed size must match");if(U(e.p,"hl: signed price")!==U(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(ke(e.t,"signed order type")!==ke(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 Qo(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(U(e.s,"hl: bracket protection size")!==U(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(U(e.p,"hl: bracket protection price")!==U(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(U(i.triggerPx,"hl: triggerPx")!==U(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function Cu(e){let t=String(e||"").replace(/\/$/,"");if(!Su.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function hn(e){return wn(e)!=null}function _u(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(hn(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 Ru(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(hn(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 We(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=ze(r.kind,"kind",48),o=vu[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=Cu(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!==Iu[n])throw new Error("hl: action type must match kind");let u=r.notionalUsd??0;if(Au.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let a=ze(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=wn(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(_u(a,t),Ru(a,c,t),n==="hip4-order"&&!hn(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");Ou(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");Zo(d[0],r,c);let p=1;l!=null&&Qo(d[p++],r,c,l,"tp"),m!=null&&Qo(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");Zo(d[0],r,c)}Tu(d[0],r,t),Nu(r,t),u=U(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=ze(r.usd,"margin usd",64),l=M(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=M(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),p=l<0n?-l:l;if(p>f)throw new Error("hl: margin notional exceeds cap");u=ku(p,6)}}if(n==="builder-fee-approval"){let a=ze(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(a))throw new Error("hl: builder address required");if(ze(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=ze(r.maxFeeRate,"maxFeeRate",32);if(ze(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=M(d.slice(0,-1),12,"hl: builder fee percent"),m=M(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 Lu}from"node:crypto";var Et="0x"+"00".repeat(32);function gn(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 ei({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=Lu("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 $u(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 Pu(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 ti(e,t){let r=de(e.makerAmount,"poly: makerAmount"),n=de(e.takerAmount,"poly: takerAmount");return Pu(t==="BUY"?r:n)}function Bu(e){let t=typeof e=="bigint"?e.toString(10):U(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 ri({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=$u(e,t);if(ne(e.metadata||Et,"poly: metadata").toLowerCase()!==Et)throw new Error("poly: metadata must be zero");if(ne(e.builder||Et,"poly: builder").toLowerCase()!==Et)throw new Error("poly: builder must be zero");let s=Bu(e.salt);return{deferExec:!1,order:{builder:Et,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:Et,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 Du=new Set(["https://clob.polymarket.com/order"]),Jt=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Yh=Object.freeze(Jt.map(e=>e[0])),Fu=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),ju="0xe111180000d2663c0091e4f400237545b87b996b",qu="0xe2222d279d744050d28e00520010520000310f59",ni=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function oi(e){let t=String(e||"").replace(/\/$/,"");if(!Du.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function ii(e){let t=ne(e,"poly: exchange").toLowerCase();if(!Fu.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function Ue(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=ni(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(oi(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(ii(o.verifyingContract),ii(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?qu:ju;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!==Jt.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let v=0;v<Jt.length;v+=1)if(u[v]?.name!==Jt[v][0]||u[v]?.type!==Jt[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=ni(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=M(r.quantity,6,"poly: quantity");if(y<=0n||y!==h)throw new Error("poly: quantity must match CLOB v2 amounts");let b=M(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(M(r.notionalUsdc,6,"poly: notionalUsdc")!==g)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let A=ti(s,l);if(M(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=M(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:oi(r.submitTo)})}var Mu=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),yn=14,si=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function xt(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function bn(e){let t=String(e||"").replace(/\/$/,"");if(!Mu.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function Ve(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=si(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=bn(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");xt(r.orderType,0,"orderType"),xt(r.timeInForce,1,"timeInForce"),xt(r.reduceOnly,0,"reduceOnly"),xt(r.triggerPrice,0,"triggerPrice"),xt(r.orderExpiry,-1,"orderExpiry");let a=si(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=M(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=M(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,g,"lighter: maxNotionalUsd");if(h>b)throw new Error("lighter: notional exceeds cap");let S=U(r.notionalUsd,"lighter: notionalUsd");return xt(r.txType,yn,"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)})}import{TypedDataEncoder as ui,getAddress as be}from"ethers";import{TypedDataEncoder as tg,getAddress as rg,isAddress as ng}from"ethers";var ai=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),En=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 wg,isAddress as hg}from"ethers";var sg=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});var ci=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Ag=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var xn=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"}]}),vg=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});var zu=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"]),Wu="0x0000000000000000000000000000000000000000";function Sn(e,t,r=256){if(typeof e!="string"||!e||e.length>r)throw new Error(`evm-order: bounded ${t} required`);return e}function li(e,t){let r=String(e||"").replace(/\/$/,"");if(!zu.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 di(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 fi(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 pi(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 mi(e,t,{allowZero:r=!1}={}){let n=String(t||"").toLowerCase();if(!n)throw new Error("evm-order: receiver required");if(n===Wu){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 tt(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=Sn(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(di(r.submitTo,l),Sn(e.destination,"destination",32)!=="cowswap")throw new Error("evm-order: cow destination must be cowswap");let m=ci[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(!fi(p,xn))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();mi(g,w.receiver),pi(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:di(r.submitTo,l),digest:ui.hash(f,{Order:xn.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(Sn(e.destination,"destination",32)!=="1inch-lop")throw new Error("evm-order: destination must be 1inch-lop");let o=Number(r.chainId??e.chainId),i=ai[o];if(!i)throw new Error(`evm-order: unsupported chainId ${o}`);li(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(!fi(u,En))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");mi(c,a.receiver,{allowZero:!0}),pi(t,a.makerAsset,a.takerAsset);let d=ui.hash(s,{Order:En.Order},a);return Object.freeze({unit:`erc20:${be(a.makerAsset).toLowerCase()}`,value:String(a.makingAmount),notional:String(a.makingAmount),fee:"0",submitTo:li(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 Ei=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]);var An=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}),Uu=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),xi=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"}}),Vu=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),br=new bi(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),wi=new bi(["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"]),Ju=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 Gt=(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`)}},hi=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ku=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},Y=(e,t,r)=>{if(!Ku(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Kt=(e,t,r)=>{Array.isArray(t)&&t.length&&Y(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},rt=e=>String(e||"0x").slice(0,10).toLowerCase(),Si=e=>N(e.gasLimit,"gasLimit")*N(e.maxFeePerGas??e.gasPrice,"feePerGas")+N(e.l1FeeWei??0,"l1FeeWei")+N(e.operatorFeeWei??0,"operatorFeeWei");function St(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 Z(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 Gu(e){if(rt(e)!=="0x095ea7b3")return null;let t=St(e,2,"approval");return{kind:"approval",spender:Z(t.word(0),"approval spender"),amount:Ee(t.word(1),"approval amount")}}function Ai(e,t){let r=t==="router02-exact-input-single"?7:8,n=St(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:Z(n.word(0),"input token"),outputToken:Z(n.word(1),"output token"),recipient:Z(n.word(3),"recipient"),amountIn:Ee(n.word(o),"amountIn"),minimumOut:Ee(n.word(o+1),"amountOutMinimum")}}function Yu(e){let t=St(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:Z(t.word(0),"depositor"),recipient:Z(t.word(1),"recipient"),inputToken:Z(t.word(2),"input token"),outputToken:Z(t.word(3),"output token"),amountIn:Ee(t.word(4),"inputAmount"),minimumOut:Ee(t.word(5),"outputAmount"),destinationChainId:Ee(t.word(6),"destinationChainId")}}function Xu(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 gi(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}=Xu(`0x${f}`);return{kind:"action",action:"swap",inputToken:p,outputToken:w,recipient:Z(a,"recipient"),amountIn:c,minimumOut:d}}function Zu(e){let t=St(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:Z(t.word(0),"input token"),outputToken:Z(t.word(1),"output token"),recipient:Z(t.word(3),"recipient"),amountIn:Ee(t.word(5),"amountIn"),minimumOut:Ee(t.word(6),"amountOutMinimum")}}function Qu(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=rt(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Ai(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function el(e,t){let r=rt(e),n=xi[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{...Ai(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...gi(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...gi(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...Qu(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Zu(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...Yu(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function tl(e){let t=St(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:Z(t.word(0),"mint NFT contract"),feeRecipient:Z(t.word(1),"mint fee recipient"),recipient:Z(t.word(2),"mint recipient"),quantity:Ee(t.word(3),"mint quantity")}}function rl(e){let t;try{t=wi.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(wi.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 nl(e,t){let r=rt(e);if(String(t).toLowerCase()==="nft-mint")return ol(e);let n=Vu[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{...tl(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 ol(e){let t=rt(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=Ju[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=St(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 Er(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 vi(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??Er(e)[0]?.chainId);if(!Number.isSafeInteger(a)||a<=0)throw new Error("envelope: explicit batch chainId required");if(Y(a,t.chains,"chain"),u?.owner!==void 0&&P(u.owner,"batch owner")!==s)throw new Error("envelope: explicit batch owner mismatch");let c=Er(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(Y(rt(f.data),t.selectors,"selector"),d+=N(f.value??0,"value"),l+=N(f.gasLimit,"gasLimit"),m+=Si(f),ve(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 Ii(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=Gt(e.provider,"provider",64).toLowerCase();Y(i,t.providers,"provider");let s=vi(e,t,o,{nowMs:r}),u=[],a=-1;for(let p=0;p<s.transactions.length;p++){let w=s.transactions[p],g=Gu(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(Y(S,t.tokens,"token"),Y(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");Y(w.to,t.destinations,"destination"),h={...el(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:Si(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(Y(c.inputToken,t.tokens,"input token"),Y(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(nn(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([...Uu,...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 il(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 yi(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 ki(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=Gt(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Kt(n,t.providers,"provider");let o=vi(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");Y(p,t.destinations,"destination");let w=P(e.contract??e.artifact?.contract,"NFT contract");if(Kt(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");Kt(h,t.erc20Tokens,"ERC20 token");let y=il(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=Gt(e.nftAction,"nftAction",8).toLowerCase(),k;if(A==="buy"){let v=yi(e,A),_=Object.entries(t.nftPaymentTokenCaps||{}).find(([W])=>W.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=br.decodeFunctionData("buySpecificNFT",f.data);if(br.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=yi(e,A),z=br.decodeFunctionData("sellNFT",f.data);if(br.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&&Po(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=rt(s.data);Y(u,t.selectors,"selector"),Y(s.to,t.destinations,"destination");let a=nl(s.data,n),c=P(e.contract??e.artifact?.contract,"NFT contract");if(Kt(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&&Kt(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 sl(e,{localsWaiver:t=!1}={}){if(!(e in An))throw new Error("fee: unknown action");return t?0:An[e]}function Yt(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=Gt(e.surface,"surface",16);if(!Ei.has(u))throw new Error("envelope: unsupported public surface");let a=Gt(e.action,"action",32);Y(u,t.surfaces,"surface"),Y(a,t.actions,"action"),Y(e.owner,t.owners,"owner"),Y(e.destination,t.destinations,"destination");let c=hi(t.maxTtlMs,"maxTtlMs"),d=hi(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")Ii(e,t,{nowMs:r,routeAttestationSecret:o});else if(u==="evm-nft")ki(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");wr({...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"?un(e,t):u==="sol"?mn(e,t):u==="hl"?We(e,t):u==="poly"?Ue(e,t):u==="lighter"?Ve(e,t):u==="evm-order"&&tt(e,t);let m=Number(e.fee?.oracleFeeBps)===0&&An[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=sl(a,{localsWaiver:m});if(Number(e.fee?.oracleFeeBps)!==f)throw new Error("fee: final artifact fee mismatch");return!0}var vn=Object.freeze([...Ei]),Mg=Object.freeze({...xi});function In(e,t){if(e.surface==="hl")return We(e,t);if(e.surface==="poly")return Ue(e,t);if(e.surface==="lighter")return Ve(e,t);if(e.surface==="evm-order")return tt(e,t);if(e.surface==="btc")return un(e,t);if(e.surface==="sol")return mn(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Ii(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=ki(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 Oi(e={}){let t={};for(let r of vn){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 xr(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 $i}from"node:crypto";import{ed25519 as gl}from"@noble/curves/ed25519.js";import{base58 as Bi}from"@scure/base";import{RawTx as _n,SigHash as nt,Transaction as Rn}from"@scure/btc-signer";import{Transaction as Ln,keccak256 as Nn,verifyTypedData as Cn}from"ethers";import{encode as al}from"@msgpack/msgpack";import{keccak256 as cl,verifyTypedData as ul}from"ethers";var At=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),kn=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Ti(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 ll(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(al(e)),Ti(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]),Ti(n)),cl(Buffer.concat(i))}function On(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:ll(e,t,{vaultAddress:n,expiresAfter:o})}}function Ni(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=On(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==At.name||String(t.domain?.version)!==At.version||Number(t.domain?.chainId)!==At.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(At.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(kn.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 Ci({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=On(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(At,kn,s)}function _i({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:s=null}){try{let u=On(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:s}),a=ul(At,kn,u,e);return String(a).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var dl=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function Tn(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)Tn(t);return}for(let t of Object.values(e))Tn(t)}}}function fl(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 Tn(e),JSON.parse(JSON.stringify(e))}function Sr(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 pl(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 Ri(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 It(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=>Ri(e[s],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function ml(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 vt(e,t,r,n){let o=It(e,t,n);if(BigInt(o)!==Sr(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function wl(e,t,r,n){let o=It(e,t,n,{signed:!0});if(BigInt(o)!==pl(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function hl(e){let t={};for(let[r,n]of dl.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 Ri(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 Xt(e,t){let r=fl(t),n=vt(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=vt(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=vt(r,["Type","type"],e.orderType,"Type"),s=vt(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),u=vt(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),a=vt(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),c=wl(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=It(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=It(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),m=It(r,["Price","price"],"Price");if(BigInt(d)!==Sr(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==Sr(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(m)!==Sr(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let f=ml(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=It(r,["txType","tx_type","TxType"],"txType");if(g!==yn)throw new Error("lighter: signed txType must be official create-order");let h={...hl(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:bn(e.submitTo)}}function Li(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var kt=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},Ar=e=>String(e||"").toLowerCase();function yl(e,t){if(typeof e!="string")return!1;let r,n;try{r=Ln.from(e),n=Ln.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 Ar(r.from)!==Ar(t.from)||Ar(r.to)!==Ar(t.to)?!1:r.unsignedHash===n.unsignedHash}function bl(e){let t=Buffer.from(_n.encode(e)),r=$i("sha256").update(t).digest();return Buffer.from($i("sha256").update(r).digest()).reverse().toString("hex")}function Pi(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||bl(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 El(e,t){let r=kt(e),n=kt(t.psbt);if(!r||!n)return!1;try{let o=Rn.fromPSBT(n),i=Rn.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(!Pi(a)||!Pi(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(_n.encode(h)).equals(Buffer.from(_n.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!==nt.DEFAULT&&u.sighashType!==nt.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===nt.ALL,m=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===nt.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]===nt.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]!==nt.ALL&&b[64]!==nt.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 Di(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=kt(e),o=kt(t.messageBase64);if(!n||!o)return!1;let i=Di(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=Bi.decode(String(r));return c.length===32&&gl.verify(u,a,c)}catch{return!1}}function Fi(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(Cn(o,i,s,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}}if(String(e).startsWith("evm"))return yl(t,r);if(e==="btc")return El(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(Cn(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return _i({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(Cn(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Xt(r,t),!0}catch{return!1}return!1}function ji(e,t){try{if(e==="evm-order")return Nn(t);if(String(e).startsWith("evm"))return Ln.from(t).hash;if(e==="btc"){let r=kt(t);if(!r)return null;let n=Rn.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=kt(t);if(!r)return null;let n=Di(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Bi.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return Nn(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return Nn(t)}catch{}return null}var Il=e=>String(e||"").toLowerCase();function Q(e){return Sl("sha256").update(JSON.stringify(e)).digest("hex")}function kr(e,t,r={}){return wr(e,t,r)}async function kl(e,t={}){if(!ve(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 Mi(e,t,r=!1){if(!ve(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 Hi(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 vr=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=Al(32).toString("hex");return this.#e.set(i,{digest:Q(t),owner:Il(r),expiresAtMs:this.now()+n,binding:Hi(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(Q(r),"hex");if(!vl(i,s))throw new Error("confirmation: artifact mismatch");if(JSON.stringify(o.binding)!==JSON.stringify(Hi(n)))throw new Error("confirmation: execution binding mismatch");return this.#e.delete(String(t)),o}clear(){this.#e.clear()}};function Ol(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 Tl(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 Nl(e){return e==="evm"||e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Ir(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=qi.decode(r);return n.length===64&&qi.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 zi(e,t,r){return!Ir(e,t)||!Ir(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function Cl(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 $n({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:s,nowMs:u}){let a=Cl(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 _l(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Rl(e,t){return e&&_l(e.surface)?Er(e):[t]}function Ll(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!zi(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function $l(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:Tl(r,n)}}function Pl(e){return Number.isSafeInteger(e)&&e>0?"commit":"settle-failed"}async function Pn(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=Rl(s,u),c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,d=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),l=await $n({artifact:e,envelope:s,nonce:t,deps:r,policy:c,confirmation:null,consumeNonce:!0,nowMs:d}),m=Q(e),f=(b={})=>{s?Yt(s,c,b):(kr(u,c,{nowMs:b.nowMs,networkFees:b.networkFees,requireNetworkFees:b.requireNetworkFees}),Ol(u))},p=async b=>{let S=!s||Nl(s.surface),A=S?await kl(b,r):void 0;return{nowMs:d(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:A,requireNetworkFees:S&&ve(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)&&Mi(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 $n({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",_=ji(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(Q(e)!==m)throw new Error("signer: artifact mutated after signing");c=typeof r.readPolicy=="function"?r.readPolicy():r.policy,l=await $n({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)&&Mi(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),W=o?await r.broadcastWithArmFence(i,z):await z(),R=W?.status,$=Ll(W,v);if(!zi(v,$,_))throw new Error("signer: receipt transaction hash does not match signed bytes");if(R===0||R==="0x0")throw Ir(v,$)?(r.executionAttempt&&await r.executionAttempt.recordCanonicalReceipt({txIndex:b,receipt:W}),Pl(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(!Ir(v,$))throw new Error("signer: successful broadcast requires a valid transaction hash");r.executionAttempt&&await r.executionAttempt.recordCanonicalReceipt({txIndex:b,receipt:W}),h.push($l(W,$))}}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 Wi=new Set(["127.0.0.1","::1","localhost"]),Fl=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Dl(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 jl(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 Ot=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)}),Ui=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},ql=e=>e==="btc"||e==="sol"||["evm","evm-swap","evm-bridge","evm-nft"].includes(e);function Vi(e={}){let t=e.host||"127.0.0.1";if(!Wi.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 vr,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 Bl.createServer(async(c,d)=>{try{let l=String(c.headers.authorization||"").replace(/^Bearer /i,"");if(!Fl(l,e.token))return O(d,401,{error:"unauthorized"});let m=jl(c.headers.host);if(!Wi.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(vn),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 Ot(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)Yt(p,w,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:b,...S}=p||{};kr(S,w,{nowMs:g})}let h=Q(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 Ot(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 Pn(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 Ot(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 Ot(c);if(f.artifact?.surface==="cex")return O(d,403,{error:"cex requires pending owner ack"});let p=Q(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)Yt(f.artifact,w,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:h,...y}=f.artifact||{};kr(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:Ui(f)})})}if(c.method==="POST"&&c.url==="/execute/reconcile"){let f=await Ot(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 Ot(c);if(f.artifact?.surface==="cex")return O(d,403,{error:"cex requires pending owner ack"});let p=typeof e.executeArtifact=="function"?e.executeArtifact:Pn;if(f.idempotencyKey!==void 0){if(!ql(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 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:Ui(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}),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 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 Or,constants as Je,fchmodSync as Ki,fsyncSync as Dn,lstatSync as ts,mkdirSync as Zl,openSync as Fn,readFileSync as rs,renameSync as Ql,rmSync as Gi,writeFileSync as Yi}from"node:fs";import{randomBytes as jn}from"node:crypto";import{dirname as ed,resolve as td}from"node:path";import{wordlists as Ml}from"ethers";var Hl=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),zl=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Wl=new Set([12,15,18,21,24]);function Ul(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Wl.has(t.length)&&t.every(r=>Ml.en.getWordIndex(r)>=0)}var Vl=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,Jl=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,Kl=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function Gl(e){let t=Ji(e);return Kl.has(t)||Jl.test(t)}var Zt=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function Ji(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Yl(e){let t=Ji(e);return[...Hl].some(r=>t.includes(r))}function Xl(e,t,r){if(typeof t=="string"){if(zl.some(n=>n.test(t))||Ul(t))throw new Zt(r);if(Vl.test(t)&&!Gl(e))throw new Zt(r)}}function Bn(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return Xl(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)=>Bn(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(Yl(o))throw new Zt(i);e[o]!==void 0&&(n[o]=Bn(e[o],i,o))}return n}function Tt(e){return Bn(e)}var ns=2,Xi=Je.O_NOFOLLOW??0;function he(e){return e==null?e:structuredClone(e)}function Zi(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function os(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 Qi(e){Zl(e,{recursive:!0,mode:448}),os(ts(e),"execution outbox directory",!0)}function rd(){return{version:ns,attempts:{}}}function is(e){if(!e||e.version!==ns||!e.attempts||typeof e.attempts!="object"||Array.isArray(e.attempts))throw new Error("execution outbox is invalid");return Tt(e),he(e)}function es(e){try{let t=ts(e);if(os(t,"execution outbox file"),t.size>16*1024*1024)throw new Error("execution outbox is too large");return is(JSON.parse(rs(e,"utf8")))}catch(t){if(t?.code==="ENOENT")return rd();throw t}}function nd(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 od(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 Nt(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 ss(e){if(!Number.isSafeInteger(e)||e<1)return null;try{let t=rs(`/proc/${e}/stat`,"utf8");return t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[19]||null}catch{return null}}function id(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=ss(t);return n===null?!1:n===r}function sd(e){return e.transactions.length>0&&e.transactions.length===e.transactionCount&&e.transactions.every(t=>t?.state==="confirmed"||t?.state==="failed")}function ad(e,t){sd(e)&&(e.state=e.transactions.some(r=>r.state==="failed")?"failed":"receipts-confirmed",e.receiptsRecordedAtMs=t())}function as({path:e,now:t=Date.now,leaseOwner:r,isLeaseOwnerAlive:n=id}={}){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:ss(process.pid)||"pid-only"};if(!Number.isSafeInteger(Number(o.pid))||!String(o.startToken||""))throw new Error("execution lease owner identity is unavailable");let i=td(e),s=ed(i),u=`${i}.lock`;function a(d){Qi(s);let l,m=!1,f=`${i}.${process.pid}.${jn(8).toString("hex")}.tmp`,p;try{l=Fn(u,Je.O_CREAT|Je.O_EXCL|Je.O_WRONLY|Xi,384),m=!0,Yi(l,`${process.pid}
|
|
4
4
|
`,"utf8"),Dn(l),Ki(l,384);let w=es(i),g=d(w),h=is(w);p=Fn(f,Je.O_CREAT|Je.O_EXCL|Je.O_WRONLY|Xi,384),Yi(p,`${JSON.stringify(h)}
|
|
5
|
-
`,"utf8"),Dn(p),Ki(p,384),Or(p),p=void 0,Ql(f,i);let y=Fn(s,Je.O_RDONLY);try{Dn(y)}finally{Or(y)}return he(g)}finally{p!==void 0&&Or(p),Gi(f,{force:!0}),l!==void 0&&Or(l),m&&Gi(u,{force:!0})}}let c={async begin(d){let l=nd(d),m=Q(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=jn(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=od(d);return a(m=>{let f=Oe(m,d.attemptKey);if(Nt(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&&(!Zi(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);Nt(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 Tt(m),a(p=>{let w=Oe(p,d);Nt(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(!Zi(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(),ad(w,t),g})},async failPreSubmission({attemptKey:d,error:l,leaseId:m}){return a(f=>{let p=Oe(f,d);return Nt(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 Tt(l),a(f=>{let p=Oe(f,d);if(Nt(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=jn(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 L of g.transactions){if(!L||L.state==="confirmed"||L.state==="failed")continue;let $=await l(he(L),he(g));$&&await c.recordCanonicalReceipt({attemptKey:d,leaseId:p,txIndex:L.txIndex,receipt:$})}let h=await c.inspect(d),y=h.transactions.filter(Boolean);if(y.some(L=>L.state!=="confirmed"&&L.state!=="failed"))return h;let b=Number(h.transactionCount||y.length),S=y.filter(L=>L.state==="confirmed").length,A=y.filter(L=>L.state==="failed").length,k=Math.max(0,b-y.length);if(y.length===0)return h;let v=y.map(L=>({...he(L.receipt),transactionHash:L.receipt?.transactionHash??L.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 W=S>0?"committed":"failed-fee-settled";if(!h.ledgerDisposition){let L=S>0?m:f;if(typeof L!="function")throw new TypeError("execution reconciliation ledger settlement callback is required");await L(z)}return a(L=>{let $=Oe(L,d);return Nt($,p),["completed","failed","partial"].includes($.state)&&$.result||($.ledgerDisposition=$.ledgerDisposition||W,$.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){Qi(s);let l=es(i).attempts[String(d||"")];return l?he(l):null}};return Object.freeze(c)}import{createHash as cd}from"node:crypto";import{wordlists as ud}from"ethers";var _t="oracle.control-plane/1",$e="0.28.26+control-plane.1",Ct=64*1024,us=32,ld=32*1024,dd=2e3,fd=512,pd=/^(?:0|[1-9][0-9]*)$/,md=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/,wd=/^[a-f0-9]{64}$/,hd=/(?:amount|quantity|value|notional|balance|price|fee|gas|slippage|bps|basispoints|limit|maximum|minimum|cap|allowance|decimals|confirmations|executions|sequence|count)(?:$|[A-Z_])/i,gd=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,yd=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],bd=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),Ed=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,xd=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]),Sd=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"||!pd.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"||!md.test(e))throw new x(`${t} must be a bounded explicit id`);return e}function Pe(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 Hn(e,t,r){return`${Ne(e,t)}\0${V(r,"idempotencyKey")}`}function cs(e,t){return e==="quantities"||hd.test(t)}function ls(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Ad(e){let t=ls(e);return[...bd].some(r=>t.includes(r))}function vd(e){let t=ls(e);return xd.has(t)||Ed.test(t)}function Id(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Sd.has(t.length)&&t.every(r=>ud.en.getWordIndex(r)>=0)}function kd(e,t,r){if(typeof t=="string"){if(yd.some(n=>n.test(t))||Id(t))throw new x(`${r} contains secret or custody material`,"CONTROL_PLANE_SECRET");if(gd.test(t)&&!vd(e))throw new x(`${r} contains secret or custody material`,"CONTROL_PLANE_SECRET")}}function Od(e){return[...new Set([...Object.getOwnPropertyNames(e),...Object.keys(e)])]}function qn(e,t="record",r="",n=new WeakSet){if(!(e===null||typeof e=="boolean"||typeof e=="number")){if(typeof e=="string"){kd(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)=>qn(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 Od(e)){let i=`${t}.${o}`;if(Ad(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");qn(e[o],i,o,n)}}}}function Mn(e,t,r,n,o,i){if(o>us)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>ld)throw new x(`${t} exceeds string size limit`);return cs(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(cs(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>dd)throw new x(`${t} exceeds array item limit`);i.bytes+=2;let a=e.map((c,d)=>Mn(c,`${t}[${d}]`,r,n,o+1,i));if(i.bytes>Ct)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>fd)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]=Mn(e[a],`${t}.${a}`,a,r,o+1,i),i.bytes>Ct)throw new x(`${t} exceeds size limit`)}return u}function Be(e,t="record"){try{Tt(e)}catch(i){throw new x(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}try{qn(e,t)}catch(i){throw i instanceof x?i:new x(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}let n=Mn(e,t,"","",0,{bytes:0});if(Buffer.byteLength(Tr(n),"utf8")>Ct)throw new x(`${t} exceeds size limit`);return n}function Tr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Tr).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Tr(e[t])}`).join(",")}}`}function ot(e){return Tr(Be(e))}function Nr(e){return cd("sha256").update(ot(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 Qt(e){if(!e||typeof e!="object"||Array.isArray(e))throw new x("record object required");let{recordHash:t,eventHash:r,...n}=e;return Nr(n)}function zn(e,t){return Be({schemaVersion:_t,buildVersion:$e,recordType:e,execution:"prepare-only",custody:"none",...t})}function Wn(e,t){if(e.schemaVersion!==_t)throw new x("schemaVersion mismatch");if(e.buildVersion!==$e)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 Td=["schemaVersion","buildVersion","recordType","execution","custody"],ky=[...Td,"recordHash"];var Oy=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"])}),Nd=new Set(["block","blockNumber","blockHash","inclusionBlock","inclusionBlockNumber","inclusionBlockHash","receipt","receiptHash","transactionIndex","logIndex","confirmations"]),Cd=/^(?:0x)?[a-f0-9]{64}$/,_d=/^(?:0x)[a-f0-9]{64}$/;function Cr(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=>Cr(r,t));for(let[r,n]of Object.entries(e))if(Nd.has(r)||Cr(n,t))return!0;return!1}function tr(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 fs(e,t){if(tr(e,t,{min:66,max:66}),!_d.test(e))throw new x(`${t} must be a 0x-prefixed 32-byte hash`);return e}function er(e,t){if(tr(e,t,{min:64,max:66}),!Cd.test(e))throw new x(`${t} must be a 32-byte digest`);return e}function ps(e,t,{positive:r=!1}={}){return xe(e,t,{positive:r})}function Ld(e,t){if(Cr(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;er(r,`${t}.artifactHash`),tr(n,`${t}.signer`,{min:1,max:256})}function Rd(e,t){if(Cr(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;fs(r,`${t}.transactionHash`),tr(n,`${t}.endpoint`,{min:1,max:4096})}function ds(e,t,{requireReceiptStatus:r=!1}={}){let n=e.transactionHash??e.txHash,o=e.blockNumber,i=e.blockHash;fs(n,`${t}.transactionHash`),ps(o,`${t}.blockNumber`,{positive:!0}),er(i,`${t}.blockHash`),e.receiptHash!=null&&er(e.receiptHash,`${t}.receiptHash`),(r||e.receiptStatus!=null)&&tr(e.receiptStatus,`${t}.receiptStatus`,{min:1,max:32})}function Un(e,t,r){switch(e){case"workflow.signed":case"legacy.signed":Ld(t,r);break;case"workflow.submitted":case"legacy.broadcast":Rd(t,r);break;case"workflow.finalized":ds(t,r,{requireReceiptStatus:!0}),t.confirmations!=null&&ps(t.confirmations,`${r}.confirmations`);break;case"workflow.reorged":case"workflow.orphaned":ds(t,r),t.observedBlockHash!=null&&er(t.observedBlockHash,`${r}.observedBlockHash`),t.replacementBlockHash!=null&&er(t.replacementBlockHash,`${r}.replacementBlockHash`);break;default:break}}var $d=Object.freeze(["draft","checked","approval","signed","submitted","finalized","reorged","orphaned","compensating","compensated","failed","cancelled"]),hs=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"]),gs=new Set(hs),Pd=new Set(["workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated"]),ys=new Set(["workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned"]),Bd=new Set(["failed","cancelled","compensated"]),ms=["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 Dd(e,t){return{status:e?.status,source:e?.source,reference:e?.reference,observedAt:e?.observedAt??t}}function bs(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`);Pe(e.observedAt,`${t}.observedAt`)}function Es(e){return Pd.has(e)}function Vn(e={}){Se(e,_r,_r,"WorkflowEvent input");let t=Be({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:Dd(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"),Pe(t.occurredAt,"WorkflowEvent.occurredAt"),Pe(t.recordedAt,"WorkflowEvent.recordedAt"),!gs.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(bs(t.evidence),Es(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 Be(t.data,"WorkflowEvent.data"),ys.has(t.type)&&Un(t.type,t.data,"WorkflowEvent.data"),se(t)}function Lr(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=Vn(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=zn("WorkflowEvent",{...i,sequence:t,previousEventHash:r}),u=se({...s,eventHash:Qt(s)});return rr(u),u}function rr(e){if(Se(e,ms,ms,"WorkflowEvent"),Wn(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(Pe(e.occurredAt,"WorkflowEvent.occurredAt"),Pe(e.recordedAt,"WorkflowEvent.recordedAt"),!gs.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(bs(e.evidence),Es(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(Be(e.data,"WorkflowEvent.data"),ys.has(e.type)&&Un(e.type,e.data,"WorkflowEvent.data"),Te(e.eventHash,"WorkflowEvent.eventHash"),Qt(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 Rr(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(rr(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(Bd.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:_t,buildVersion:$e,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 Fd,randomUUID as As}from"node:crypto";import{chmodSync as Kn,closeSync as st,constants as ce,existsSync as it,fstatSync as jd,fsyncSync as Dr,lstatSync as qd,mkdirSync as Md,openSync as Fr,readFileSync as Pr,renameSync as Hd,unlinkSync as vs,writeSync as zd}from"node:fs";import{dirname as Is,resolve as Wd}from"node:path";import{setTimeout as Ud}from"node:timers/promises";var Gn="oracle.control-plane-ledger-checkpoint/1",Yn="oracle.control-plane-ledger-lock/1",Xn=64*1024*1024,ks=1e4,Os=Ct,xs=["schemaVersion","buildVersion","totalEvents","fileSize","ledgerHash","lastEventHash","workflowHeads","checkpointHash"],Ss=["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 at(e){if(typeof e!="string"||e.length<1||e.length>4096)throw new B("bounded path required","PATH_INVALID");let t=Wd(e);return{ledger:t,checkpoint:`${t}.checkpoint`,lock:`${t}.lock`,directory:Is(t)}}function Vd(e){Md(e,{recursive:!0,mode:448})}function Br(e,t){let r=qd(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 jr(e){let t;try{t=Fr(e,ce.O_RDONLY),Dr(t)}finally{t!==void 0&&st(t)}}function Zn(e,t){let r=0;for(;r<t.length;)r+=zd(e,t,r,t.length-r)}function Jd(e){let t=ce.O_WRONLY|ce.O_CREAT|ce.O_APPEND|(ce.O_NOFOLLOW||0),r=Fr(e,t,384);if(!jd(r).isFile())throw st(r),new B("ledger target is not a regular file","UNSAFE_FILE");return r}function Kd(e){rr(e);let t=Lr({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 Jn(e){return Ne(e.tenantId,e.workflowId)}function Gd(e){let t={};for(let r of e)t[Jn(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 Ts(e,t,r=null){let n=r??(it(e)?Pr(e):Buffer.alloc(0));return Be({schemaVersion:Gn,buildVersion:$e,totalEvents:String(t.length),fileSize:String(n.length),ledgerHash:Fd("sha256").update(n).digest("hex"),lastEventHash:t.at(-1)?.eventHash??null,workflowHeads:Gd(t)},"workflow checkpoint")}function Ns(e,t,r=null){let n=Ts(e,t,r);return se({...n,checkpointHash:Nr(n)})}function Yd(e){if(Se(e,xs,xs,"workflow checkpoint"),e.schemaVersion!==Gn)throw new B("checkpoint schema mismatch","CHECKPOINT_INVALID");if(e.buildVersion!==$e)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(Nr(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 Xd(e,t,r=null,n=null){let{checkpoint:o,directory:i}=at(e),s=n??Ns(e,t,r),u=`${o}.${As()}.tmp`,a;try{a=Fr(u,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),Zn(a,Buffer.from(`${JSON.stringify(s)}
|
|
5
|
+
`,"utf8"),Dn(p),Ki(p,384),Or(p),p=void 0,Ql(f,i);let y=Fn(s,Je.O_RDONLY);try{Dn(y)}finally{Or(y)}return he(g)}finally{p!==void 0&&Or(p),Gi(f,{force:!0}),l!==void 0&&Or(l),m&&Gi(u,{force:!0})}}let c={async begin(d){let l=nd(d),m=Q(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=jn(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=od(d);return a(m=>{let f=Oe(m,d.attemptKey);if(Nt(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&&(!Zi(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);Nt(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 Tt(m),a(p=>{let w=Oe(p,d);Nt(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(!Zi(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(),ad(w,t),g})},async failPreSubmission({attemptKey:d,error:l,leaseId:m}){return a(f=>{let p=Oe(f,d);return Nt(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 Tt(l),a(f=>{let p=Oe(f,d);if(Nt(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=jn(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 W=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 Nt($,p),["completed","failed","partial"].includes($.state)&&$.result||($.ledgerDisposition=$.ledgerDisposition||W,$.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){Qi(s);let l=es(i).attempts[String(d||"")];return l?he(l):null}};return Object.freeze(c)}import{createHash as cd}from"node:crypto";import{wordlists as ud}from"ethers";var _t="oracle.control-plane/1",$e="0.28.26+control-plane.1",Ct=64*1024,us=32,ld=32*1024,dd=2e3,fd=512,pd=/^(?:0|[1-9][0-9]*)$/,md=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/,wd=/^[a-f0-9]{64}$/,hd=/(?:amount|quantity|value|notional|balance|price|fee|gas|slippage|bps|basispoints|limit|maximum|minimum|cap|allowance|decimals|confirmations|executions|sequence|count)(?:$|[A-Z_])/i,gd=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,yd=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],bd=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),Ed=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,xd=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]),Sd=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"||!pd.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"||!md.test(e))throw new x(`${t} must be a bounded explicit id`);return e}function Pe(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 Hn(e,t,r){return`${Ne(e,t)}\0${V(r,"idempotencyKey")}`}function cs(e,t){return e==="quantities"||hd.test(t)}function ls(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Ad(e){let t=ls(e);return[...bd].some(r=>t.includes(r))}function vd(e){let t=ls(e);return xd.has(t)||Ed.test(t)}function Id(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Sd.has(t.length)&&t.every(r=>ud.en.getWordIndex(r)>=0)}function kd(e,t,r){if(typeof t=="string"){if(yd.some(n=>n.test(t))||Id(t))throw new x(`${r} contains secret or custody material`,"CONTROL_PLANE_SECRET");if(gd.test(t)&&!vd(e))throw new x(`${r} contains secret or custody material`,"CONTROL_PLANE_SECRET")}}function Od(e){return[...new Set([...Object.getOwnPropertyNames(e),...Object.keys(e)])]}function qn(e,t="record",r="",n=new WeakSet){if(!(e===null||typeof e=="boolean"||typeof e=="number")){if(typeof e=="string"){kd(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)=>qn(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 Od(e)){let i=`${t}.${o}`;if(Ad(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");qn(e[o],i,o,n)}}}}function Mn(e,t,r,n,o,i){if(o>us)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>ld)throw new x(`${t} exceeds string size limit`);return cs(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(cs(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>dd)throw new x(`${t} exceeds array item limit`);i.bytes+=2;let a=e.map((c,d)=>Mn(c,`${t}[${d}]`,r,n,o+1,i));if(i.bytes>Ct)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>fd)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]=Mn(e[a],`${t}.${a}`,a,r,o+1,i),i.bytes>Ct)throw new x(`${t} exceeds size limit`)}return u}function Be(e,t="record"){try{Tt(e)}catch(i){throw new x(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}try{qn(e,t)}catch(i){throw i instanceof x?i:new x(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}let n=Mn(e,t,"","",0,{bytes:0});if(Buffer.byteLength(Tr(n),"utf8")>Ct)throw new x(`${t} exceeds size limit`);return n}function Tr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Tr).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Tr(e[t])}`).join(",")}}`}function ot(e){return Tr(Be(e))}function Nr(e){return cd("sha256").update(ot(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 Qt(e){if(!e||typeof e!="object"||Array.isArray(e))throw new x("record object required");let{recordHash:t,eventHash:r,...n}=e;return Nr(n)}function zn(e,t){return Be({schemaVersion:_t,buildVersion:$e,recordType:e,execution:"prepare-only",custody:"none",...t})}function Wn(e,t){if(e.schemaVersion!==_t)throw new x("schemaVersion mismatch");if(e.buildVersion!==$e)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 Td=["schemaVersion","buildVersion","recordType","execution","custody"],Oy=[...Td,"recordHash"];var Ty=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"])}),Nd=new Set(["block","blockNumber","blockHash","inclusionBlock","inclusionBlockNumber","inclusionBlockHash","receipt","receiptHash","transactionIndex","logIndex","confirmations"]),Cd=/^(?:0x)?[a-f0-9]{64}$/,_d=/^(?:0x)[a-f0-9]{64}$/;function Cr(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=>Cr(r,t));for(let[r,n]of Object.entries(e))if(Nd.has(r)||Cr(n,t))return!0;return!1}function tr(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 fs(e,t){if(tr(e,t,{min:66,max:66}),!_d.test(e))throw new x(`${t} must be a 0x-prefixed 32-byte hash`);return e}function er(e,t){if(tr(e,t,{min:64,max:66}),!Cd.test(e))throw new x(`${t} must be a 32-byte digest`);return e}function ps(e,t,{positive:r=!1}={}){return xe(e,t,{positive:r})}function Rd(e,t){if(Cr(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;er(r,`${t}.artifactHash`),tr(n,`${t}.signer`,{min:1,max:256})}function Ld(e,t){if(Cr(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;fs(r,`${t}.transactionHash`),tr(n,`${t}.endpoint`,{min:1,max:4096})}function ds(e,t,{requireReceiptStatus:r=!1}={}){let n=e.transactionHash??e.txHash,o=e.blockNumber,i=e.blockHash;fs(n,`${t}.transactionHash`),ps(o,`${t}.blockNumber`,{positive:!0}),er(i,`${t}.blockHash`),e.receiptHash!=null&&er(e.receiptHash,`${t}.receiptHash`),(r||e.receiptStatus!=null)&&tr(e.receiptStatus,`${t}.receiptStatus`,{min:1,max:32})}function Un(e,t,r){switch(e){case"workflow.signed":case"legacy.signed":Rd(t,r);break;case"workflow.submitted":case"legacy.broadcast":Ld(t,r);break;case"workflow.finalized":ds(t,r,{requireReceiptStatus:!0}),t.confirmations!=null&&ps(t.confirmations,`${r}.confirmations`);break;case"workflow.reorged":case"workflow.orphaned":ds(t,r),t.observedBlockHash!=null&&er(t.observedBlockHash,`${r}.observedBlockHash`),t.replacementBlockHash!=null&&er(t.replacementBlockHash,`${r}.replacementBlockHash`);break;default:break}}var $d=Object.freeze(["draft","checked","approval","signed","submitted","finalized","reorged","orphaned","compensating","compensated","failed","cancelled"]),hs=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"]),gs=new Set(hs),Pd=new Set(["workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated"]),ys=new Set(["workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned"]),Bd=new Set(["failed","cancelled","compensated"]),ms=["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 Dd(e,t){return{status:e?.status,source:e?.source,reference:e?.reference,observedAt:e?.observedAt??t}}function bs(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`);Pe(e.observedAt,`${t}.observedAt`)}function Es(e){return Pd.has(e)}function Vn(e={}){Se(e,_r,_r,"WorkflowEvent input");let t=Be({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:Dd(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"),Pe(t.occurredAt,"WorkflowEvent.occurredAt"),Pe(t.recordedAt,"WorkflowEvent.recordedAt"),!gs.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(bs(t.evidence),Es(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 Be(t.data,"WorkflowEvent.data"),ys.has(t.type)&&Un(t.type,t.data,"WorkflowEvent.data"),se(t)}function Rr(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=Vn(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=zn("WorkflowEvent",{...i,sequence:t,previousEventHash:r}),u=se({...s,eventHash:Qt(s)});return rr(u),u}function rr(e){if(Se(e,ms,ms,"WorkflowEvent"),Wn(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(Pe(e.occurredAt,"WorkflowEvent.occurredAt"),Pe(e.recordedAt,"WorkflowEvent.recordedAt"),!gs.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(bs(e.evidence),Es(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(Be(e.data,"WorkflowEvent.data"),ys.has(e.type)&&Un(e.type,e.data,"WorkflowEvent.data"),Te(e.eventHash,"WorkflowEvent.eventHash"),Qt(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 Lr(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(rr(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(Bd.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:_t,buildVersion:$e,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 Fd,randomUUID as As}from"node:crypto";import{chmodSync as Kn,closeSync as st,constants as ce,existsSync as it,fstatSync as jd,fsyncSync as Dr,lstatSync as qd,mkdirSync as Md,openSync as Fr,readFileSync as Pr,renameSync as Hd,unlinkSync as vs,writeSync as zd}from"node:fs";import{dirname as Is,resolve as Wd}from"node:path";import{setTimeout as Ud}from"node:timers/promises";var Gn="oracle.control-plane-ledger-checkpoint/1",Yn="oracle.control-plane-ledger-lock/1",Xn=64*1024*1024,ks=1e4,Os=Ct,xs=["schemaVersion","buildVersion","totalEvents","fileSize","ledgerHash","lastEventHash","workflowHeads","checkpointHash"],Ss=["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 at(e){if(typeof e!="string"||e.length<1||e.length>4096)throw new B("bounded path required","PATH_INVALID");let t=Wd(e);return{ledger:t,checkpoint:`${t}.checkpoint`,lock:`${t}.lock`,directory:Is(t)}}function Vd(e){Md(e,{recursive:!0,mode:448})}function Br(e,t){let r=qd(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 jr(e){let t;try{t=Fr(e,ce.O_RDONLY),Dr(t)}finally{t!==void 0&&st(t)}}function Zn(e,t){let r=0;for(;r<t.length;)r+=zd(e,t,r,t.length-r)}function Jd(e){let t=ce.O_WRONLY|ce.O_CREAT|ce.O_APPEND|(ce.O_NOFOLLOW||0),r=Fr(e,t,384);if(!jd(r).isFile())throw st(r),new B("ledger target is not a regular file","UNSAFE_FILE");return r}function Kd(e){rr(e);let t=Rr({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 Jn(e){return Ne(e.tenantId,e.workflowId)}function Gd(e){let t={};for(let r of e)t[Jn(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 Ts(e,t,r=null){let n=r??(it(e)?Pr(e):Buffer.alloc(0));return Be({schemaVersion:Gn,buildVersion:$e,totalEvents:String(t.length),fileSize:String(n.length),ledgerHash:Fd("sha256").update(n).digest("hex"),lastEventHash:t.at(-1)?.eventHash??null,workflowHeads:Gd(t)},"workflow checkpoint")}function Ns(e,t,r=null){let n=Ts(e,t,r);return se({...n,checkpointHash:Nr(n)})}function Yd(e){if(Se(e,xs,xs,"workflow checkpoint"),e.schemaVersion!==Gn)throw new B("checkpoint schema mismatch","CHECKPOINT_INVALID");if(e.buildVersion!==$e)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(Nr(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 Xd(e,t,r=null,n=null){let{checkpoint:o,directory:i}=at(e),s=n??Ns(e,t,r),u=`${o}.${As()}.tmp`,a;try{a=Fr(u,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),Zn(a,Buffer.from(`${JSON.stringify(s)}
|
|
6
6
|
`,"utf8")),Dr(a),st(a),a=void 0,Hd(u,o),Kn(o,384),jr(i)}catch(c){a!==void 0&&st(a);try{it(u)&&vs(u)}catch{}throw c}return s}function Zd(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}:ot(e.workflowHeads)!==ot(t.workflowHeads)?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:{ok:!0}}function Qd({path:e,maxBytes:t=Xn,checkCheckpoint:r=!0}={}){let n=at(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(!it(n.ledger))return r&&it(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(Br(n.ledger,"ledger").size>t)return{ok:!1,reason:"size-limit",count:0,workflows:0,events:[],paths:n};let i=Pr(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(`
|
|
7
|
-
`),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")>Os)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=Kd(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=Jn(g),y=Hn(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=Jn(f);m.has(p)||m.set(p,[]),m.get(p).push(f)}for(let[f,p]of m)try{
|
|
7
|
+
`),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")>Os)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=Kd(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=Jn(g),y=Hn(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=Jn(f);m.has(p)||m.set(p,[]),m.get(p).push(f)}for(let[f,p]of m)try{Lr(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(!it(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{Br(n.checkpoint,"checkpoint");let g=Pr(n.checkpoint,"utf8");if(!g.endsWith(`
|
|
8
8
|
`))throw new B("checkpoint truncated","CHECKPOINT_INVALID");f=JSON.parse(g),Yd(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=Ts(n.ledger,a,i),w=Zd(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 ef(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 tf(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 Cs(e){let{lock:t}=at(e);Br(t,"lock");let r=JSON.parse(Pr(t,"utf8"));if(Se(r,Ss,Ss,"workflow ledger lock"),r.schemaVersion!==Yn)throw new B("lock schema mismatch","LOCK_INVALID");if(V(r.token,"workflow ledger lock.token"),!Number.isSafeInteger(r.pid)||r.pid<=0)throw new B("lock pid invalid","LOCK_INVALID");return Pe(r.createdAt,"workflow ledger lock.createdAt"),r}function _s({path:e}={}){let{lock:t}=at(e);if(!it(t))return se({state:"unlocked",lock:null});try{let r=Cs(e);return se({state:tf(r.pid),lock:r})}catch(r){return se({state:"invalid",lock:null,error:String(r?.message||r)})}}function rf(e){let t=at(e);Vd(t.directory);let r={schemaVersion:Yn,token:As(),pid:process.pid,createdAt:new Date().toISOString()},n;try{return n=Fr(t.lock,ce.O_WRONLY|ce.O_CREAT|ce.O_EXCL|(ce.O_NOFOLLOW||0),384),Zn(n,Buffer.from(`${JSON.stringify(r)}
|
|
9
|
-
`,"utf8")),Dr(n),st(n),n=void 0,Kn(t.lock,384),jr(t.directory),r}catch(o){throw n!==void 0&&st(n),o}}async function nf(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 rf(e)}catch(n){if(n?.code!=="EEXIST")throw n;if(Date.now()-r>=t){let o=_s({path:e});throw new B(`ledger busy (${o.state} lock); explicit token-bound recovery is required for stale locks`,"LEDGER_BUSY",o)}await Ud(10)}}function $r(e,t){let r=Cs(e);if(r.token!==t||r.pid!==process.pid)throw new B("lock fencing token no longer owned","LOCK_FENCED");return!0}function of(e,t){let r=at(e);$r(e,t),vs(r.lock),jr(r.directory)}function sf(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 Qn(e={}){Se(e,["path","event","lockTimeoutMs","maxBytes"],["path","event"],"appendWorkflowEvent options");let t=at(e.path).ledger,r=Vn(e.event),n=e.lockTimeoutMs??ks,o=e.maxBytes??Xn,i=await nf(t,n),s=null;try{$r(t,i.token);let u=Qd({path:t,maxBytes:o});if(!u.ok)throw new B(`append refused until ledger recovery: ${u.reason}`,"LEDGER_CORRUPT",ef(u));let a=u.events.find(b=>b.tenantId===r.tenantId&&b.workflowId===r.workflowId&&b.idempotencyKey===r.idempotencyKey);if(a){if(ot(sf(a))!==ot(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=
|
|
10
|
-
`,"utf8");if(f.length>Os)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=Ns(t,w,p),h=it(t);h&&Br(t,"ledger"),$r(t,i.token);let y;try{y=Jd(t),Zn(y,f),Dr(y)}finally{y!==void 0&&st(y)}return Kn(t,384),h||jr(Is(t)),$r(t,i.token),Xd(t,w,p,g),se({event:l,duplicate:!1})}catch(u){throw s=u,u}finally{try{of(t,i.token)}catch(u){if(s===null)throw u}}}var jy=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),qy=Object.freeze(["read","simulate"]);var My=1440*60;var Yy=Object.freeze(["privkey","wif","xprv","seed"]);var Xy=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}]),Zy=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);var eo=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),rb=Object.freeze(Object.fromEntries(eo.map((e,t)=>[e,Object.freeze(t+1<eo.length?[eo[t+1]]:[])])));var af=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 pf,randomBytes as mf}from"node:crypto";var cf=Object.freeze(["owner","operator","agent","viewer"]),uf=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),lf=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),$b=Object.freeze(["owner"]),Pb=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"}),Bb=new Set(cf),Db=new Set(uf),Fb=new Set(Object.values(lf));var df=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;var ff=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"])}),jb=Object.freeze(Object.fromEntries(Object.entries(ff).map(([e,t])=>[e,Object.freeze([...t])]))),qr=class extends Error{constructor(t,r="invalid-context"){super(t),this.name="TenantContextError",this.code=r}};function Ls(e,t){let r=String(e??"").trim();if(!df.test(r))throw new qr(`${t} is invalid`);return r}function Rs(e,t){let r=Ls(e,"tenantId"),n=Ls(t,"workflowId");if(r.includes(":")||n.includes(":"))throw new qr("stream key parts must not contain ':'","invalid-stream-key");return`${r}:${n}`}var js=1,qs=1,wf=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),hf=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),Ms=Object.freeze(["taskId","intentId","planId","runId","eventId"]);function $s(e,t){return Rs(e,t)}var nr=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),gf=new Set(wf),yf=new Set(hf),bf=new Set(Ms),Ef=/^[0-9a-f]{32}$/,Ps=/^[0-9a-f]{16}$/;var xf=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,95}$/,Sf=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Af=/^[A-Za-z][A-Za-z0-9_.-]*$/,vf=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"]),If=/(?:^|\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,kf=/(?:0x)?[0-9a-fA-F]{66,}/,Of=/[A-Za-z0-9+/=_-]{96,}/,F=class extends Error{constructor(t,r="invalid-telemetry"){super(t),this.name="WorkflowTelemetryError",this.code=r}};function Mr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Hr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Hr(t)}return e}function to(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(to).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${to(e[t])}`).join(",")}}`}function Hs(e){return pf("sha256").update(to(e)).digest("hex")}function Bs(e,t,r){let n=r?r(e,t):mf(e).toString("hex");return String(n??"").trim().toLowerCase()}function zs(e={}){if(e==null)return{};if(!Mr(e))throw new F("correlation must be a plain object");let t=Object.keys(e).filter(n=>!bf.has(n));if(t.length)throw new F(`unknown correlation fields: ${t.sort().join(", ")}`);let r={};for(let n of Ms){if(e[n]==null)continue;let o=String(e[n]).trim();if(!Sf.test(o))throw new F(`${n} is invalid`);r[n]=o}return r}function Ws(e){if(!Mr(e)||e.schemaVersion!==js)throw new F("trace context version is invalid","invalid-trace");if(!Ef.test(e.traceId||"")||!Ps.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&&!Ps.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 zs(e.correlation),e}function Tf({traceId:e,spanId:t,parentSpanId:r=null,sampled:n=!1,correlation:o={}}={},{idFactory:i}={}){let s=e==null?Bs(16,"trace",i):String(e).trim().toLowerCase(),u=t==null?Bs(8,"span",i):String(t).trim().toLowerCase(),a=r==null?null:String(r).trim().toLowerCase(),c=Hr({schemaVersion:js,traceId:s,spanId:u,parentSpanId:a,sampled:n===!0,correlation:zs(o)});return Ws(c)}var Us=Tf;var zb=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 Ds(e){let t=String(e).replace(/[^a-z0-9]/gi,"").toLowerCase();return vf.some(r=>t.includes(r))}function Nf(e){return If.test(e)||kf.test(e)||Of.test(e)?{value:"[REDACTED]",redacted:!0,truncated:!1}:e.length>nr.maxStringLength?{value:`${e.slice(0,nr.maxStringLength-1)}\u2026`,redacted:!1,truncated:!0}:{value:e,redacted:!1,truncated:!1}}function Vs(e){if(typeof e=="string")return Nf(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,nr.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=Vs(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 Cf(e={}){if(!Mr(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>=nr.maxAttributes){n+=1;continue}if(s.length>nr.maxKeyLength||!Af.test(s)||Ds(s)){n+=1,Ds(s)&&(r+=1);continue}let u=Vs(e[s]);if(!u){n+=1;continue}t[s]=u.value,u.redacted&&(r+=1),u.truncated&&(o+=1)}return Hr({attributes:t,redactedCount:r,droppedCount:n,truncatedCount:o})}function Fs(e,t){if(!Number.isSafeInteger(e)||e<0)throw new F(`${t} must be a non-negative integer milliseconds value`);return e}function _f(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 Lf({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=$s(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?$s(i,s):null}function Rf({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}){Ws(e);let p=String(t??"").trim();if(!xf.test(p))throw new F("workflow telemetry name is invalid");if(!yf.has(r))throw new F("workflow telemetry kind is invalid");let w=c==="ledger_projection"?o:n;if(!gf.has(w))throw new F("workflow telemetry outcome is invalid");let g=Fs(s,"startedAt"),h=Fs(u,"endedAt");if(h<g)throw new F("endedAt must not be before startedAt");let y=Cf(a),b=Lf({streamKey:l,tenantId:m,workflowId:f,sourceEvent:d}),S={schemaVersion:qs,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:_f(i),startedAt:g,endedAt:h,durationMs:h-g,attributes:{...y.attributes},attributePolicy:{redactedCount:y.redactedCount,droppedCount:y.droppedCount,truncatedCount:y.truncatedCount}};return Hr({...S,recordId:Hs(S)})}function ro({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 Rf({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 no(e){if(!Mr(e)||!Object.isFrozen(e)||e.schemaVersion!==qs||e.recordType!=="oracle.workflow.telemetry")return!1;let{recordId:t,...r}=e;return typeof t=="string"&&t===Hs(r)}function oo({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=no(r)?r:ro(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 $f="ORACLE_LEDGER_DUAL_WRITE",Js=/^[a-f0-9]{64}$/,Pf=/^0x[a-f0-9]{64}$/,Bf=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"});function Lt(e,t){return String(e??"").slice(0,t)}function Ks(e=process.env){return String(e?.[$f]??"")==="1"}function Gs({path:e,tenantId:t="local-signer",nowMs:r=Date.now,onError:n=null,telemetry:o=null,append:i=Qn}={}){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=ro({trace:f.trace,name:p,kind:"workflow",outcome:Bf[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: ${Lt(y?.message||y,200)}`)})}catch(g){s(`signer telemetry record failed: ${Lt(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}: ${Lt(A?.message||A,200)}`)}),d(f,p,{digest:f.digest}),a}function m(f){let p=String(f??"").toLowerCase();return Js.test(p)?u.get(p)??null:null}return Object.freeze({queued({digest:f,createdAtMs:p}={}){let w=String(f??"").toLowerCase();if(!Js.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:Us()};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:Lt(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&&Pf.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:Lt(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:Lt(p,300)}})),a},flush(){return a}})}import{appendFileSync as Df,existsSync as Ff,mkdirSync as jf,renameSync as qf,statSync as Mf}from"node:fs";import{dirname as Hf}from"node:path";var zf="ORACLE_TELEMETRY_JSONL",Wf=32*1024*1024,Ys=4096;function Uf({path:e,maxBytes:t=Wf}={}){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<Ys)throw new F(`jsonl exporter maxBytes must be >= ${Ys}`,"invalid-exporter-cap");let n=e;return Object.freeze({path:n,maxBytes:r,export(o){if(!no(o))throw new F("jsonl exporter accepts only sealed workflow telemetry records","invalid-record");let i=`${JSON.stringify(o)}
|
|
11
|
-
`;jf(Hf(n),{recursive:!0,mode:448}),Ff(n)&&Mf(n).size+Buffer.byteLength(i)>r&&qf(n,`${n}.1`),Df(n,i,{mode:384})}})}function Xs(e=process.env,{maxBytes:t}={}){let r=String(e?.[zf]??"").trim();return r?oo({exporter:Uf({path:r,...t===void 0?{}:{maxBytes:t}})}):oo({})}import{createCipheriv as
|
|
12
|
-
`)}function pp(e,t){let r=Jr(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 fp(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function Kr(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=
|
|
9
|
+
`,"utf8")),Dr(n),st(n),n=void 0,Kn(t.lock,384),jr(t.directory),r}catch(o){throw n!==void 0&&st(n),o}}async function nf(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 rf(e)}catch(n){if(n?.code!=="EEXIST")throw n;if(Date.now()-r>=t){let o=_s({path:e});throw new B(`ledger busy (${o.state} lock); explicit token-bound recovery is required for stale locks`,"LEDGER_BUSY",o)}await Ud(10)}}function $r(e,t){let r=Cs(e);if(r.token!==t||r.pid!==process.pid)throw new B("lock fencing token no longer owned","LOCK_FENCED");return!0}function of(e,t){let r=at(e);$r(e,t),vs(r.lock),jr(r.directory)}function sf(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 Qn(e={}){Se(e,["path","event","lockTimeoutMs","maxBytes"],["path","event"],"appendWorkflowEvent options");let t=at(e.path).ledger,r=Vn(e.event),n=e.lockTimeoutMs??ks,o=e.maxBytes??Xn,i=await nf(t,n),s=null;try{$r(t,i.token);let u=Qd({path:t,maxBytes:o});if(!u.ok)throw new B(`append refused until ledger recovery: ${u.reason}`,"LEDGER_CORRUPT",ef(u));let a=u.events.find(b=>b.tenantId===r.tenantId&&b.workflowId===r.workflowId&&b.idempotencyKey===r.idempotencyKey);if(a){if(ot(sf(a))!==ot(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=Rr({...r,sequence:String(BigInt(d?.sequence??"0")+1n),previousEventHash:d?.eventHash??null}),m=u.events.filter(b=>Ne(b.tenantId,b.workflowId)===c);Lr([...m,l]);let f=Buffer.from(`${JSON.stringify(l)}
|
|
10
|
+
`,"utf8");if(f.length>Os)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=Ns(t,w,p),h=it(t);h&&Br(t,"ledger"),$r(t,i.token);let y;try{y=Jd(t),Zn(y,f),Dr(y)}finally{y!==void 0&&st(y)}return Kn(t,384),h||jr(Is(t)),$r(t,i.token),Xd(t,w,p,g),se({event:l,duplicate:!1})}catch(u){throw s=u,u}finally{try{of(t,i.token)}catch(u){if(s===null)throw u}}}var qy=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),My=Object.freeze(["read","simulate"]);var Hy=1440*60;var Xy=Object.freeze(["privkey","wif","xprv","seed"]);var Zy=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}]),Qy=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);var eo=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),nb=Object.freeze(Object.fromEntries(eo.map((e,t)=>[e,Object.freeze(t+1<eo.length?[eo[t+1]]:[])])));var af=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 pf,randomBytes as mf}from"node:crypto";var cf=Object.freeze(["owner","operator","agent","viewer"]),uf=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),lf=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),Pb=Object.freeze(["owner"]),Bb=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),Db=new Set(cf),Fb=new Set(uf),jb=new Set(Object.values(lf));var df=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;var ff=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"])}),qb=Object.freeze(Object.fromEntries(Object.entries(ff).map(([e,t])=>[e,Object.freeze([...t])]))),qr=class extends Error{constructor(t,r="invalid-context"){super(t),this.name="TenantContextError",this.code=r}};function Rs(e,t){let r=String(e??"").trim();if(!df.test(r))throw new qr(`${t} is invalid`);return r}function Ls(e,t){let r=Rs(e,"tenantId"),n=Rs(t,"workflowId");if(r.includes(":")||n.includes(":"))throw new qr("stream key parts must not contain ':'","invalid-stream-key");return`${r}:${n}`}var js=1,qs=1,wf=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),hf=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),Ms=Object.freeze(["taskId","intentId","planId","runId","eventId"]);function $s(e,t){return Ls(e,t)}var nr=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),gf=new Set(wf),yf=new Set(hf),bf=new Set(Ms),Ef=/^[0-9a-f]{32}$/,Ps=/^[0-9a-f]{16}$/;var xf=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,95}$/,Sf=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Af=/^[A-Za-z][A-Za-z0-9_.-]*$/,vf=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"]),If=/(?:^|\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,kf=/(?:0x)?[0-9a-fA-F]{66,}/,Of=/[A-Za-z0-9+/=_-]{96,}/,F=class extends Error{constructor(t,r="invalid-telemetry"){super(t),this.name="WorkflowTelemetryError",this.code=r}};function Mr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Hr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Hr(t)}return e}function to(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(to).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${to(e[t])}`).join(",")}}`}function Hs(e){return pf("sha256").update(to(e)).digest("hex")}function Bs(e,t,r){let n=r?r(e,t):mf(e).toString("hex");return String(n??"").trim().toLowerCase()}function zs(e={}){if(e==null)return{};if(!Mr(e))throw new F("correlation must be a plain object");let t=Object.keys(e).filter(n=>!bf.has(n));if(t.length)throw new F(`unknown correlation fields: ${t.sort().join(", ")}`);let r={};for(let n of Ms){if(e[n]==null)continue;let o=String(e[n]).trim();if(!Sf.test(o))throw new F(`${n} is invalid`);r[n]=o}return r}function Ws(e){if(!Mr(e)||e.schemaVersion!==js)throw new F("trace context version is invalid","invalid-trace");if(!Ef.test(e.traceId||"")||!Ps.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&&!Ps.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 zs(e.correlation),e}function Tf({traceId:e,spanId:t,parentSpanId:r=null,sampled:n=!1,correlation:o={}}={},{idFactory:i}={}){let s=e==null?Bs(16,"trace",i):String(e).trim().toLowerCase(),u=t==null?Bs(8,"span",i):String(t).trim().toLowerCase(),a=r==null?null:String(r).trim().toLowerCase(),c=Hr({schemaVersion:js,traceId:s,spanId:u,parentSpanId:a,sampled:n===!0,correlation:zs(o)});return Ws(c)}var Us=Tf;var Wb=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 Ds(e){let t=String(e).replace(/[^a-z0-9]/gi,"").toLowerCase();return vf.some(r=>t.includes(r))}function Nf(e){return If.test(e)||kf.test(e)||Of.test(e)?{value:"[REDACTED]",redacted:!0,truncated:!1}:e.length>nr.maxStringLength?{value:`${e.slice(0,nr.maxStringLength-1)}\u2026`,redacted:!1,truncated:!0}:{value:e,redacted:!1,truncated:!1}}function Vs(e){if(typeof e=="string")return Nf(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,nr.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=Vs(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 Cf(e={}){if(!Mr(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>=nr.maxAttributes){n+=1;continue}if(s.length>nr.maxKeyLength||!Af.test(s)||Ds(s)){n+=1,Ds(s)&&(r+=1);continue}let u=Vs(e[s]);if(!u){n+=1;continue}t[s]=u.value,u.redacted&&(r+=1),u.truncated&&(o+=1)}return Hr({attributes:t,redactedCount:r,droppedCount:n,truncatedCount:o})}function Fs(e,t){if(!Number.isSafeInteger(e)||e<0)throw new F(`${t} must be a non-negative integer milliseconds value`);return e}function _f(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 Rf({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=$s(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?$s(i,s):null}function Lf({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}){Ws(e);let p=String(t??"").trim();if(!xf.test(p))throw new F("workflow telemetry name is invalid");if(!yf.has(r))throw new F("workflow telemetry kind is invalid");let w=c==="ledger_projection"?o:n;if(!gf.has(w))throw new F("workflow telemetry outcome is invalid");let g=Fs(s,"startedAt"),h=Fs(u,"endedAt");if(h<g)throw new F("endedAt must not be before startedAt");let y=Cf(a),b=Rf({streamKey:l,tenantId:m,workflowId:f,sourceEvent:d}),S={schemaVersion:qs,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:_f(i),startedAt:g,endedAt:h,durationMs:h-g,attributes:{...y.attributes},attributePolicy:{redactedCount:y.redactedCount,droppedCount:y.droppedCount,truncatedCount:y.truncatedCount}};return Hr({...S,recordId:Hs(S)})}function ro({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 Lf({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 no(e){if(!Mr(e)||!Object.isFrozen(e)||e.schemaVersion!==qs||e.recordType!=="oracle.workflow.telemetry")return!1;let{recordId:t,...r}=e;return typeof t=="string"&&t===Hs(r)}function oo({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=no(r)?r:ro(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 $f="ORACLE_LEDGER_DUAL_WRITE",Js=/^[a-f0-9]{64}$/,Pf=/^0x[a-f0-9]{64}$/,Bf=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"});function Rt(e,t){return String(e??"").slice(0,t)}function Ks(e=process.env){return String(e?.[$f]??"")==="1"}function Gs({path:e,tenantId:t="local-signer",nowMs:r=Date.now,onError:n=null,telemetry:o=null,append:i=Qn}={}){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=ro({trace:f.trace,name:p,kind:"workflow",outcome:Bf[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: ${Rt(y?.message||y,200)}`)})}catch(g){s(`signer telemetry record failed: ${Rt(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}: ${Rt(A?.message||A,200)}`)}),d(f,p,{digest:f.digest}),a}function m(f){let p=String(f??"").toLowerCase();return Js.test(p)?u.get(p)??null:null}return Object.freeze({queued({digest:f,createdAtMs:p}={}){let w=String(f??"").toLowerCase();if(!Js.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:Us()};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:Rt(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&&Pf.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:Rt(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:Rt(p,300)}})),a},flush(){return a}})}import{appendFileSync as Df,existsSync as Ff,mkdirSync as jf,renameSync as qf,statSync as Mf}from"node:fs";import{dirname as Hf}from"node:path";var zf="ORACLE_TELEMETRY_JSONL",Wf=32*1024*1024,Ys=4096;function Uf({path:e,maxBytes:t=Wf}={}){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<Ys)throw new F(`jsonl exporter maxBytes must be >= ${Ys}`,"invalid-exporter-cap");let n=e;return Object.freeze({path:n,maxBytes:r,export(o){if(!no(o))throw new F("jsonl exporter accepts only sealed workflow telemetry records","invalid-record");let i=`${JSON.stringify(o)}
|
|
11
|
+
`;jf(Hf(n),{recursive:!0,mode:448}),Ff(n)&&Mf(n).size+Buffer.byteLength(i)>r&&qf(n,`${n}.1`),Df(n,i,{mode:384})}})}function Xs(e=process.env,{maxBytes:t}={}){let r=String(e?.[zf]??"").trim();return r?oo({exporter:Uf({path:r,...t===void 0?{}:{maxBytes:t}})}):oo({})}import{createCipheriv as e0,createDecipheriv as Vf,randomBytes as Jf,scryptSync as Kf}from"node:crypto";import D from"node:fs";import Lt from"node:path";var Gf="ORACLE-LOCAL-VAULT",Yf=1,Wr=Object.freeze({N:1<<17,r:8,p:1}),Xf=256*1024*1024,Zf=16*1024;function zr(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 Qf(e,t,r=Wr){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 Kf(n,t,32,{...r,maxmem:Xf})}function Zs(e,t){if(e?.magic!==Gf||e?.version!==Yf)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!==Wr.N||e.kdf.r!==Wr.r||e.kdf.p!==Wr.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=zr(e.kdf.salt,32,"salt"),o=zr(e.cipher.iv,12,"iv"),i=zr(e.tag,16,"tag"),s=zr(e.ciphertext,1,"ciphertext",{max:Zf}),{ciphertext:u,tag:a,...c}=e,d=Qf(t,n);try{let l=Vf("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 ep(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 tp(e){let t=Lt.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(ep(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 Qs(e){return JSON.parse(L(e))}function Ae(e,t){D.mkdirSync(Lt.dirname(e),{recursive:!0,mode:448}),tp(e);let r=Lt.join(Lt.dirname(e),`.${Lt.basename(e)}.${process.pid}.${Jf(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(Lt.dirname(e),"r");try{D.fsyncSync(o)}finally{D.closeSync(o)}}catch(n){try{D.unlinkSync(r)}catch{}throw n}}var ea=/^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 np(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 op(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=np(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 ta(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!ea.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let s=op(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&&ea.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 sp,randomBytes as ap,timingSafeEqual as cp}from"node:crypto";import te from"node:fs";import ct from"node:path";import{homedir as io}from"node:os";import{join as so}from"node:path";var ra=process.env.ORACLE_PUBLIC_DESKTOP==="1",ip=ra?process.env.ORACLE_CONFIG_DIR||so(io(),".config","oracle"):so(io(),".config","oracle"),a0=ra?ip:so(io(),".config","mad-desk");var f0="0".repeat(64),p0=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 Ur(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Ur).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Ur(e[r])).join(",")+"}"}var m0=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 ct.resolve(s)}},n=r(ct.dirname(ct.resolve(e))),o=r(ct.dirname(ct.resolve(t))),i=(s,u)=>u===s||u.startsWith(s+ct.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var up=864e5,ue=(e,t)=>sp("sha256",t).update(Ur(e)).digest("hex"),Ce=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&cp(r,n)},lp=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function dp(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 Jr(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 fp(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=Jr(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)}})+`
|
|
12
|
+
`)}function pp(e,t){let r=Jr(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 fp(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function Kr(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=dp(o,n);ut(r,e);let s=Jr(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 Pt(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=Jr(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>=up){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 mp(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=mp(o).find(s=>s.unit===r);return i?n+BigInt(i[t]??0):n},0n)}function Vr(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 $t(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=M(o,6,"ledger: maxDailyNotionalUsdc"),u=M(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 Bt(e,t){let r=`${e}.lock`,n=ap(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 De(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}})+`
|
|
13
13
|
`);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)}})+`
|
|
14
14
|
`);let c={version:1,sequence:s.sequence,ledgerMac:u};te.mkdirSync(ct.dirname(n),{recursive:!0,mode:448}),Ae(n,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:ue(c,r)}})+`
|
|
15
|
-
`),o&&pp(o,r)}function or({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");ut(r,e);let p=R(t);return Bt(e,()=>{let w=Pt(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=Vr(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]=$t(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]=$t(d,i);if(BigInt(y.notional)>A)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+BigInt(y.value)>b||ge(w.entries,"notional",i)+BigInt(y.notional)>S)throw new Error("ledger: daily cap exceeded")}return g.state="reserved",g.atMs=m,g.retriedAtMs=m,delete g.releasedAtMs,De(e,w,p,r,n),structuredClone(g)}let h;if(c!==void 0){let y=Vr(c);for(let b of y){let[S,A,k]=$t(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]=$t(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),De(e,w,p,r,n),structuredClone(h)})}function na({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:s,nowMs:u=Date.now()}){ut(r,e);let a=R(t);return Bt(e,()=>{let c=Pt(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=Vr(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=Vr(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]=$t(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]=$t(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 oa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(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,De(e,u,s,r,n),structuredClone(a)})}function ia({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(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,De(e,u,s,r,n),c})}function hp(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 sa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:s,disposition:u,nowMs:a=Date.now()}){if(ut(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let c=R(t);return Bt(e,()=>{let d=Pt(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(hp(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",De(e,d,c,r,n),m}return l.state="committed",l.committedAtMs=a,l.filledQuote=s,De(e,d,c,r,n),structuredClone(l)})}function aa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=R(t);return Bt(e,()=>{let u=Pt(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",De(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",De(e,u,s,r,n),structuredClone(a)):(a.state="committed",a.committedAtMs=i,a.value="0",a.notional=c.toString(),a.settledAs="fee-only",De(e,u,s,r,n),structuredClone(a))})}function ca(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(lp(t))};return Ce(e.mac,ue(o,R(r)))}function gp(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function ua(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(t.owner).toLowerCase(),action:String(t.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(gp(t))};return Ce(e.mac,ue(o,R(r)))}import{spawnSync as yp}from"node:child_process";function la(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=yp(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}var bp=/^0x[0-9a-f]{40}$/,Ep=/^0x(?:[0-9a-f]{2})*$/,xp=/^(?:0x)?[0-9a-f]{64}$/,Sp=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Ap=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,vp=new Set([12,15,18,21,24]),Gr=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function ao(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Ap.test(e)||vp.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new Gr(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)=>ao(o,`${t}[${i}]`,r));lt(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(Sp.test(i))throw new Gr(`${t}.${o}`);e[o]!==void 0&&(n[o]=ao(e[o],`${t}.${o}`,o))}return n}function lt(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function ir(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Dt(e,t){let r=String(ir(e,t)).toLowerCase();if(!bp.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function Fe(e,t,{positive:r=!1}={}){try{let n=BigInt(ir(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 co(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 da(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))da(t);Object.freeze(e)}return e}function Ip(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};lt(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:co(String(n),`${t}.reason`)}}function kp(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Ip(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 Op(e){if(e==null)return null;if(lt(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:co(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=Fe(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=Fe(e.gasLimit,"simulation.gasLimit")),t}function Tp(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{lt(t,`assetDeltas[${r}]`);let n=Fe(t.before,`assetDeltas[${r}].before`),o=Fe(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),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:co(String(ir(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:s}})}function Np(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{lt(t,`approvalDeltas[${r}]`);let n=Fe(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Dt(t.token,`approvalDeltas[${r}].token`),spender:Dt(t.spender,`approvalDeltas[${r}].spender`),owner:Dt(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function fa(e={}){lt(e,"input");let t=ao(e),r=t.tx==null?t:lt(t.tx,"tx"),n=Fe(t.chainId??r.chainId,"chainId",{positive:!0}),o=Dt(t.account??t.from??r.from,"account/from"),i=Dt(t.destination??t.to??r.to,"destination/to"),s=String(ir(t.prepareHash,"prepareHash")).toLowerCase();if(!xp.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(ir(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Ep.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=kp(d?t.policyChecks:[]),m=Op(t.simulation),f=Tp(t.assetDeltas),p=Np(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:Dt(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:Fe(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:Fe(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:Fe(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:l,allowlistHits:w,assetDeltas:f,approvalDeltas:p,summary:S};return da(A)}import{readFileSync as Cp,readdirSync as _p,existsSync as wa}from"node:fs";import{dirname as Lp,join as Ft}from"node:path";import{fileURLToPath as Rp}from"node:url";var sr=Lp(Rp(import.meta.url));function $p(){let e=[Ft(sr,"descriptors"),Ft(sr,"clear-sign","descriptors"),Ft(sr,"..","clear-sign","descriptors"),Ft(sr,"..","..","clear-sign","descriptors"),Ft(sr,"..","..","..","clear-sign","descriptors")];for(let t of e)if(wa(t))return t;return e[0]}var Pp=$p(),Bp=/^0x[0-9a-f]{8}/,Dp=/^0x[0-9a-fA-F]{40}$/;function Fp(e=Pp){if(!wa(e))return[];let t=[];for(let r of _p(e).filter(n=>n.endsWith(".json")).sort()){let n=Cp(Ft(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 jp(e,{to:t=null,chainId:r=null}={},n=Fp()){let o=String(e||"").toLowerCase(),i=Bp.test(o)?o.slice(0,10):null;if(!i)return null;let s=t&&Dp.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 ha(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function qp(e,t){let r=ha(e,t);return r?`0x${r.slice(24)}`:null}function pa(e,t){let r=ha(e,t);return r?BigInt(`0x${r}`).toString():null}var Mp=(1n<<256n)-1n;function ma(e){if(e==null)return"unknown";let t=BigInt(e);return t>=Mp/2n?"UNLIMITED":t.toString()}function ga(e,{to:t=null,chainId:r=null}={},n=void 0){let o=jp(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"?qp(s,d):c.format==="amount"||c.format==="tokenAmount"?ma(pa(s,d)):pa(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=Re(i)}catch(l){let m=String(l?.message||l);if(/unlimited approvals are refused/i.test(m))d="ORACLE POLICY: unlimited approval \u2014 Oracle refuses to prepare this; bound the amount";else return{ok:!1,refused:`descriptor matched but reviewed decoder refused: ${m}`,intent:o.format.intent}}if(c){let l=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=ma(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 Hp=/^0x[0-9a-f]{40}$/;function ar(e){let t=String(e??"").toLowerCase();return Hp.test(t)?t:null}function zp(e,{token:t,owner:r}){if(!oe(e))return[];let n;try{n=Re(e)}catch{return[]}let o={token:ar(n.token??t),spender:ar(n.spender),owner:ar(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Wp(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=ar(n?.owner??i.from),u=ar(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 fa({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:zp(a,{token:u,owner:s})})}catch{return null}}function ya(e,t,r={}){let n=Wp(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=ga(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{Wallet as uo}from"ethers";import{base58 as lo}from"@scure/base";import{ed25519 as Aa}from"@noble/curves/ed25519.js";import{NETWORK as va,TEST_NETWORK as Ia,WIF as Up,p2wpkh as ba}from"@scure/btc-signer";import{pubECDSA as Vp}from"@scure/btc-signer/utils.js";var Yr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Jp=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},Ea=e=>{let t=String(e||"").trim();try{let r=Buffer.from(lo.decode(t));return lo.encode(r)===t?r:null}catch{return null}},fo=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(Aa.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},xa=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),je=(e,t)=>{if(t==="sol")return fo(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`)},Kp=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return je(r,t)};function po(e,t){let r=String(t||"").trim();if(e==="evm")return new uo(r).privateKey;if(e==="btc")for(let i of[va,Ia])try{return Buffer.from(Up(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let c=Yr(r.slice(4));if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}if(/^base58:/i.test(r)){let c=Ea(r.slice(7));if(!xa(c))throw new Error("sol: invalid explicit base58 private key");return fo(c)}if(/^0x/i.test(r)){let c=Yr(r);if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}let i=Yr(r),s=i&&(i.length===32||i.length===64)?je(i,"sol"):null,u=Ea(r),a=xa(u);if(s&&a&&!s.equals(a))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(a)return fo(u);if(i)return je(i,"sol")}let n=Yr(r);if(n)return e==="evm"?new uo(`0x${n.toString("hex")}`).privateKey:je(n,e);let o=Jp(r);if(o)return je(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Kp(i,e);let s=i.privateKey??i.secretKey??i.key;if(s)return po(e,Array.isArray(s)?JSON.stringify(s):String(s))}throw new Error(`${e}: unsupported private key format`)}function Sa(e,t){if(e==="evm"){let r=new uo(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=je(t,"btc"),n=Vp(r);return{kind:e,secret:r.toString("hex"),addresses:[ba(n,va).address,ba(n,Ia).address]}}if(e==="sol"){let r=je(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[lo.encode(Aa.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function ka(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:Sa(t.kind||"evm",po(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Sa(i,po(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 mo(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Gp=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),Yp=Object.freeze(["binance","bybit","okx","coinbase"]),Xp=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Zp=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Qp=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),H0=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),em=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),z0=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),W0=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),U0=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),V0=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function wo(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 Oa(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 tm(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function rm(e){return new Date(e).toISOString().slice(0,10)}function nm(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 Xr(e={},t={},r=Date.now()){for(let C of Object.keys(e)){let z=C.toLowerCase();if(em.some(W=>W.toLowerCase()===z))throw new Error(`cex-policy: envelope field ${C} forbidden`);if(!Qp.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(!Gp.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=le(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!Yp.includes(o)||!Xp[o]||!Zp[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:s}=nm(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=Oa(e.baseSize,"baseSize"),g=Oa(e.limitPrice,"limitPrice"),!m)throw new Error("cex-policy: clientOrderId required");if(h=wo(e.maxQuoteNotional,"maxQuoteNotional"),y=tm(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=wo(s.perOrderQuoteCap,"sealed perOrderQuoteCap"),A=wo(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}:${rm(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 Ta({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Kr(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Xr(e,n,r);return or({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 om,randomBytes as im,timingSafeEqual as sm}from"node:crypto";var Zr=(e,t)=>om("sha256",e).update(JSON.stringify(t)).digest("hex"),Na=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&sm(r,n)},Ca=e=>Buffer.from(R(e));function _a({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(l){return l?.code==="ESRCH"?!1:null}try{return J.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{J.mkdirSync(dt.dirname(n),{recursive:!0,mode:448});let l=im(16).toString("hex"),m=Date.now()+5e3,f=`${n}.${process.pid}.${l}.tmp`,p=JSON.stringify({version:1,pid:process.pid,processStart:o,token:l,createdAtMs:Date.now()})+`
|
|
16
|
-
`;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!==l||w.pid!==process.pid||w.processStart!==o)throw new Error("cex-state: lock ownership lost");J.unlinkSync(n)}},a=()=>{let d=Ca(t);try{if(!J.existsSync(e)){if(J.existsSync(r))throw new Error("cex-state: rollback detected");return{version:1,sequence:0,orders:[]}}let l=JSON.parse(
|
|
15
|
+
`),o&&pp(o,r)}function or({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");ut(r,e);let p=L(t);return Bt(e,()=>{let w=Pt(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=Vr(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]=$t(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]=$t(d,i);if(BigInt(y.notional)>A)throw new Error("ledger: per-trade cap exceeded");if(ge(w.entries,"value",i)+BigInt(y.value)>b||ge(w.entries,"notional",i)+BigInt(y.notional)>S)throw new Error("ledger: daily cap exceeded")}return g.state="reserved",g.atMs=m,g.retriedAtMs=m,delete g.releasedAtMs,De(e,w,p,r,n),structuredClone(g)}let h;if(c!==void 0){let y=Vr(c);for(let b of y){let[S,A,k]=$t(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]=$t(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),De(e,w,p,r,n),structuredClone(h)})}function na({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:s,nowMs:u=Date.now()}){ut(r,e);let a=L(t);return Bt(e,()=>{let c=Pt(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=Vr(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=Vr(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]=$t(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]=$t(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 oa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=L(t);return Bt(e,()=>{let u=Pt(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,De(e,u,s,r,n),structuredClone(a)})}function ia({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=L(t);return Bt(e,()=>{let u=Pt(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,De(e,u,s,r,n),c})}function hp(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 sa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:s,disposition:u,nowMs:a=Date.now()}){if(ut(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let c=L(t);return Bt(e,()=>{let d=Pt(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(hp(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",De(e,d,c,r,n),m}return l.state="committed",l.committedAtMs=a,l.filledQuote=s,De(e,d,c,r,n),structuredClone(l)})}function aa({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ut(r,e);let s=L(t);return Bt(e,()=>{let u=Pt(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",De(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",De(e,u,s,r,n),structuredClone(a)):(a.state="committed",a.committedAtMs=i,a.value="0",a.notional=c.toString(),a.settledAs="fee-only",De(e,u,s,r,n),structuredClone(a))})}function ca(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(lp(t))};return Ce(e.mac,ue(o,L(r)))}function gp(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function ua(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(t.owner).toLowerCase(),action:String(t.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Q(gp(t))};return Ce(e.mac,ue(o,L(r)))}import{spawnSync as yp}from"node:child_process";function la(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=yp(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}var bp=/^0x[0-9a-f]{40}$/,Ep=/^0x(?:[0-9a-f]{2})*$/,xp=/^(?:0x)?[0-9a-f]{64}$/,Sp=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Ap=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,vp=new Set([12,15,18,21,24]),Gr=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function ao(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Ap.test(e)||vp.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new Gr(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)=>ao(o,`${t}[${i}]`,r));lt(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(Sp.test(i))throw new Gr(`${t}.${o}`);e[o]!==void 0&&(n[o]=ao(e[o],`${t}.${o}`,o))}return n}function lt(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function ir(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Dt(e,t){let r=String(ir(e,t)).toLowerCase();if(!bp.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function Fe(e,t,{positive:r=!1}={}){try{let n=BigInt(ir(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 co(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 da(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))da(t);Object.freeze(e)}return e}function Ip(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};lt(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:co(String(n),`${t}.reason`)}}function kp(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Ip(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 Op(e){if(e==null)return null;if(lt(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:co(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=Fe(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=Fe(e.gasLimit,"simulation.gasLimit")),t}function Tp(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{lt(t,`assetDeltas[${r}]`);let n=Fe(t.before,`assetDeltas[${r}].before`),o=Fe(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),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:co(String(ir(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:s}})}function Np(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{lt(t,`approvalDeltas[${r}]`);let n=Fe(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Dt(t.token,`approvalDeltas[${r}].token`),spender:Dt(t.spender,`approvalDeltas[${r}].spender`),owner:Dt(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function fa(e={}){lt(e,"input");let t=ao(e),r=t.tx==null?t:lt(t.tx,"tx"),n=Fe(t.chainId??r.chainId,"chainId",{positive:!0}),o=Dt(t.account??t.from??r.from,"account/from"),i=Dt(t.destination??t.to??r.to,"destination/to"),s=String(ir(t.prepareHash,"prepareHash")).toLowerCase();if(!xp.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(ir(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Ep.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=kp(d?t.policyChecks:[]),m=Op(t.simulation),f=Tp(t.assetDeltas),p=Np(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:Dt(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:Fe(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:Fe(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:Fe(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:l,allowlistHits:w,assetDeltas:f,approvalDeltas:p,summary:S};return da(A)}import{readFileSync as Cp,readdirSync as _p,existsSync as wa}from"node:fs";import{dirname as Rp,join as Ft}from"node:path";import{fileURLToPath as Lp}from"node:url";var sr=Rp(Lp(import.meta.url));function $p(){let e=[Ft(sr,"descriptors"),Ft(sr,"clear-sign","descriptors"),Ft(sr,"..","clear-sign","descriptors"),Ft(sr,"..","..","clear-sign","descriptors"),Ft(sr,"..","..","..","clear-sign","descriptors")];for(let t of e)if(wa(t))return t;return e[0]}var Pp=$p(),Bp=/^0x[0-9a-f]{8}/,Dp=/^0x[0-9a-fA-F]{40}$/;function Fp(e=Pp){if(!wa(e))return[];let t=[];for(let r of _p(e).filter(n=>n.endsWith(".json")).sort()){let n=Cp(Ft(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 jp(e,{to:t=null,chainId:r=null}={},n=Fp()){let o=String(e||"").toLowerCase(),i=Bp.test(o)?o.slice(0,10):null;if(!i)return null;let s=t&&Dp.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 ha(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function qp(e,t){let r=ha(e,t);return r?`0x${r.slice(24)}`:null}function pa(e,t){let r=ha(e,t);return r?BigInt(`0x${r}`).toString():null}var Mp=(1n<<256n)-1n;function ma(e){if(e==null)return"unknown";let t=BigInt(e);return t>=Mp/2n?"UNLIMITED":t.toString()}function ga(e,{to:t=null,chainId:r=null}={},n=void 0){let o=jp(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"?qp(s,d):c.format==="amount"||c.format==="tokenAmount"?ma(pa(s,d)):pa(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=ma(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 Hp=/^0x[0-9a-f]{40}$/;function ar(e){let t=String(e??"").toLowerCase();return Hp.test(t)?t:null}function zp(e,{token:t,owner:r}){if(!oe(e))return[];let n;try{n=Le(e)}catch{return[]}let o={token:ar(n.token??t),spender:ar(n.spender),owner:ar(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Wp(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=ar(n?.owner??i.from),u=ar(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 fa({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:zp(a,{token:u,owner:s})})}catch{return null}}function ya(e,t,r={}){let n=Wp(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=ga(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{Wallet as uo}from"ethers";import{base58 as lo}from"@scure/base";import{ed25519 as Aa}from"@noble/curves/ed25519.js";import{NETWORK as va,TEST_NETWORK as Ia,WIF as Up,p2wpkh as ba}from"@scure/btc-signer";import{pubECDSA as Vp}from"@scure/btc-signer/utils.js";var Yr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Jp=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},Ea=e=>{let t=String(e||"").trim();try{let r=Buffer.from(lo.decode(t));return lo.encode(r)===t?r:null}catch{return null}},fo=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(Aa.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},xa=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),je=(e,t)=>{if(t==="sol")return fo(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`)},Kp=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return je(r,t)};function po(e,t){let r=String(t||"").trim();if(e==="evm")return new uo(r).privateKey;if(e==="btc")for(let i of[va,Ia])try{return Buffer.from(Up(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let c=Yr(r.slice(4));if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}if(/^base58:/i.test(r)){let c=Ea(r.slice(7));if(!xa(c))throw new Error("sol: invalid explicit base58 private key");return fo(c)}if(/^0x/i.test(r)){let c=Yr(r);if(!c)throw new Error("sol: invalid explicit hex private key");return je(c,"sol")}let i=Yr(r),s=i&&(i.length===32||i.length===64)?je(i,"sol"):null,u=Ea(r),a=xa(u);if(s&&a&&!s.equals(a))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(a)return fo(u);if(i)return je(i,"sol")}let n=Yr(r);if(n)return e==="evm"?new uo(`0x${n.toString("hex")}`).privateKey:je(n,e);let o=Jp(r);if(o)return je(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Kp(i,e);let s=i.privateKey??i.secretKey??i.key;if(s)return po(e,Array.isArray(s)?JSON.stringify(s):String(s))}throw new Error(`${e}: unsupported private key format`)}function Sa(e,t){if(e==="evm"){let r=new uo(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=je(t,"btc"),n=Vp(r);return{kind:e,secret:r.toString("hex"),addresses:[ba(n,va).address,ba(n,Ia).address]}}if(e==="sol"){let r=je(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[lo.encode(Aa.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function ka(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:Sa(t.kind||"evm",po(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Sa(i,po(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 mo(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Gp=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),Yp=Object.freeze(["binance","bybit","okx","coinbase"]),Xp=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Zp=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Qp=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),z0=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),em=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),W0=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),U0=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),V0=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),J0=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function wo(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 Oa(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 tm(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function rm(e){return new Date(e).toISOString().slice(0,10)}function nm(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 Xr(e={},t={},r=Date.now()){for(let C of Object.keys(e)){let z=C.toLowerCase();if(em.some(W=>W.toLowerCase()===z))throw new Error(`cex-policy: envelope field ${C} forbidden`);if(!Qp.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(!Gp.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=le(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!Yp.includes(o)||!Xp[o]||!Zp[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:s}=nm(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=Oa(e.baseSize,"baseSize"),g=Oa(e.limitPrice,"limitPrice"),!m)throw new Error("cex-policy: clientOrderId required");if(h=wo(e.maxQuoteNotional,"maxQuoteNotional"),y=tm(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=wo(s.perOrderQuoteCap,"sealed perOrderQuoteCap"),A=wo(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}:${rm(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 Ta({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Kr(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Xr(e,n,r);return or({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 om,randomBytes as im,timingSafeEqual as sm}from"node:crypto";var Zr=(e,t)=>om("sha256",e).update(JSON.stringify(t)).digest("hex"),Na=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&sm(r,n)},Ca=e=>Buffer.from(L(e));function _a({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(l){return l?.code==="ESRCH"?!1:null}try{return J.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{J.mkdirSync(dt.dirname(n),{recursive:!0,mode:448});let l=im(16).toString("hex"),m=Date.now()+5e3,f=`${n}.${process.pid}.${l}.tmp`,p=JSON.stringify({version:1,pid:process.pid,processStart:o,token:l,createdAtMs:Date.now()})+`
|
|
16
|
+
`;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!==l||w.pid!==process.pid||w.processStart!==o)throw new Error("cex-state: lock ownership lost");J.unlinkSync(n)}},a=()=>{let d=Ca(t);try{if(!J.existsSync(e)){if(J.existsSync(r))throw new Error("cex-state: rollback detected");return{version:1,sequence:0,orders:[]}}let l=JSON.parse(L(e));if(!Na(l.mac,Zr(d,l.state)))throw new Error("cex-state: integrity failed");let m=JSON.parse(L(r));if(!Na(m.mac,Zr(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=Ca(t);try{let m={...d,sequence:d.sequence+1},f=Zr(l,m),p={version:1,sequence:m.sequence,stateMac:f};return J.mkdirSync(dt.dirname(e),{recursive:!0,mode:448}),J.mkdirSync(dt.dirname(r),{recursive:!0,mode:448}),Ae(r,JSON.stringify({marker:p,mac:Zr(l,p)})+`
|
|
17
17
|
`),Ae(e,JSON.stringify({state:m,mac:f})+`
|
|
18
|
-
`),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 gm}from"node:crypto";import{createHash as am}from"node:crypto";var yo=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"}),cm=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,um=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/,La=(e,t)=>{let r=String(e??"");if(!cm.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 ho=(e,t)=>{let r=String(e??"");if(!um.test(r))throw new Error(`cex: bounded ${t} required`);return r},go=e=>{if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(go).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${go(e[t])}`).join(",")}}`;throw new Error("cex: non-canonical request fact refused")};function lm(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");La(e.baseSize,"baseSize"),La(e.limitPrice,"limitPrice"),ho(e.clientOrderId,"clientOrderId")}else ho(e.venueOrderId,"venueOrderId");return e}function dm(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 Ra({venue:e,order:t,timestamp:r,recvWindow:n=5e3}){lm(t);let o=yo[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(ho(t.venueOrderId,"venueOrderId"))));let a={venue:e,operation:t.operation,method:s,path:u,timestamp:i,recvWindow:n,...dm(e,t)};return Object.freeze({...a,params:a.params&&Object.freeze(a.params),body:a.body&&Object.freeze(a.body),requestDigest:am("sha256").update(go(a)).digest("hex")})}import{createHmac as fm}from"node:crypto";var Qr=(e,t,r="hex")=>fm("sha256",e).update(t).digest(r),$a=e=>new URLSearchParams(Object.entries(e||{})).toString(),pm=e=>e===void 0?"":JSON.stringify(e),bo=(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 mm(e,t){let r=bo(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 Pa(e,t){if(t?.venue!==e.venue)throw new Error("cex: credential venue mismatch");let r=bo(t.apiKeyBytes,"credential"),n=mm(t,e.venue),o=t.passphraseBytes?bo(t.passphraseBytes,"credential"):null;try{let i={accept:"application/json"},s=pm(e.body);s&&(i["content-type"]="application/json");let u=$a(e.params),a=e.path;if(e.venue==="binance"){let c=$a({...e.params,timestamp:e.timestamp,recvWindow:String(e.recvWindow)});u=`${c}&signature=${Qr(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":Qr(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":Qr(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":Qr(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 Ba=256*1024,wm=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/;function hm(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(!wm.test(s)||encodeURIComponent(s)!==i)return!1;try{return new URL(r,e).pathname===r&&r===`${n}${i}${o}`}catch{return!1}}async function Eo(e,t){let r=yo[e.venue]?.[e.operation],n=cr[e.venue];if(!r||!n||r[0]!==e.method||!hm(n,r[1],e.path))throw new Error("cex transport refused");let o=Pa(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>Ba)throw new Error("size");let l=new Uint8Array(await u.arrayBuffer());if(l.length>Ba)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 ym=e=>gm("sha256").update(e).digest("hex"),bm=(e,t)=>e==="okx"?new Date(t).toISOString():String(e==="coinbase"?t/1e3:t),xo=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 Da=e=>/^0(?:\.0+)?$/.test(String(e));function Em(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 xm(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:xo(n)}function Sm(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),xo(n)===r.venueOrderId}function Am(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)&&(Da(n.accFillSz)||!Da(n.avgPx))&&(a=Em(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),xo(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 vm(e,t){let r=t?.nowMs?.()??Date.now(),n=t?.transport||Eo,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=Ra({venue:e.venue,order:e.order,timestamp:bm(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=ym(c.responseBodyBytes);if(e.order.operation==="create"){let f=xm(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",Sm(e.venue,c.value,i)?"cancel-pending":"uncertain",{responseDigest:d,observedAtMs:r});let l;try{l=Am(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 Fa(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||Eo,nowMs:e.nowMs||Date.now,settleLedger:e.settleLedger});return Object.freeze({execute:r=>vm(r,t)})}import{createHash as Im,createHmac as ja,randomBytes as km,timingSafeEqual as Om}from"node:crypto";var qa="oracle-local-signer-cex-owner-allow-v1",jt=e=>/^(?:0|[1-9]\d{0,19})$/.test(String(e||""))?String(e):null,Ma=e=>JSON.stringify(e),Tm=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Om(r,n)};function Ha({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(R(e));try{return u(a)}finally{a.fill(0)}},s=i(u=>Im("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:qa,instance:s,nonce:km(16).toString("hex"),issuedAtMs:p,expiresAtMs:p+l},g=i(h=>ja("sha256",h).update(Ma(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!==qa||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=>ja("sha256",m).update(Ma(c)).digest("hex"));return Tm(u.mac,l)?(o.add(c.nonce),!0):!1}})}var Le=new Oo(["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"]),Wa=new Oo(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),Ao=new Oo(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function Bm({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 Dm(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||re.join(process.env.XDG_STATE_HOME||re.join(Nm.homedir(),".local","state"),"oracle"),r=Cm("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 Fm(e){try{return R(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=_m(32).toString("hex");return Ae(e,t+`
|
|
19
|
-
`),t}function vo(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 Ua(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 Va(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function jm(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 qm(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=Le.decodeFunctionData(u,s[0].data),Le.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 qe(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 Mm(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=jm(t,f),w=qm(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(Va(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=Va(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=$m(C).toLowerCase();if(z!==h)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[W,L,$]=await Promise.all([qe(e,i,Le,"collection",_),qe(e,i,Le,"token",_),qe(e,i,Le,"robinhoodSwapFeeWei",_)]),Ke=_e(W,"live Anvil collection"),pt=_e(L,"live Anvil payment token"),qt=BigInt($).toString();if(Ke!==s)throw new Error("signer: live Anvil collection mismatch");if(pt!==u)throw new Error("signer: live Anvil payment token mismatch");if(qt!==a.toString())throw new Error("signer: live Anvil native swap fee mismatch");let Mt=Number(await qe(e,pt,Wa,"decimals",_));if(!Number.isSafeInteger(Mt)||Mt!==c)throw new Error("signer: live Anvil payment token decimals mismatch");let mt=_e(await qe(e,Ke,Ao,"ownerOf",_,[m]),"live Anvil token owner"),Ge=null,Ye=null,Xe=null,Ze=null,q;if(f==="buy"){let[Me,wt,E]=await Promise.all([qe(e,i,Le,"inventory",_,[m]),qe(e,pt,Wa,"allowance",_,[d,i]),e.send("eth_call",[{to:i,data:Le.encodeFunctionData("quoteSpecificBuy",[m])},_])]);Ge=!!Me,Ye=BigInt(wt).toString();let I=Le.decodeFunctionResult("quoteSpecificBuy",E);if(q=Object.freeze({totalCostRaw:BigInt(I[0]).toString(),baseCostRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString(),available:!!I[4]}),JSON.stringify(q)!==JSON.stringify(p))throw new Error("signer: exact Anvil buy quote changed after preparation");if(mt!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!Ge)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt(Ye)!==BigInt(t.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(Ye)<w)throw new Error("signer: live Anvil ERC20 allowance is insufficient");if(!q.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(q.totalCostRaw)!==w)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(q.totalCostRaw)!==BigInt(q.baseCostRaw)+BigInt(q.feeRaw)+BigInt(q.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[Me,wt,E]=await Promise.all([qe(e,Ke,Ao,"getApproved",_,[m]),qe(e,Ke,Ao,"isApprovedForAll",_,[d,i]),e.send("eth_call",[{to:i,data:Le.encodeFunctionData("quoteSellNFT")},_])]);Xe=_e(Me,"live Anvil token approval"),Ze=!!wt;let I=Le.decodeFunctionResult("quoteSellNFT",E);if(q=Object.freeze({netPayoutRaw:BigInt(I[0]).toString(),grossPayoutRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString()}),JSON.stringify(q)!==JSON.stringify(p))throw new Error("signer: exact Anvil sell quote changed after preparation");if(mt!==d)throw new Error("signer: exact Anvil token owner does not match signer");if(Xe!==i&&!Ze)throw new Error("signer: live Anvil NFT approval is insufficient");if(Xe!==_e(t.preconditions?.approvedAddress,"prepared Anvil token approval")||Ze!==!!t.preconditions?.approvedForAll)throw new Error("signer: live Anvil NFT approval changed after preparation");if(BigInt(q.netPayoutRaw)!==w)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(q.netPayoutRaw)+BigInt(q.feeRaw)+BigInt(q.protocolFeeRaw)!==BigInt(q.grossPayoutRaw))throw new Error("signer: exact Anvil sell quote fee arithmetic mismatch")}return Object.freeze({source:"local-signer-trusted-rpc",chainId:4663,market:i,collection:Ke,paymentToken:pt,paymentTokenDecimals:Mt,nativeSwapFeeWei:qt,signerAddress:d,nftAction:f,tokenId:m.toString(),tokenOwner:mt,inventoryMember:Ge,allowanceRaw:Ye,approvedAddress:Xe,approvedForAll:Ze,quote:q,blockNumber:A.toString(),blockHash:v,runtimeCodeHash:z,verifiedAtMs:Number(n)})}function Ja(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 Hm(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:s}={}){let u=Rm(new URL("./anvil-attestation-worker.mjs",import.meta.url)),a={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},c;try{c=Lm(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)}function zm(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=Re(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=Re(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=cn(o,r);s.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(o?.surface==="sol"){let c=pn(o,r);s.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(o?.surface==="hl"){let c=We(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=Ue(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=Ve(o,r);s.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
|
|
18
|
+
`),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 gm}from"node:crypto";import{createHash as am}from"node:crypto";var yo=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"}),cm=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,um=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/,Ra=(e,t)=>{let r=String(e??"");if(!cm.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 ho=(e,t)=>{let r=String(e??"");if(!um.test(r))throw new Error(`cex: bounded ${t} required`);return r},go=e=>{if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(go).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${go(e[t])}`).join(",")}}`;throw new Error("cex: non-canonical request fact refused")};function lm(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");Ra(e.baseSize,"baseSize"),Ra(e.limitPrice,"limitPrice"),ho(e.clientOrderId,"clientOrderId")}else ho(e.venueOrderId,"venueOrderId");return e}function dm(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 La({venue:e,order:t,timestamp:r,recvWindow:n=5e3}){lm(t);let o=yo[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(ho(t.venueOrderId,"venueOrderId"))));let a={venue:e,operation:t.operation,method:s,path:u,timestamp:i,recvWindow:n,...dm(e,t)};return Object.freeze({...a,params:a.params&&Object.freeze(a.params),body:a.body&&Object.freeze(a.body),requestDigest:am("sha256").update(go(a)).digest("hex")})}import{createHmac as fm}from"node:crypto";var Qr=(e,t,r="hex")=>fm("sha256",e).update(t).digest(r),$a=e=>new URLSearchParams(Object.entries(e||{})).toString(),pm=e=>e===void 0?"":JSON.stringify(e),bo=(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 mm(e,t){let r=bo(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 Pa(e,t){if(t?.venue!==e.venue)throw new Error("cex: credential venue mismatch");let r=bo(t.apiKeyBytes,"credential"),n=mm(t,e.venue),o=t.passphraseBytes?bo(t.passphraseBytes,"credential"):null;try{let i={accept:"application/json"},s=pm(e.body);s&&(i["content-type"]="application/json");let u=$a(e.params),a=e.path;if(e.venue==="binance"){let c=$a({...e.params,timestamp:e.timestamp,recvWindow:String(e.recvWindow)});u=`${c}&signature=${Qr(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":Qr(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":Qr(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":Qr(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 Ba=256*1024,wm=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/;function hm(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(!wm.test(s)||encodeURIComponent(s)!==i)return!1;try{return new URL(r,e).pathname===r&&r===`${n}${i}${o}`}catch{return!1}}async function Eo(e,t){let r=yo[e.venue]?.[e.operation],n=cr[e.venue];if(!r||!n||r[0]!==e.method||!hm(n,r[1],e.path))throw new Error("cex transport refused");let o=Pa(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>Ba)throw new Error("size");let l=new Uint8Array(await u.arrayBuffer());if(l.length>Ba)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 ym=e=>gm("sha256").update(e).digest("hex"),bm=(e,t)=>e==="okx"?new Date(t).toISOString():String(e==="coinbase"?t/1e3:t),xo=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 Da=e=>/^0(?:\.0+)?$/.test(String(e));function Em(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 xm(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:xo(n)}function Sm(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),xo(n)===r.venueOrderId}function Am(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)&&(Da(n.accFillSz)||!Da(n.avgPx))&&(a=Em(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),xo(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 vm(e,t){let r=t?.nowMs?.()??Date.now(),n=t?.transport||Eo,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=La({venue:e.venue,order:e.order,timestamp:bm(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=ym(c.responseBodyBytes);if(e.order.operation==="create"){let f=xm(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",Sm(e.venue,c.value,i)?"cancel-pending":"uncertain",{responseDigest:d,observedAtMs:r});let l;try{l=Am(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 Fa(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||Eo,nowMs:e.nowMs||Date.now,settleLedger:e.settleLedger});return Object.freeze({execute:r=>vm(r,t)})}import{createHash as Im,createHmac as ja,randomBytes as km,timingSafeEqual as Om}from"node:crypto";var qa="oracle-local-signer-cex-owner-allow-v1",jt=e=>/^(?:0|[1-9]\d{0,19})$/.test(String(e||""))?String(e):null,Ma=e=>JSON.stringify(e),Tm=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Om(r,n)};function Ha({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=>Im("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:qa,instance:s,nonce:km(16).toString("hex"),issuedAtMs:p,expiresAtMs:p+l},g=i(h=>ja("sha256",h).update(Ma(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!==qa||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=>ja("sha256",m).update(Ma(c)).digest("hex"));return Tm(u.mac,l)?(o.add(c.nonce),!0):!1}})}var Re=new Oo(["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"]),Wa=new Oo(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),Ao=new Oo(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function Bm({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 Dm(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||re.join(process.env.XDG_STATE_HOME||re.join(Nm.homedir(),".local","state"),"oracle"),r=Cm("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 Fm(e){try{return L(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=_m(32).toString("hex");return Ae(e,t+`
|
|
19
|
+
`),t}function vo(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 Ua(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 Va(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function jm(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 qm(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 qe(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 Mm(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=jm(t,f),w=qm(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(Va(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=Va(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=$m(C).toLowerCase();if(z!==h)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[W,R,$]=await Promise.all([qe(e,i,Re,"collection",_),qe(e,i,Re,"token",_),qe(e,i,Re,"robinhoodSwapFeeWei",_)]),Ke=_e(W,"live Anvil collection"),pt=_e(R,"live Anvil payment token"),qt=BigInt($).toString();if(Ke!==s)throw new Error("signer: live Anvil collection mismatch");if(pt!==u)throw new Error("signer: live Anvil payment token mismatch");if(qt!==a.toString())throw new Error("signer: live Anvil native swap fee mismatch");let Mt=Number(await qe(e,pt,Wa,"decimals",_));if(!Number.isSafeInteger(Mt)||Mt!==c)throw new Error("signer: live Anvil payment token decimals mismatch");let mt=_e(await qe(e,Ke,Ao,"ownerOf",_,[m]),"live Anvil token owner"),Ge=null,Ye=null,Xe=null,Ze=null,q;if(f==="buy"){let[Me,wt,E]=await Promise.all([qe(e,i,Re,"inventory",_,[m]),qe(e,pt,Wa,"allowance",_,[d,i]),e.send("eth_call",[{to:i,data:Re.encodeFunctionData("quoteSpecificBuy",[m])},_])]);Ge=!!Me,Ye=BigInt(wt).toString();let I=Re.decodeFunctionResult("quoteSpecificBuy",E);if(q=Object.freeze({totalCostRaw:BigInt(I[0]).toString(),baseCostRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString(),available:!!I[4]}),JSON.stringify(q)!==JSON.stringify(p))throw new Error("signer: exact Anvil buy quote changed after preparation");if(mt!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!Ge)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt(Ye)!==BigInt(t.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(Ye)<w)throw new Error("signer: live Anvil ERC20 allowance is insufficient");if(!q.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(q.totalCostRaw)!==w)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(q.totalCostRaw)!==BigInt(q.baseCostRaw)+BigInt(q.feeRaw)+BigInt(q.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[Me,wt,E]=await Promise.all([qe(e,Ke,Ao,"getApproved",_,[m]),qe(e,Ke,Ao,"isApprovedForAll",_,[d,i]),e.send("eth_call",[{to:i,data:Re.encodeFunctionData("quoteSellNFT")},_])]);Xe=_e(Me,"live Anvil token approval"),Ze=!!wt;let I=Re.decodeFunctionResult("quoteSellNFT",E);if(q=Object.freeze({netPayoutRaw:BigInt(I[0]).toString(),grossPayoutRaw:BigInt(I[1]).toString(),feeRaw:BigInt(I[2]).toString(),protocolFeeRaw:BigInt(I[3]).toString()}),JSON.stringify(q)!==JSON.stringify(p))throw new Error("signer: exact Anvil sell quote changed after preparation");if(mt!==d)throw new Error("signer: exact Anvil token owner does not match signer");if(Xe!==i&&!Ze)throw new Error("signer: live Anvil NFT approval is insufficient");if(Xe!==_e(t.preconditions?.approvedAddress,"prepared Anvil token approval")||Ze!==!!t.preconditions?.approvedForAll)throw new Error("signer: live Anvil NFT approval changed after preparation");if(BigInt(q.netPayoutRaw)!==w)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(q.netPayoutRaw)+BigInt(q.feeRaw)+BigInt(q.protocolFeeRaw)!==BigInt(q.grossPayoutRaw))throw new Error("signer: exact Anvil sell quote fee arithmetic mismatch")}return Object.freeze({source:"local-signer-trusted-rpc",chainId:4663,market:i,collection:Ke,paymentToken:pt,paymentTokenDecimals:Mt,nativeSwapFeeWei:qt,signerAddress:d,nftAction:f,tokenId:m.toString(),tokenOwner:mt,inventoryMember:Ge,allowanceRaw:Ye,approvedAddress:Xe,approvedForAll:Ze,quote:q,blockNumber:A.toString(),blockHash:v,runtimeCodeHash:z,verifiedAtMs:Number(n)})}function Ja(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 Hm(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:s}={}){let u=Lm(new URL("./anvil-attestation-worker.mjs",import.meta.url)),a={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},c;try{c=Rm(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)}function zm(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=cn(o,r);s.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(o?.surface==="sol"){let c=pn(o,r);s.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(o?.surface==="hl"){let c=We(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=Ue(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=Ve(o,r);s.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
|
|
20
20
|
Confirm exact action
|
|
21
21
|
${[...s,...ya(e,t,r)].join(`
|
|
22
22
|
`)}
|
|
23
|
-
Type digest ${t}: `}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 ko(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 Io(e,t){let r=Array.isArray(t)?t:[t],n=ko(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 Wm({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 Ga(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 Um(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 Ga(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Vm(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 Jm(e,t){return{simulate:async(r,n)=>(We(n,e()),!0),sign:async(r,n)=>{We(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(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?(Ni(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Ci({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{We(o,e());let{Signature:i,keccak256: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 Km(e){return{simulate:async(t,r)=>(Ve(r,e()),!0),sign:async(t,r)=>{Ve(r,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(t,r);return Xt(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=Ve(n,e()),i=Xt(r,t),s=Ri(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 Gm(e,t){return{simulate:async(r,n)=>(tt(n,e()),!0),sign:async(r,n)=>{tt(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(c=>String(c).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: order wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: order wallet must match envelope owner");let 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=tt(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 Ym(e,t){return{simulate:async(r,n)=>(Ue(n,e()),!0),sign:async(r,n)=>{Ue(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(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=Ue(o,i),u=gn(i),{keccak256:a}=await import("ethers"),c=ri({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:u.key}),d=JSON.stringify(c),l=ei({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 Xm(e,t){let r=mo(t);return{simulate:async n=>{let o=e(),i=So.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 Um(o,c,a.index)})),!0},sign:n=>{let o=So.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=So.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 Ga(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 Zm(e,t){let r=mo(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=ko(s),a=Io(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 Vm(c)},sign:n=>{let o=Buffer.from(n.messageBase64,"base64"),i=ko(o),s=Pm.sign(o,r);if(i===1)return Io(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 Io(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 Qm(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 ew(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 Ya({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=Dm(e),d=()=>Object.freeze(Kr(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?Ha({keyFile:c.policyKey,approvedTelegramOwners:m}):null;if(K(l,"cex")&&!f)throw new Error("signer: cex requires an approved Telegram owner context");if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let p=["surfaces","actions","destinations","owners"];l.surfaces.some(E=>String(E).startsWith("evm"))&&p.push("chains","spenders");for(let E of p)if(!Array.isArray(l[E])||l[E].length===0)throw new Error(`signer: ${E} allowlist is empty`);if(l.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-nft"||E==="evm-order")){for(let E of["providers"])if(!Array.isArray(l[E])||l[E].length===0)throw new Error(`signer: ${E} allowlist is empty`)}if(l.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-order")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(E=>String(E).startsWith("evm")&&E!=="evm-order")&&(!Array.isArray(l.selectors)||l.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(l.surfaces.includes("sol")&&(!Array.isArray(l.programs)||l.programs.length===0))throw new Error("signer: programs allowlist is empty");if(K(l,"poly")&&(gn(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(K(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(K(l,"cex")&&(!l.cexAccounts||Object.keys(l.cexAccounts).length===0))throw new Error("signer: cexAccounts allowlist is empty");if(K(l,"hl")){let E=Array.isArray(l.coins)?l.coins.map(String):[],I=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(E.filter(j=>j!=="*"&&j!=="#*").length&&!E.includes("*")&&I.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let w=r?la(r):R(t),g=Qs(c.vault),h=Zs(g,w),y;try{y=ka(h,g.meta)}finally{h.fill(0)}if((Ua(l)||K(l,"hl")||K(l,"poly"))&&vo("evm",y.evm,l.owners),K(l,"btc")&&vo("btc",y.btc,l.owners),K(l,"sol")&&vo("sol",y.sol,l.owners),K(l,"cex")){if(!y.cex||Object.keys(y.cex).length===0)throw new Error("signer: local CEX credential records required");for(let[E,I]of Object.entries(l.cexAccounts)){let T=y.cex[E];if(!T||T.accountId!==I.accountId||!I.venues.includes(T.venue)||I.credentialRecordRef!==E)throw new Error("signer: CEX credential venue/account binding refused")}}let b=Array.isArray(l.chains)?l.chains.filter(E=>Number.isInteger(Number(E))&&String(E).trim()!==""):[],S=Ua(l);if(S&&(b.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(K(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(K(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let A=S?new u(l.rpcUrl,Number(b[0])):null,k=y.evm&&(S||K(l,"hl")||K(l,"poly"))?A?new 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)=>ew(A,E,I,T,{submitPrivate:ta})}:null,_=A?async E=>tw(A,E):void 0,C=new Map,z=E=>E?.surface==="evm-nft"&&String(E?.provider).toLowerCase()==="anvil-nft",W=async(E,I=d(),T="execution")=>{if(!z(E))return null;let j=await Mm(A,E,I,{nowMs:Date.now(),signerAddress:k.address}),G=C.get(Q(E));return G&&Ja(G,j,T),j},L={...v?{evm:v,"evm-swap":v,"evm-bridge":v,"evm-nft":v}:{},...k&&K(l,"evm-order")?{"evm-order":Gm(d,k)}:{},...y.btc?{btc:Xm(d,y.btc)}:{},...y.sol?{sol:Zm(d,y.sol)}:{},...k&&K(l,"hl")?{hl:Jm(d,k)}:{},...k&&K(l,"poly")?{poly:Ym(d,k)}:{},...K(l,"lighter")?{lighter:Km(d)}:{}};Qm(L,n);let $=Oi({...L,...n}),Ke=new Set(Object.keys(L)),pt=new Set(Object.keys(n||{})),qt=l.surfaces.filter(E=>E!=="cex"&&!Ke.has(E)&&!pt.has(E));if(qt.length)throw new Error(`signer: ${qt.join(",")} require local keys or injected surface transports`);let Mt=Date.now(),mt=Mt+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:za.existsSync(c.lock)?(Ge=!0,!1):za.existsSync(c.vault)&&Date.now()<mt,q=Bm({isArmed:Ze,disarmNow:()=>{Ge=!0,Xe(),Ae(c.lock,`disarmed ${new Date().toISOString()}
|
|
23
|
+
Type digest ${t}: `}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 ko(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 Io(e,t){let r=Array.isArray(t)?t:[t],n=ko(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 Wm({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 Ga(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 Um(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 Ga(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Vm(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 Jm(e,t){return{simulate:async(r,n)=>(We(n,e()),!0),sign:async(r,n)=>{We(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(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?(Ni(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Ci({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{We(o,e());let{Signature:i,keccak256: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 Km(e){return{simulate:async(t,r)=>(Ve(r,e()),!0),sign:async(t,r)=>{Ve(r,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(t,r);return Xt(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=Ve(n,e()),i=Xt(r,t),s=Li(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 Gm(e,t){return{simulate:async(r,n)=>(tt(n,e()),!0),sign:async(r,n)=>{tt(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(c=>String(c).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: order wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: order wallet must match envelope owner");let 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=tt(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 Ym(e,t){return{simulate:async(r,n)=>(Ue(n,e()),!0),sign:async(r,n)=>{Ue(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(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=Ue(o,i),u=gn(i),{keccak256:a}=await import("ethers"),c=ri({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:u.key}),d=JSON.stringify(c),l=ei({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 Xm(e,t){let r=mo(t);return{simulate:async n=>{let o=e(),i=So.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 Um(o,c,a.index)})),!0},sign:n=>{let o=So.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=So.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 Ga(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 Zm(e,t){let r=mo(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=ko(s),a=Io(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 Vm(c)},sign:n=>{let o=Buffer.from(n.messageBase64,"base64"),i=ko(o),s=Pm.sign(o,r);if(i===1)return Io(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 Io(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 Qm(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 ew(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 Ya({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=Dm(e),d=()=>Object.freeze(Kr(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?Ha({keyFile:c.policyKey,approvedTelegramOwners:m}):null;if(K(l,"cex")&&!f)throw new Error("signer: cex requires an approved Telegram owner context");if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let p=["surfaces","actions","destinations","owners"];l.surfaces.some(E=>String(E).startsWith("evm"))&&p.push("chains","spenders");for(let E of p)if(!Array.isArray(l[E])||l[E].length===0)throw new Error(`signer: ${E} allowlist is empty`);if(l.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-nft"||E==="evm-order")){for(let E of["providers"])if(!Array.isArray(l[E])||l[E].length===0)throw new Error(`signer: ${E} allowlist is empty`)}if(l.surfaces.some(E=>E==="evm-swap"||E==="evm-bridge"||E==="evm-order")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(E=>String(E).startsWith("evm")&&E!=="evm-order")&&(!Array.isArray(l.selectors)||l.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(l.surfaces.includes("sol")&&(!Array.isArray(l.programs)||l.programs.length===0))throw new Error("signer: programs allowlist is empty");if(K(l,"poly")&&(gn(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(K(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(K(l,"cex")&&(!l.cexAccounts||Object.keys(l.cexAccounts).length===0))throw new Error("signer: cexAccounts allowlist is empty");if(K(l,"hl")){let E=Array.isArray(l.coins)?l.coins.map(String):[],I=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(E.filter(j=>j!=="*"&&j!=="#*").length&&!E.includes("*")&&I.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let w=r?la(r):L(t),g=Qs(c.vault),h=Zs(g,w),y;try{y=ka(h,g.meta)}finally{h.fill(0)}if((Ua(l)||K(l,"hl")||K(l,"poly"))&&vo("evm",y.evm,l.owners),K(l,"btc")&&vo("btc",y.btc,l.owners),K(l,"sol")&&vo("sol",y.sol,l.owners),K(l,"cex")){if(!y.cex||Object.keys(y.cex).length===0)throw new Error("signer: local CEX credential records required");for(let[E,I]of Object.entries(l.cexAccounts)){let T=y.cex[E];if(!T||T.accountId!==I.accountId||!I.venues.includes(T.venue)||I.credentialRecordRef!==E)throw new Error("signer: CEX credential venue/account binding refused")}}let b=Array.isArray(l.chains)?l.chains.filter(E=>Number.isInteger(Number(E))&&String(E).trim()!==""):[],S=Ua(l);if(S&&(b.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(K(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(K(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let A=S?new u(l.rpcUrl,Number(b[0])):null,k=y.evm&&(S||K(l,"hl")||K(l,"poly"))?A?new 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)=>ew(A,E,I,T,{submitPrivate:ta})}:null,_=A?async E=>tw(A,E):void 0,C=new Map,z=E=>E?.surface==="evm-nft"&&String(E?.provider).toLowerCase()==="anvil-nft",W=async(E,I=d(),T="execution")=>{if(!z(E))return null;let j=await Mm(A,E,I,{nowMs:Date.now(),signerAddress:k.address}),G=C.get(Q(E));return G&&Ja(G,j,T),j},R={...v?{evm:v,"evm-swap":v,"evm-bridge":v,"evm-nft":v}:{},...k&&K(l,"evm-order")?{"evm-order":Gm(d,k)}:{},...y.btc?{btc:Xm(d,y.btc)}:{},...y.sol?{sol:Zm(d,y.sol)}:{},...k&&K(l,"hl")?{hl:Jm(d,k)}:{},...k&&K(l,"poly")?{poly:Ym(d,k)}:{},...K(l,"lighter")?{lighter:Km(d)}:{}};Qm(R,n);let $=Oi({...R,...n}),Ke=new Set(Object.keys(R)),pt=new Set(Object.keys(n||{})),qt=l.surfaces.filter(E=>E!=="cex"&&!Ke.has(E)&&!pt.has(E));if(qt.length)throw new Error(`signer: ${qt.join(",")} require local keys or injected surface transports`);let Mt=Date.now(),mt=Mt+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:za.existsSync(c.lock)?(Ge=!0,!1):za.existsSync(c.vault)&&Date.now()<mt,q=Bm({isArmed:Ze,disarmNow:()=>{Ge=!0,Xe(),Ae(c.lock,`disarmed ${new Date().toISOString()}
|
|
24
24
|
`)}}),Me=Vi({host:o,port:i,token:Fm(c.token),policy:l,readPolicy:d,isArmed:Ze,disarm:q.disarm,armGeneration:q.armGeneration,broadcastWithArmFence:q.broadcastWithArmFence,sessionExpiresAtMs:mt,executionOutbox:as({path:c.executionOutbox,now:Date.now}),observeExecutionTransaction:Wm({provider:A,readPolicy:d}),nowMs:Date.now,simulate:async(E,I)=>(await W(I,d(),"before simulation"),xr(I,$).simulate(E,I)),estimateNetworkFees:_,sign:async(E,I)=>(await W(I,d(),"before signing"),xr(I,$).sign(E,I)),verifySigned:(E,I,T)=>Fi(T?.surface||"evm",E,I,T),broadcast:async(E,I,T)=>(await W(T,d(),"before broadcast"),xr(T,$).broadcast(E,I,T)),confirmArtifact:async(E,I,T)=>{let j=await W(E,T),G=await nw(E,I,T,j);return G===!0&&j&&C.set(I,j),G},decodeEconomics:(E,I)=>In(E,I),reserveLedger:(E,I,T={})=>{let j=E?.version===1&&E?.surface?E:null,G=j?.artifact||E;if(z(j)){let Qe=Q(j),He=C.get(Qe);if(!He||Date.now()-Number(He.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let Ht=Hm(I.rpcUrl,G.chainId,j,I,{nowMs:Date.now(),signerAddress:k.address});Ja(He,Ht,"before reservation"),C.set(Qe,Ht)}let dr=j?.tradeId||G?.tradeId;if(!dr)throw new Error("ledger: executable artifact requires a tradeId");let ye;if(j)ye=In(j,I);else{if(G?.value===void 0)throw new Error("ledger: executable artifact value required");let Qe=BigInt(G.value),He=BigInt(G.gasLimit??0),Ht=BigInt(G.maxFeePerGas??G.gasPrice??0);if(He<=0n||Ht<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let To=He*Ht+BigInt(G.l1FeeWei??0)+BigInt(G.operatorFeeWei??0);ye={unit:"wei",value:Qe.toString(),notional:(Qe+To).toString(),fee:To.toString()}}if(Array.isArray(ye.units))return or({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 or({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:dr,...ye,policy:I,retryReleasedTradeId:T.retryReleasedTradeId})},commitLedger:E=>oa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),releaseLedger:E=>ia({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),settleFailedLedger:E=>aa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:E.tradeId}),validateReservation:(E,I,T)=>na({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,reservation:E,policy:I,economics:T}),verifyFeeWaiver:(E,I)=>ua(E,I,c.policyKey),verifyTriggerAttestation:(E,I,T)=>ca(E,I,c.policyKey,T),inspectCex:Xr,verifyOwnerProof:f?(E,I)=>f.verify(E,I):void 0,verifyCexOwnerProof:f?(E,I)=>f.verify(E,I):void 0,cexExecute:K(l,"cex")?async E=>{let I=d(),T=Xr(E,I,Date.now()),j=T.kind==="spot-limit-create"?"create":T.kind==="spot-limit-cancel"?"cancel":"status";j==="create"&&Ta({envelope:E,paths:c,nowMs:Date.now()});let G=j==="create"?{operation:j,symbol:T.symbol,side:T.side,baseSize:T.baseSize,limitPrice:T.limitPrice,clientOrderId:T.clientOrderId}:{operation:j,symbol:T.symbol,venueOrderId:T.venueOrderId};return Fa({credential:ye=>y.cex[ye],settleLedger:({tradeId:ye,disposition:Qe,filledQuote:He})=>sa({file:c.ledger,keyFile:c.policyKey,anchorFile:c.ledgerAnchor,policyAnchorFile:c.policyAnchor,tradeId:ye,expectedUnit:T.unit,filledQuote:He,disposition:Qe})}).execute({venue:T.venue,accountId:T.accountId,credentialRef:T.credentialRef,tradeId:T.tradeId,reservedNotional:T.notional,order:G,store:_a({file:c.cexOrders,keyFile:c.policyKey,anchorFile:c.cexOrdersAnchor})})}:void 0,ledgerObserver:Ks(process.env)?Gs({path:c.workflowLedger,telemetry:Xs(process.env),onError:E=>{try{console.error(`signer: ${E}`)}catch{}}}):null,autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),wt=setTimeout(()=>Me.close(),s);return wt.unref(),Me.on("close",()=>{clearTimeout(wt),Xe()}),Me.listen(i,o),Me}var en="0x420000000000000000000000000000000000000F";function Ka(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 tw(e,t){if(!ve(t?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:r,Transaction:n}=await import("ethers"),o=new r(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce??0,type:t.type,accessList:t.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let s;try{let u=await e.call({to:en,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 rw(e,o,t.gasLimit)}}async function rw(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:en,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Ka(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:en,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:en,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(!Ka(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function nw(e,t,r,n=null){return process.stdin.isTTY?(process.stderr.write(zm(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 Xa=`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.`,tn=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function iw(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(Xa+`
|
|
26
26
|
`),0;let r=tn(e,"--passphrase-file"),n=await Ya({configDir:ow.join(t.configDir||pr(),"signer"),passphraseFile:r,credentialService:tn(e,"--credential-service"),port:Number(tn(e,"--port",9462)),sessionMs:Number(tn(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
|
|
27
|
-
`),await new Promise(o=>n.on("close",o)),0}var
|
|
27
|
+
`),await new Promise(o=>n.on("close",o)),0}var ox={name:"signer",summary:"run the short-lived loopback signer",usage:Xa,run:e=>iw(e.argv||[])};export{ox as default,iw as run};
|