@oracle-agent/oracle 0.25.1 → 0.25.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
- import Ga from"node:path";import Pe from"node:fs";import Nn from"node:os";import ue from"node:path";import{fileURLToPath as _n}from"node:url";var Bn=ue.dirname(_n(import.meta.url)),Qa=ue.resolve(Bn,"../..");function Jr(){return process.env.ORACLE_FAKE_HOME||Nn.homedir()}function Cn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function Re(){return Cn()?process.env.ORACLE_CONFIG_DIR||ue.join(Jr(),".config","oracle"):ue.join(Jr(),".config","oracle")}function Pn(){return ue.join(Re(),"desk.json")}function Rn(){return ue.join(Re(),"env")}function ce({force:e=!1}={}){if(ce._done&&!e)return ce._result||null;ce._done=!0;let t={},r=(o,i)=>{if(i==null)return;let a=String(i).trim();a&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=a,t[o]=a))};try{let o=Rn();if(Pe.existsSync(o))for(let i of Pe.readFileSync(o,"utf8").split(/\r?\n/)){let a=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),r(a[1],s)}}catch{}try{let o=Pn();if(Pe.existsSync(o)){let i=JSON.parse(Pe.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)),ce._result=Object.keys(t).length?t:null,ce._result}try{ce()}catch{}import yn from"node:fs";import J from"node:path";import La from"node:os";import{createHash as Na,randomBytes as _a}from"node:crypto";import{Transaction as Mr}from"@scure/btc-signer";import{ed25519 as Ba}from"@noble/curves/ed25519.js";import Qi from"node:http";import{timingSafeEqual as ea}from"node:crypto";import{createHash as Ui,randomBytes as ji,timingSafeEqual as Wi}from"node:crypto";import{base58 as Ht}from"@scure/base";import{Interface as Xn,MaxUint256 as Zn,isAddress as Qn,keccak256 as Fs,toUtf8Bytes as qs}from"ethers";import{Interface as Kn,isAddress as ys}from"ethers";import{isAddress as ds}from"ethers";import{createHash as Dn,createHmac as Un,timingSafeEqual as jn}from"node:crypto";import{readFileSync as Mn}from"node:fs";import{homedir as Fn}from"node:os";import{join as Me}from"node:path";function qn(){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=Fn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Me(t,".config","oracle")).trim();return[e,Me(r,"exec.env")].filter(Boolean)}return[e,Me(t,".config","oracle","exec.env"),Me(t,".config","mad-desk","exec.env")].filter(Boolean)}function be(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of qn())try{let i=Mn(o,"utf8"),a=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[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 le(e,t,r="guard"){let n=Number(t);if(t==null||!Number.isFinite(n))throw new Error(`${r}: current time must be a finite number (got ${$n(t)})`);let 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 $n(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var Hr=100;function nr(e){return Array.isArray(e)?`[${e.map(nr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${nr(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Wn(e,{required:t=!1}={}){try{return be(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Jn(e){let{signature:t,...r}=e;return r}function Hn(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 Dn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function Vn(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:jn(r,n)}function Gn(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 a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+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 or(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:i,requireSigned:a=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let s=Wn(o,{required:a});if(a&&!s)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(s){let m=Un("sha256",s).update(nr(Jn(e))).digest("hex");if(!Vn(e.signature,m))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 c=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>Hr)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>Hr||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{le({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},t,"auto-slippage quote")}catch(m){throw new Error(`${m.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 f=BigInt(e.quoteAmountOut??0),l=BigInt(e.minAmountOut??0);if(f<=0n||l<=0n)throw new Error("auto-slippage guard amounts must be positive");let p=f*BigInt(1e4-c),d=p/10000n;if(p%10000n!==0n&&(d+=1n),l<d)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let m=Gn(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==Hn(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(m!=null&&m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is hash-bound but the calldata encodes ${m}, not the guard floor ${e.minAmountOut}`)}else{if(m==null){let y=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${y}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${m}`)}}return!0}var Ss=new Kn(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Yn,isAddress as Ts}from"ethers";var Ls=new Yn(["function approve(address spender,uint256 amount) returns (bool)"]),Ns=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function Vr(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=String(e??"").trim();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)}`)}}var Js=new Xn(["function approve(address spender,uint256 amount) returns (bool)"]);function Gr(e,t){let r=String(e||"").trim();if(!Qn(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function eo(e,t="approval amount",{allowZero:r=!1}={}){let n=Vr(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=Zn)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var zr=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),ro=new Set(["0x39509351","0xf9255c1f"]);function H(e){let t=String(e||"").toLowerCase();return t.length<10?!1:zr.has(t.slice(0,10))}function xe(e){if(!H(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=u=>n[u]?"0x"+n[u].slice(24):null,i=u=>n[u]?BigInt("0x"+n[u]):null,a=null,s=null,c=null;switch(r){case"0x095ea7b3":case"0x39509351":a=o(0),s=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),a=o(1),s=i(2);break;case"0xd505accf":a=o(1),s=i(2);break;case"0x8fcbaf0c":{a=o(1),s=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),a=o(1),s=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(a==null||s==null)throw new Error("invalid approve calldata");return{spender:Gr(a,"approval spender"),token:c==null?null:Gr(c,"approval token"),amount:eo(s,"approval amount",{allowZero:!0}),selector:r,additive:ro.has(r)}}import{createHash as to,createHmac as no,timingSafeEqual as oo}from"node:crypto";var io=2,ir=300*1e3,Yr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function ao(e){let t=e==null||e===""?ir:Number(e);return!Number.isFinite(t)||t<0?ir:Math.min(t,Yr)}function ar(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ar).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ar(e[r])}`).join(",")}}`}function Kr(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Xr(e=process.env){return Kr(process.env)||Kr(e)}function so(e=process.env){return String(process.env.ORACLE_STAMP_REQUIRE_MAC||"").trim()==="1"||String(e?.ORACLE_STAMP_REQUIRE_MAC||"").trim()==="1"}function co(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...i}=e||{};return i}function uo(e){let t=co(e);return to("sha256").update(ar(t)).digest("hex")}function lo(e,t=Xr()){return t?no("sha256",t).update(String(e)).digest("hex"):""}function fo(e,t){try{let r=Buffer.from(String(e),"hex"),n=Buffer.from(String(t),"hex");return r.length===0||r.length!==n.length?!1:oo(r,n)}catch{return!1}}function Zr(e,{maxAgeMs:t=ir,nowMs:r=Date.now(),providers:n=null,kinds:o=null,label:i="operator",env:a=process.env}={}){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)!==io)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=uo(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let c=Xr(a),u=String(e.prepareMac||"");if(so(a)||u||c){if(!c)throw new Error(`${i}: prepareMac present or ORACLE_STAMP_REQUIRE_MAC=1 but ORACLE_STAMP_HMAC_SECRET missing in signer`);let y=lo(s,c);if(!u||!fo(u,y))throw new Error(`${i}: prepareMac mismatch \u2014 stamp not from trusted preparer`)}let f=Number(e.preparedAt),l=Number(e.expiresAt),p=ao(t),d=r-f,m=l-f;if(!Number.isFinite(d)||!Number.isFinite(l)||!Number.isFinite(m)||d<0||m<=0||m>Yr||d>p||r>l)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${p})`);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 Fe=e=>String(e||"").toLowerCase(),po=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),mo=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function V(e){try{return mo.has(BigInt(e))}catch{return!1}}var U=(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`)}},Qr=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Se=(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 qe(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(d=>!po.has(d)))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].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");let i=(d,m)=>{try{return BigInt(d)===BigInt(m)}catch{return String(d)===String(m)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(d=>i(d,e.chainId)))throw new Error("policy: chain not allowed");if(Se(e.to,t.destinations,"destination",Fe),Se(String(e.data||"0x").slice(0,10),t.selectors,"selector",d=>String(d).toLowerCase()),Se(e.from,t.owners,"owner",Fe),H(e.data)){let d;try{d=xe(e.data)}catch(y){throw new Error(`policy: malformed approval calldata: ${y?.message||y}`)}Se(d.spender,t.spenders,"spender",Fe),Se(d.token||e.to,t.erc20Tokens,"ERC-20 token",Fe);let m=U(t.maxApproval,"maxApproval");if(BigInt(d.amount)>m)throw new Error("policy: approval exceeds cap");if(d.additive)throw new Error("policy: additive approval cannot be bounded; use approve() with an absolute amount")}if(U(e.value,"value")>U(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=U(e.gasLimit,"gasLimit");if(a>U(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let s=e.maxFeePerGas??e.gasPrice,c=U(s,"feePerGas")*a,u=0n;try{if(V(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&&(u+=U(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(u+=U(e.operatorFeeWei,"operatorFeeWei")),V(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let d=U(n.l1FeeWei,"estimated l1FeeWei")+U(n.operatorFeeWei,"estimated operatorFeeWei");if(u<d)throw new Error("policy: rollup fee attestation understates estimate")}if(c+u>U(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=Qr(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 p=Qr(t.maxTtlMs??12e4,"maxTtlMs");if(p<=0||e.expiresAtMs-r>p)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as et}from"node:crypto";import{Address as ho,NETWORK as wo,OutScript as rt,RawTx as go,SigHash as tt,TEST_NETWORK as yo,Transaction as Eo}from"@scure/btc-signer";var nt=(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)=>{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},xo=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,So=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),ne=e=>So(e)?String(e).toLowerCase():String(e),sr=(e,t)=>Array.isArray(t)&&t.some(r=>ne(r)===ne(e)),Ao=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function vo(e){let t=Buffer.from(go.encode(e)),r=et("sha256").update(t).digest();return Buffer.from(et("sha256").update(r).digest()).reverse().toString("hex")}function To(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(vo(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)||!Ao(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function cr(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(!sr(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?wo:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?yo:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Eo.fromPSBT(bo(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=ho(n);for(let l=0;l<o.inputsLength;l++){let p=o.getInput(l);for(let y of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(xo(p[y]))throw new Error("envelope: signed or finalized PSBT refused");if(p.sighashType!==void 0&&p.sighashType!==tt.DEFAULT&&p.sighashType!==tt.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let d=To(p),m;try{let y=rt.decode(d.script);if(!["wpkh"].includes(y.type))throw new Error("unsupported input");m=i.encode(y)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!sr(m,t.owners)||ne(m)!==ne(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...t.changeAddresses||[]].map(l=>ne(l))),s=0n,c=!1,u=[];for(let l=0;l<o.outputsLength;l++){let p=o.getOutput(l),d;try{d=i.encode(rt.decode(p.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=ne(d);if(u.push(`${d}:${p.amount}`),m===ne(e.destination)){c=!0,s+=p.amount;continue}if(sr(d,t.destinations)){s+=p.amount;continue}if(!a.has(m))throw new Error("policy: Bitcoin output destination not allowed")}if(!c)throw new Error("envelope: Bitcoin destination mismatch");let f;try{f=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(f<0n||f>nt(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(s>nt(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:s.toString(),notional:(s+f).toString(),fee:f.toString(),outputs:Object.freeze(u)})}function ur(e,t){let{unit:r,value:n,notional:o,fee:i}=cr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as fr}from"node:crypto";import{base58 as ut}from"@scure/base";import{getCompiledTransactionMessageDecoder as Io}from"@solana/transaction-messages";var dr="11111111111111111111111111111111",ko="ComputeBudget111111111111111111111111111111",Oo="So11111111111111111111111111111111111111112",lt="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var ft="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Lo=5000n,No=2039280n,_o=37095705934669439343138083508754565189542113879843219016388785533085940283555n,N=57896044618658097711785492504343953926634992332820282019728792003956564819949n,ot=19681161376707505956807079304988542015446066515923890162744021073123829784752n,it=e=>fr("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Bo=new Map([[it("route"),{name:"route",prefixBytes:0}],[it("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),$=(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`)}},Co=(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},K=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),j=e=>String(e||""),Po=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,De=e=>fr("sha256").update(e).digest("hex");function $e(e,t){try{let r=Buffer.from(ut.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function q(e){let t=e%N;return t>=0n?t:N+t}function G(e,t){let r=e;for(;t-- >0n;)r=r*r%N;return r}function Ro(e){let r=e*e%N*e%N,n=G(r,2n)*r%N,o=G(n,1n)*e%N,i=G(o,5n)*o%N,a=G(i,10n)*i%N,s=G(a,20n)*a%N,c=G(s,40n)*s%N,u=G(c,80n)*c%N,f=G(u,80n)*c%N,l=G(f,10n)*i%N;return G(l,2n)*e%N}function Mo(e,t){let r=q(t*t*t),n=q(r*r*t),o=Ro(e*n),i=q(e*r*o),a=q(t*i*i),s=i,c=q(i*ot),u=a===e,f=a===q(-e),l=a===q(-e*ot);return u&&(i=s),(f||l)&&(i=c),(q(i)&1n)===1n&&(i=q(-i)),!u&&!f?null:i}function Fo(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=q(t*t),n=Mo(q(r-1n),q(_o*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function qo(e,t){let r=Buffer.concat([...e,$e(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=fr("sha256").update(r).digest();if(Fo(n))throw new Error("envelope: derived Solana program address is on curve");return ut.encode(n)}function pr(e,t,r=lt){let n=[$e(e,"owner"),$e(r,"token program"),$e(t,"mint")];for(let o=255;o>=0;o--)try{return qo([...n,Buffer.from([o])],ft)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function $o(e,t){return(t.accountIndices||[]).map(r=>j(e.staticAccounts[r]))}function Ae(e){return Buffer.from(e.data||[])}function Do(e,t){return j(e.staticAccounts[t.programAddressIndex])}function dt(e,t){return Number(t)<e.header.numSignerAccounts}function Uo(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 ve(e){return e.accountIndices||[]}function lr(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function at(e,t){let r=ve(t).map(n=>{let o=dt(e,n)?"s":"n",i=Uo(e,n)?"w":"r";return`${n}:${j(e.staticAccounts[n])}:${o}:${i}`});return De(Buffer.from(r.join(`
2
- `)))}function st(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function jo(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function Wo(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function Jo(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||{},a=0,s=0,c=[];for(let u=0;u<t;u++){if(a>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e[a++];if(!o.includes(f))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(f)))throw new Error("policy: Jupiter route variant payload size required");let l=Number(i[String(f)]);if(!Number.isSafeInteger(l)||l<0||l>16)throw new Error("policy: Jupiter route variant payload size invalid");if(a+l+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let p=e.subarray(a,a+l);a+=l;let d=p.toString("hex"),m=r.jupiterRouteVariantPayloads?.[String(f)];if(!Array.isArray(m)||!m.map(String).includes(d))throw new Error("policy: Jupiter route variant payload not allowed");let y=e[a++],w=e[a++],h=e[a++];if(y<1||y>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(w!==u||h!==u+1)throw new Error("envelope: unsupported Jupiter route-plan token index");s+=y,c.push(Object.freeze({swapVariant:f,variantPayloadHex:d,percent:y,inputIndex:w,outputIndex:h}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(s!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function Ho(e,t){let r=Ae({data:e}),n=r.subarray(0,8).toString("hex"),o=Bo.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,a=o.prefixBytes===1?r[8]:null;if(o.prefixBytes===1&&r.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let s=8+o.prefixBytes,c=s+4,u=r.length-i;if(u<=c)throw new Error("envelope: malformed Jupiter route payload");let f=Wo(r,s,"route plan length"),l=r.subarray(c,u),p=Jo(l,f,t);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:f,routePlan:p,routePlanHash:De(l),inAmount:st(r,u,"in_amount"),quotedOutAmount:st(r,u+8,"quoted_out_amount"),slippageBps:jo(r,u+16,"slippage_bps"),platformFeeBps:r[u+18],instructionHash:De(r)})}function Vo(e,t,r){let n=$o(e,t),o=(i,a)=>{let s=n[i];if(!s)throw new Error(`envelope: Jupiter ${a} account missing`);return s};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 ct(e,t){return e&&e!==t?e:null}function D(e,t,r){let n=j(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function Go(e,t){let r=Ae(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 zo(e,t,r,n,o,i){let a=Ae(t);if(a.length!==1||a[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let s=ve(t);if(s.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=D(e,s[0],"ATA payer"),u=D(e,s[1],"ATA account"),f=D(e,s[2],"ATA owner"),l=D(e,s[3],"ATA mint"),p=D(e,s[4],"ATA system program"),d=D(e,s[5],"ATA token program");if(c!==r.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(f!==r.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(p!==dr)throw new Error("envelope: Jupiter ATA system program mismatch");if(d!==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(u!==pr(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:u,debit:i}}function Ko(e,t,r,n,o){let i=ve(t),a=Ae(t);if(i.length!==2||a.length!==12||a.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let s=D(e,i[0],"wrap payer"),c=D(e,i[1],"wrap target"),u=a.readBigUInt64LE(4);if(s!==r.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(u!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return u}function Yo(e,t,r,n){let o=ve(t),i=Ae(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||D(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 a=D(e,o[0],"closeAccount source"),s=D(e,o[1],"closeAccount destination"),c=D(e,o[2],"closeAccount authority");if(a!==n||s!==r.owner||c!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function Xo(e,t,r,n,o,i,a){let s=pr(t.owner,t.artifact.inputMint,a);if(o.userSourceTokenAccount!==s)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=$(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<No)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let u=new Map,f=0n,l=!1,p=!1;for(let d of e.instructions){if(d===n)continue;let m=Do(e,d);if(m===ko)Go(d,r);else if(m===ft){let{ata:y,debit:w}=zo(e,d,t,t.artifact,a,c);u.set(y,w)}else if(m===dr)f+=Ko(e,d,t,s,i);else if(m===a){let y=Yo(e,d,t,s);y.kind==="syncNative"&&(l=!0),y.kind==="closeAccount"&&(p=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(f>0n&&(!l||!p))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(f!==0n&&f!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...u.values()].reduce((d,m)=>d+m,0n)}function Zo(e){let t;try{t=Io().decode(Co(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 Qo(e,t,r){if(e.header.numSignerAccounts!==1||j(e.staticAccounts[0])!==t.owner||!K(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 n=[];for(let o of e.instructions){let i=j(e.staticAccounts[o.programAddressIndex]);if(!i||!K(i,r.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function ei(e,t,r){let n=$(r.lamportsPerSignature,"lamportsPerSignature");if(n<Lo)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:$(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),a=i*n,s=i*o;if(t.exactFeeLamports!==void 0){let u=$(t.exactFeeLamports,"exactFeeLamports");if(u<a)throw new Error("policy: Solana exact fee below the base signature fee");if(u>s)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=s;if(c>$(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function ri(e,t,r,n){let o=0n,i=!1;for(let a of e.instructions){if(j(e.staticAccounts[a.programAddressIndex])!==dr)throw new Error("envelope: unsupported Solana program decoder");let c=a.accountIndices||[];if(c.length!==2||j(e.staticAccounts[c[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let u=j(e.staticAccounts[c[1]]);if(u!==t.destination||!K(u,r.destinations))throw new Error("envelope: Solana destination mismatch");let f=Buffer.from(a.data||[]);if(f.length!==12||f.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=f.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>$(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function ti(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!==Oo)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!K(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Po(r);if(!K(o.inputMint,i)||!K(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=$(o.inAmount,"inAmount"),s=$(o.outAmount,"outAmount"),c=$(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>$(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>$(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(s<=0n||c<=0n||c>s)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let u=j(o.jupiterProgram);if(!u||!K(u,r.programs)||!n.includes(u))throw new Error("policy: Jupiter program not allowed or absent");let f=e.instructions.filter(v=>j(e.staticAccounts[v.programAddressIndex])===u);if(f.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=f[0],p=Ho(l.data,r);if(p.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(p.routeId)))throw new Error("policy: Jupiter shared route id not allowed")}else if(p.routeId!=null)throw new Error("envelope: unexpected Jupiter shared route id");if(!lr(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(p.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(p.inAmount!==a)throw new Error("envelope: Jupiter route in_amount mismatch");if(p.quotedOutAmount!==s)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(p.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let d=p.quotedOutAmount-p.quotedOutAmount*BigInt(p.slippageBps)/10000n;if(c!==d)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(p.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let m=Vo(e,l,p),y=ve(l),w=p.instruction==="shared_accounts_route"?2:1;if(!dt(e,y[w]))throw new Error("envelope: Jupiter transfer authority must be signer");if(m.program!==u)throw new Error("envelope: Jupiter program account mismatch");if(m.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(m.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(m.sourceMint!==void 0&&m.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let h=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[lt];if(!K(m.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let b=pr(t.owner,o.outputMint,m.tokenProgram);if(m.userDestinationTokenAccount!==b)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=ct(m.destinationTokenAccount,u);if(E&&E!==b)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(ct(m.platformFeeAccount,u))throw new Error("policy: Jupiter platform fee account not allowed");if(!lr(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(at(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let S=De(Buffer.from([p.instruction,p.routeId??"",p.routePlanHash,at(e,l)].join(`
3
- `)));if(!lr(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(S))throw new Error("policy: Jupiter route review hash not allowed");let I=Xo(e,t,r,l,m,a,m.tokenProgram),k=a+I;if(k>$(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:k,programs:n}}function mr(e,t){if(e.action!=="transfer"&&e.action!=="swap")throw new Error("envelope: Solana decoder requires transfer or swap action");let r=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(r||{}).some(c=>!n.includes(c)))throw new Error("envelope: unexpected Solana artifact field");if(!K(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=Zo(r),i=Qo(o,e,t),a=e.action==="transfer"?ri(o,e,t,i):ti(o,e,t,i),s=ei(o,r,t);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+s).toString(),fee:s.toString(),programs:Object.freeze(a.programs)})}function hr(e,t){let{unit:r,value:n,notional:o,fee:i}=mr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}var ni=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),oi=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),ii=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-stake-delegate":"delegate"}),ai=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-stake-delegate":"tokenDelegate"}),pt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function mt(e){let t=String(e||"").replace(/\/$/,"");if(!ni.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function wr(e){return/^#\d+$/.test(String(e||""))}function si(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(wr(r)){if(t.hip4===!1)throw new Error("hl: HIP-4 outcome orders are disabled by policy");if(n.includes(r)||n.includes("#*")||n.includes("*")||t.hip4===!0||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 ci(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(a=>{if(typeof a=="string"){let[s,c]=String(a).split(":");return s===e&&Number(c)===t}return String(a?.coin)===e&&Number(a?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(wr(e)){let i=Array.isArray(r.coins)?r.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0||r.hip4===!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 Q(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=pt(r.kind,"kind",48),o=ii[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");if(mt(r.submitTo),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 i=Number(r.nonce);if(!Number.isSafeInteger(i)||i<=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(r.action.type!==ai[n])throw new Error("hl: action type must match kind");if(oi.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let a=pt(r.coin,"coin",64);si(a,t);let s=Number(r.assetId??r.assetIndex);if(!Number.isInteger(s)||s<0)throw new Error("hl: assetId required");if(ci(a,s,t),n==="hip4-order"&&!wr(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"){let c=Number(r.notionalUsd);if(!Number.isFinite(c)||c<=0)throw new Error("hl: notionalUsd required");if(c>Number(t.maxNotionalUsd))throw new Error("hl: notional exceeds cap");if(!["buy","sell"].includes(String(r.side)))throw new Error("hl: side must be buy or sell");if(r.action.type!=="order"||!Array.isArray(r.action.orders)||r.action.orders.length!==1)throw new Error("hl: exactly one signed order is required");let u=r.action.orders[0];if(Number(u.a)!==s)throw new Error("hl: signed asset must match assetId");if(!!u.b!=(r.side==="buy"))throw new Error("hl: signed side must match");if(String(u.s)!==String(r.size))throw new Error("hl: signed size must match");if(String(u.p)!==String(r.price))throw new Error("hl: signed price must match");let f=Number(u.s)*Number(u.p);if(!Number.isFinite(f)||Math.abs(f-c)>1e-6)throw new Error("hl: signed notional must match")}if(n==="perp-leverage"){let c=Number(r.leverage);if(!Number.isInteger(c)||c<1)throw new Error("hl: leverage must be a positive integer");if(c>Number(t.maxLeverage||50))throw new Error("hl: leverage exceeds cap")}if(n==="perp-cancel"){let c=r.action.cancels;if(!Array.isArray(c)||c.length!==1)throw new Error("hl: exactly one cancel is required");if(Number(c[0].a)!==s)throw new Error("hl: signed cancel asset must match assetId")}if(n==="perp-leverage"){if(Number(r.action.asset)!==s)throw new Error("hl: signed leverage asset must match assetId");if(Number(r.action.leverage)!==Number(r.leverage))throw new Error("hl: signed leverage must match")}if(n==="perp-isolated-margin"&&Number(r.action.asset)!==s)throw new Error("hl: signed margin asset must match assetId")}if(n.startsWith("hype-stake")&&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(r.notionalUsd??r.action.wei??0),notional:String(r.notionalUsd??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??r.notionalUsd??0),coin:r.coin||null,submitTo:mt(r.submitTo)})}import{createHmac as ui}from"node:crypto";var fe="0x"+"00".repeat(32);function gr(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 ht({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 a=String(i??Math.floor(Date.now()/1e3)),s=String(r||"").toUpperCase(),c=String(n||"");if(s!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let u=a+s+c+String(o||""),f=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(f,"base64"),p=ui("sha256",l).update(u).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:p,POLY_TIMESTAMP:a,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function li(e,t){let r=Number(e.side)===0?"BUY":Number(e.side)===1?"SELL":null;if(!r)throw new Error("poly: side must be BUY or SELL");if(t&&t!==r)throw new Error("poly: side mismatch");return r}function wt(e,t){let r=BigInt(String(e.makerAmount)),n=BigInt(String(e.takerAmount));if(r<=0n||n<=0n)throw new Error("poly: order amounts must be positive integer micro-units");return Number(t==="BUY"?r:n)/1e6}function fi(e){let t=typeof e=="bigint"?e.toString(10):String(e??"").trim();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 gt({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=li(e,t);if(String(e.metadata||fe).toLowerCase()!==fe)throw new Error("poly: metadata must be zero");if(String(e.builder||fe).toLowerCase()!==fe)throw new Error("poly: builder must be zero");let a=fi(e.salt);return{deferExec:!1,order:{builder:fe,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:fe,salt:String(a),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 di=new Set(["https://clob.polymarket.com/order"]),Te=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),sc=Object.freeze(Te.map(e=>e[0])),pi=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),yt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function Et(e){let t=String(e||"").replace(/\/$/,"");if(!di.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function bt(e){let t=String(e||"").toLowerCase();if(!pi.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function ee(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=yt(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(String(e.destination).toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(Et(r.submitTo),Number(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"||String(o.version)!=="2"||Number(o.chainId)!==137)throw new Error("poly: EIP-712 domain must be official CTF Exchange v2 on Polygon");if(bt(o.verifyingContract),bt(r.exchange),String(o.verifyingContract).toLowerCase()!==String(r.exchange).toLowerCase())throw new Error("poly: exchange/domain mismatch");let i=r.message||r.value;if(!i||typeof i!="object")throw new Error("poly: signed order message required");let a=r.types?.Order;if(!Array.isArray(a)||a.length!==Te.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let d=0;d<Te.length;d+=1)if(a[d]?.name!==Te[d][0]||a[d]?.type!==Te[d][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 s=String(e.owner||"").toLowerCase();if(String(i.maker||"").toLowerCase()!==s)throw new Error("poly: maker must equal owner");if(String(i.signer||"").toLowerCase()!==s)throw new Error("poly: signer must equal owner");if(Number(i.signatureType)!==0)throw new Error("poly: only EOA signatureType 0 is public");if(![0,1].includes(Number(i.side)))throw new Error("poly: side must be BUY or SELL");let c=yt(String(r.tokenId||""),"tokenId",80);if(String(i.tokenId)!==c)throw new Error("poly: tokenId mismatch");let u=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(u.length&&!u.includes(c)&&!u.includes("*"))throw new Error("poly: tokenId not allowed");let f=Number(i.side)===0?"BUY":"SELL";if(r.side&&r.side!==f)throw new Error("poly: side mismatch");let l=wt(i,f),p=Number(r.notionalUsdc);if(!Number.isFinite(p)||Math.abs(p-l)>1e-6)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");if(l>Number(t.maxNotionalUsd??t.maxNotionalUsdc))throw new Error("poly: notional exceeds cap");return Object.freeze({unit:"usdc",value:String(l),notional:String(l),fee:"0",kind:n,tokenId:c,side:f,submitTo:Et(r.submitTo)})}var mi=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),Ie=14,xt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function yr(e){let t=String(e||"").replace(/\/$/,"");if(!mi.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function re(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=xt(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=yr(r.submitTo),i=Number(r.marketIndex);if(!Number.isInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=xt(r.symbol||r.coin,"symbol",32),s=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(s.length&&!s.includes(a)&&!s.includes(String(i))&&!s.includes("*"))throw new Error("lighter: market not allowed");if(!["buy","sell"].includes(String(r.side)))throw new Error("lighter: side must be buy or sell");let c=Number(r.baseAmount),u=Number(r.price);if(!(c>0)||!(u>0))throw new Error("lighter: baseAmount and price required");let f=Number(r.sizeDecimals??0),l=Number(r.priceDecimals??0);if(!Number.isInteger(f)||f<0||f>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(l)||l<0||l>12)throw new Error("lighter: priceDecimals required");let p=c/10**f*(u/10**l),d=Number(r.notionalUsd);if(!Number.isFinite(d)||d<=0)throw new Error("lighter: notionalUsd required");if(!Number.isFinite(p)||Math.abs(p-d)>.01)throw new Error("lighter: notionalUsd must match size and price");if(p>Number(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER))throw new Error("lighter: notional exceeds cap");if(Number(r.txType??Ie)!==Ie)throw new Error("lighter: only official create-order txType is public");return Object.freeze({unit:"usd",value:String(d),notional:String(d),fee:"0",kind:n,symbol:a,marketIndex:i,side:r.side,baseAmount:c,price:u,submitTo:o,actionType:"create-order",amount:String(d)})}var vt=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var br=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0,delegate:0}),hi=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Tt=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"}}),wi=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"}}),gi=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 Ue=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},x=(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`)}},St=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},yi=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},_=(e,t,r)=>{if(!yi(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Er=(e,t,r)=>{Array.isArray(t)&&t.length&&_(e,t,r)},Y=(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},oe=e=>String(e||"0x").slice(0,10).toLowerCase(),It=e=>x(e.gasLimit,"gasLimit")*x(e.maxFeePerGas??e.gasPrice,"feePerGas")+x(e.l1FeeWei??0,"l1FeeWei")+x(e.operatorFeeWei??0,"operatorFeeWei");function de(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 B(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function W(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function Ei(e){if(oe(e)!=="0x095ea7b3")return null;let t=de(e,2,"approval");return{kind:"approval",spender:B(t.word(0),"approval spender"),amount:W(t.word(1),"approval amount")}}function kt(e,t){let r=t==="router02-exact-input-single"?7:8,n=de(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:B(n.word(0),"input token"),outputToken:B(n.word(1),"output token"),recipient:B(n.word(3),"recipient"),amountIn:W(n.word(o),"amountIn"),minimumOut:W(n.word(o+1),"amountOutMinimum")}}function bi(e){let t=de(e,12,"Across depositV3",{dynamicTail:!0}),r=W(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:B(t.word(0),"depositor"),recipient:B(t.word(1),"recipient"),inputToken:B(t.word(2),"input token"),outputToken:B(t.word(3),"output token"),amountIn:W(t.word(4),"inputAmount"),minimumOut:W(t.word(5),"outputAmount"),destinationChainId:W(t.word(6),"destinationChainId")}}function xi(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 At(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 w=10;w+64<=r.length;w+=64)n.push(r.slice(w,w+64));let o=(w,h)=>{if(!n[w])throw new Error(`envelope: malformed ${h}`);return BigInt(`0x${n[w]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let a=i/32,s=Number(o(a,"path offset")),c=n[a+1],u=o(a+(t?3:2),"amountIn"),f=o(a+(t?4:3),"amountOutMinimum"),l=a+s/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let p=Number(o(l,"path length")),d=r.slice(10+(l+1)*64,10+(l+1)*64+p*2),{inputToken:m,outputToken:y}=xi(`0x${d}`);return{kind:"action",action:"swap",inputToken:m,outputToken:y,recipient:B(c,"recipient"),amountIn:u,minimumOut:f}}function Si(e){let t=de(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:B(t.word(0),"input token"),outputToken:B(t.word(1),"output token"),recipient:B(t.word(3),"recipient"),amountIn:W(t.word(5),"amountIn"),minimumOut:W(t.word(6),"amountOutMinimum")}}function Ai(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let p=10;p+64<=t.length;p+=64)r.push(t.slice(p,p+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 a=Number(BigInt(`0x${r[o+1]}`)),s=o+1+a/32,c=Number(BigInt(`0x${r[s]}`)),f=`0x${t.slice(10+(s+1)*64,10+(s+1)*64+c*2)}`,l=oe(f);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return kt(f,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function vi(e,t){let r=oe(e),n=Tt[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{...kt(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...At(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...At(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...Ai(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Si(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...bi(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Ti(e){let t=de(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",contract:B(t.word(0),"mint NFT contract"),feeRecipient:B(t.word(1),"mint fee recipient"),recipient:B(t.word(2),"mint recipient"),quantity:W(t.word(3),"mint quantity")}}function Ii(e,t){let r=oe(e);if(String(t).toLowerCase()==="nft-mint")return ki(e);let n=wi[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{...Ti(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function ki(e){let t=oe(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=gi[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=de(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:W(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function je(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 Ot(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=Y(e.owner,"owner"),s=e.artifact,c=Number(s?.chainId??je(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(_(c,t.chains,"chain"),s?.owner!==void 0&&Y(s.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let u=je(e);if(!u.length||u.length>8)throw new Error("envelope: bounded EVM transaction batch required");let f=0n,l=0n,p=0n;for(let d of u){if(!d||typeof d!="object"||Array.isArray(d))throw new Error("envelope: structured EVM transaction required");if(Number(d.chainId)!==c)throw new Error("envelope: every batch leg must use the same chain");if(Y(d.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(_(oe(d.data),t.selectors,"selector"),f+=x(d.value??0,"value"),l+=x(d.gasLimit,"gasLimit"),p+=It(d),V(c)&&(d.l1FeeWei===void 0||d.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(f>x(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>x(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(p>x(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:u,chainId:c,owner:a,totalValue:f,totalGas:l,totalFee:p}}function Lt(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=Ue(e.provider,"provider",64).toLowerCase();_(i,t.providers,"provider");let a=Ot(e,t,o,{nowMs:r}),s=[],c=-1;for(let m=0;m<a.transactions.length;m++){let y=a.transactions[m],w=Ei(y.data),h;if(w){if(c!==-1)throw new Error("envelope: approval must be before action");if(x(y.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let S=Y(y.to,"approval token");if(_(S,t.tokens,"token"),_(w.spender,t.spenders,"spender"),w.amount>x(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...w,token:S,index:m}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");_(y.to,t.destinations,"destination"),h={...vi(y.data,i),target:Y(y.to,"action target"),index:m},c=m}let b=x(y.value??0,"value"),E=x(y.gasLimit,"gasLimit");s.push({...h,value:b,gas:E,fee:It(y)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let u=s[c],f=o==="evm-swap"?"swap":"bridge";if(u.action!==f||e.action!==f)throw new Error("envelope: surface/action/calldata mismatch");if(Y(e.destination,"destination")!==u.target)throw new Error("envelope: destination must equal decoded action target");if(u.recipient!==a.owner)throw new Error("envelope: decoded recipient must equal owner");if(u.depositor&&u.depositor!==a.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(_(u.inputToken,t.tokens,"input token"),_(u.outputToken,t.tokens,"output token"),u.amountIn<=0n||u.amountIn>x(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(u.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(or(e.autoSlippage,{nowMs:r,chainId:a.chainId,venue:i,tx:a.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(u.minimumOut!==x(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(u.action==="bridge"&&x(e.toChainId,"toChainId")!==u.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=s.filter(m=>m.kind==="approval");if(!new Set([...hi,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(m=>String(m).toLowerCase()):[]]).has(u.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(u.value!==u.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let d=Object.freeze({quoteAmountOut:x(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:x(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...a,decoded:s,action:u,provider:i,authenticatedQuote:d}}function Nt(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 action");let n=Ue(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Er(n,t.providers,"provider");let o=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;o?.oraclePrepared===!0&&Zr(o,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"});let i=Ot(e,t,"evm-nft",{nowMs:r});if(i.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let a=i.transactions[0],s=oe(a.data);_(s,t.selectors,"selector"),_(a.to,t.destinations,"destination");let c=Ii(a.data,n),u=Y(e.contract??e.artifact?.contract,"NFT contract");if(Er(u,t.nftContracts,"NFT contract"),(c.contract||Y(a.to,"NFT contract"))!==u)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==i.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&Er(c.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let l=x(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>x(t.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(c.quantity!==l)throw new Error("envelope: mint calldata quantity mismatch");let p=x(e.totalWei??e.artifact?.totalWei,"totalWei");if(i.totalValue!==p)throw new Error("envelope: mint value does not match declared totalWei");if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&x(e.priceWei??e.artifact.priceWei,"priceWei")*l!==p)throw new Error("envelope: mint price does not match declared totalWei");if(p>x(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...i,provider:n,decoded:[{...c,target:Y(a.to,"mint target"),value:i.totalValue,gas:i.totalGas,fee:i.totalFee}]}}function Oi(e,{localsWaiver:t=!1}={}){if(!(e in br))throw new Error("fee: unknown action");return t?0:br[e]}function We(e,t,{nowMs:r=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:a=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let s=Ue(e.surface,"surface",16);if(!vt.has(s))throw new Error("envelope: unsupported public surface");let c=Ue(e.action,"action",32);_(s,t.surfaces,"surface"),_(c,t.actions,"action"),_(e.owner,t.owners,"owner"),_(e.destination,t.destinations,"destination");let u=St(t.maxTtlMs,"maxTtlMs"),f=St(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>u)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>f)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(s==="evm-swap"||s==="evm-bridge")Lt(e,t,{nowMs:r,routeAttestationSecret:o});else if(s==="evm-nft")Nt(e,t,{nowMs:r});else if(s==="evm"){if(!["transfer","approve"].includes(c))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");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");qe({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:a});let m=String(l.data||"0x").toLowerCase(),y=x(l.value,"EVM value");if(m==="0x"){if(y===0n)throw new Error("envelope: native EVM transfer value required")}else if(H(m)){if(y!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else s==="btc"?ur(e,t):s==="sol"?hr(e,t):s==="hl"?Q(e,t):s==="poly"?ee(e,t):s==="lighter"&&re(e,t);let p=Number(e.fee?.oracleFeeBps)===0&&br[c]!==0;if(e.fee?.waiver||p&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(p&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let d=Oi(c,{localsWaiver:p});if(Number(e.fee?.oracleFeeBps)!==d)throw new Error("fee: final artifact fee mismatch");return!0}var xr=Object.freeze([...vt]),Ec=Object.freeze({...Tt});function Sr(e,t){if(e.surface==="hl")return Q(e,t);if(e.surface==="poly")return ee(e,t);if(e.surface==="lighter")return re(e,t);if(e.surface==="btc")return ur(e,t);if(e.surface==="sol")return hr(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Lt(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=Nt(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(String(e.surface).startsWith("evm")){let r=x(e.artifact?.value,"EVM value"),n=x(e.artifact?.gasLimit,"EVM gasLimit"),o=x(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+x(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+x(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 _t(e={}){let t={};for(let r of xr){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,a)=>n.broadcast(o,structuredClone(i),structuredClone(a))})}}return Object.freeze(t)}function Je(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 Ft}from"node:crypto";import{ed25519 as Mi}from"@noble/curves/ed25519.js";import{base58 as Ut}from"@scure/base";import{RawTx as Ir,SigHash as ae,Transaction as kr}from"@scure/btc-signer";import{Transaction as Or,keccak256 as qt,verifyTypedData as $t}from"ethers";import{encode as Li}from"@msgpack/msgpack";import{keccak256 as Ni,verifyTypedData as _i}from"ethers";var pe=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Ar=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Bt(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 Bi(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Li(e)),Bt(t)];if(r){let a=String(r).replace(/^0x/i,"");if(!/^[0-9a-fA-F]{40}$/.test(a))throw new Error("hl-l1: vaultAddress must be a 20-byte address");i.push(Buffer.from([1]),Buffer.from(a,"hex"))}else i.push(Buffer.from([0]));return n!=null&&i.push(Buffer.from([0]),Bt(n)),Ni(Buffer.concat(i))}function vr(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:Bi(e,t,{vaultAddress:n,expiresAfter:o})}}function Ct(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=vr(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==pe.name||String(t.domain?.version)!==pe.version||Number(t.domain?.chainId)!==pe.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(pe.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(Ar.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 Pt({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 a=vr(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(pe,Ar,a)}function Rt({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:a=null}){try{let s=vr(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:a}),c=_i(pe,Ar,s,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var Ci=[["AccountIndex","account_index","accountIndex"],["ApiKeyIndex","api_key_index","apiKeyIndex"],["ClientOrderIndex","client_order_index","clientOrderIndex"],["Type","type"],["TimeInForce","time_in_force","timeInForce"],["ReduceOnly","reduce_only","reduceOnly"],["TriggerPrice","trigger_price","triggerPrice"],["OrderExpiry","order_expiry","orderExpiry"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"]];function Tr(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)Tr(t);return}for(let t of Object.values(e))Tr(t)}}}function Pi(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 Tr(e),JSON.parse(JSON.stringify(e))}function ie(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 ke(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 Ri(e){let t={};for(let r of Ci){let n=r.filter(a=>e[a]!==void 0&&e[a]!==null);if(!n.length)continue;let o=n.map(a=>String(e[a]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${r[0]}`);let i=e[n[0]];if(typeof i=="function")throw new Error("lighter: signed tx_info cannot include functions");t[r[0]]=i}return t}function Oe(e,t){let r=Pi(t),n=ie(ke(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),"MarketIndex"),o=ie(ke(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),"BaseAmount"),i=ie(ke(r,["Price","price"],"Price"),"Price");if(n!==ie(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(o!==ie(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(i!==ie(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let a=ke(r,["IsAsk","is_ask","isAsk"],"IsAsk");if(a!==0&&a!==1&&a!=="0"&&a!=="1")throw new Error("lighter: signed IsAsk must be 0 or 1");let s=Number(a)===1,c=String(e.side)==="sell";if(s!==c)throw new Error("lighter: signed IsAsk must match the prepared side");let f=["txType","tx_type","TxType"].filter(m=>r[m]!==void 0&&r[m]!==null).length?Number(ie(ke(r,["txType","tx_type","TxType"],"txType"),"txType")):Number(e.txType??Ie);if(f!==Ie)throw new Error("lighter: signed txType must be official create-order");let l={...Ri(r),MarketIndex:Number(n),BaseAmount:Number(o),Price:Number(i),IsAsk:s?1:0,txType:f},p=JSON.stringify(l),d=JSON.parse(p);if(d.MarketIndex!==Number(n)||d.BaseAmount!==Number(o)||d.Price!==Number(i)||d.IsAsk!==(s?1:0)||d.txType!==f)throw new Error("lighter: canonical tx_info mutated");return{txType:f,txInfo:p,submitTo:yr(e.submitTo)}}function Mt(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var me=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},He=e=>String(e||"").toLowerCase();function Fi(e,t){if(typeof e!="string")return!1;let r,n;try{r=Or.from(e),n=Or.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})}catch{return!1}return He(r.from)!==He(t.from)||He(r.to)!==He(t.to)?!1:r.unsignedHash===n.unsignedHash}function qi(e){let t=Buffer.from(Ir.encode(e)),r=Ft("sha256").update(t).digest();return Buffer.from(Ft("sha256").update(r).digest()).reverse().toString("hex")}function Dt(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||qi(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 $i(e,t){let r=me(e),n=me(t.psbt);if(!r||!n)return!1;try{let o=kr.fromPSBT(n),i=kr.fromPSBT(r);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let a=0;a<i.inputsLength;a++){let s=i.getInput(a),c=o.getInput(a);if(!Dt(c)||!Dt(s))return!1;let u=(h,b)=>{if(h==null&&b==null)return!0;if(h==null||b==null)return!1;try{return Buffer.from(h).equals(Buffer.from(b))}catch{return!1}},f=(h,b)=>{if(h==null&&b==null)return!0;if(h==null||b==null)return!1;try{return Buffer.from(Ir.encode(h)).equals(Buffer.from(Ir.encode(b)))}catch{return u(h,b)}};if(!!s.witnessUtxo!=!!c.witnessUtxo||s.witnessUtxo&&(BigInt(s.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!u(s.witnessUtxo.script,c.witnessUtxo.script))||!f(s.nonWitnessUtxo,c.nonWitnessUtxo)||!u(s.redeemScript,c.redeemScript)||!u(s.witnessScript,c.witnessScript)||s.sighashType!==void 0&&s.sighashType!==ae.DEFAULT&&s.sighashType!==ae.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===ae.ALL,p=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===ae.ALL:!1;for(let h of s.partialSig||[]){let b=Array.isArray(h)?h[1]:h;if(!l(b))return!1}if(s.tapKeySig&&!p(s.tapKeySig))return!1;for(let h of s.tapScriptSig||[]){let b=Array.isArray(h)?h[1]:h;if(!p(b))return!1}let d=h=>h[h.length-1]===ae.ALL,m=h=>h.length>=9&&h.length<=73&&h[1]===h.length-3&&h[2]===2,y=h=>{let b=!1;for(let E of h)if(E instanceof Uint8Array){if(E[0]===48){if(!m(E)||!d(E))return!1;b=!0;continue}if(E.length===64){b=!0;continue}if(E.length===65){if(E[64]!==ae.ALL&&E[64]!==ae.DEFAULT)return!1;b=!0}}return b};if(s.finalScriptWitness){let h;if(Array.isArray(s.finalScriptWitness))h=s.finalScriptWitness;else if(s.finalScriptWitness instanceof Uint8Array){let b=s.finalScriptWitness,E=k=>{let v=b[k];return v===void 0?null:v<253?{value:v,next:k+1}:v===253?{value:b[k+1]|b[k+2]<<8,next:k+3}:null},S=E(0);if(!S)return!1;h=[];let I=S.next;for(let k=0;k<S.value;k++){let v=E(I);if(!v||I+v.value>b.length)return!1;h.push(b.slice(v.next,v.next+v.value)),I=v.next+v.value}if(I!==b.length)return!1}else return!1;if(!h.length||!y(h))return!1}if(s.finalScriptSig instanceof Uint8Array&&s.finalScriptSig.length){let h=s.finalScriptSig,b=[],E=0;for(;E<h.length;){let S=h[E];if(S>=1&&S<=75){if(E+1+S>h.length)return!1;b.push(h.slice(E+1,E+1+S)),E+=1+S;continue}if(S===76){let I=h[E+1];if(I===void 0||E+2+I>h.length)return!1;b.push(h.slice(E+2,E+2+I)),E+=2+I;continue}return!1}if(!b.length||!y(b))return!1}if(![s.partialSig,s.tapKeySig,s.tapScriptSig,s.finalScriptSig,s.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function jt(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 Di(e,t,r){let n=me(e),o=me(t.messageBase64);if(!n||!o)return!1;let i=jt(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let s=n.subarray(i.offset,a),c=n.subarray(a);if(!c.equals(o))return!1;try{let u=Ut.decode(String(r));return u.length===32&&Mi.verify(s,c,u)}catch{return!1}}function Wt(e,t,r,n){if(String(e).startsWith("evm"))return Fi(t,r);if(e==="btc")return $i(t,r);if(e==="sol")return Di(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String($t(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return Rt({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($t(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Oe(r,t),!0}catch{return!1}return!1}function Jt(e,t){try{if(String(e).startsWith("evm"))return Or.from(t).hash;if(e==="btc"){let r=me(t);if(!r)return null;let n=kr.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=me(t);if(!r)return null;let n=jt(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Ut.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return qt(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return qt(t)}catch{}return null}var Ji=e=>String(e||"").toLowerCase();function X(e){return Ui("sha256").update(JSON.stringify(e)).digest("hex")}function Nr(e,t,r={}){return qe(e,t,r)}async function Hi(e,t={}){if(!V(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 Vt(e,t,r=!1){if(!V(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}var Ve=class{#e=new Map;constructor({now:t=Date.now}={}){this.now=t}issue({artifact:t,owner:r,ttlMs:n=6e4}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=ji(32).toString("hex");return this.#e.set(o,{digest:X(t),owner:Ji(r),expiresAtMs:this.now()+n}),o}consume(t,r){let n=this.#e.get(String(t));if(!n)throw new Error("confirmation: used or unknown nonce");if(n.expiresAtMs<=this.now())throw this.#e.delete(String(t)),new Error("confirmation: expired nonce");let o=Buffer.from(n.digest,"hex"),i=Buffer.from(X(r),"hex");if(!Wi(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(t)),n}clear(){this.#e.clear()}};function Vi(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(H(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 Gi(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 Ge(e,t){let r=String(t||"");if(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=Ht.decode(r);return n.length===64&&Ht.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 Gt(e,t,r){return!Ge(e,t)||!Ge(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function zi(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 Lr({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:s}){let c=zi(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="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,s())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="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(a)return n.confirmations.consume(r,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=s())throw new Error("confirmation: expired nonce");return i}function Ki(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Yi(e,t){return e&&Ki(e.surface)?je(e):[t]}function Xi(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!Gt(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function Zi(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:Gi(r,n)}}async function zt(e,t,r){if(!r.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:w,...h}=e||{};return h})(),i=Yi(n,o),a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,s=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),c=await Lr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:null,consumeNonce:!0,nowMs:s}),u=X(e),f=(w={})=>{n?We(n,a,w):(Nr(o,a,{nowMs:w.nowMs,networkFees:w.networkFees,requireNetworkFees:w.requireNetworkFees}),Vi(o))},l=async w=>{let h=n&&!String(n.surface||"").startsWith("evm")?void 0:await Hi(w,r);return{nowMs:s(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:h,requireNetworkFees:V(w?.chainId)}};f({nowMs:s(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let w of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[w]!="function")throw new Error(`signer: ${w} is required`);let p=r.reserveLedger(n||e,a);if(!p)throw new Error("signer: ledger reservation required");let d=!1,m=[];try{for(let w of i){if(typeof r.simulate!="function"||await r.simulate(w,n)!==!0)throw new Error("signer: strict affirmative simulation required");let h=await l(w);if(Vt(w,h.networkFees,h.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await Lr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:s}),f(h),r.validateReservation(p,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0),d=!0;let b=await r.sign(w,n);if(typeof r.verifySigned!="function"||await r.verifySigned(b,w,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!r.isArmed())throw new Error("signer: disarmed before broadcast");if(X(e)!==u)throw new Error("signer: artifact mutated after signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await Lr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:s});let E=await l(w);Vt(w,E.networkFees,E.requireNetworkFees),f(E),r.validateReservation(p,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0);let S=await r.broadcast(b,w,n),I=S?.status,k=n?.surface||"evm",v=Xi(S,k),ye=Jt(k,b);if(!Gt(k,v,ye))throw new Error("signer: receipt transaction hash does not match signed bytes");if(I===0||I==="0x0")throw Ge(k,v)?(r.settleFailedLedger(p),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(I!==1&&I!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Ge(k,v))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(Zi(S,v))}}catch(w){throw d||r.releaseLedger(p),w}if(r.commitLedger(p),m.length===1){let w={receipt:m[0]};return n?.surface==="evm-bridge"&&(w.originStatus="success",w.destinationStatus="unverified",w.destinationSuccess=!1,w.note="Origin-chain receipts do not prove destination-chain settlement."),w}let y={receipts:m,status:"success"};return n?.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 Kt=new Set(["127.0.0.1","::1","localhost"]),ra=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&ea(r,n)},C=(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 ta(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 Yt=e=>new Promise((t,r)=>{let n=0,o=[],i=!1;e.on("data",a=>{n+=a.length,n>64*1024&&!i?(i=!0,r(new Error("request refused")),e.resume()):i||o.push(a)}),e.on("end",()=>{if(!i)try{t(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{r(new Error("request refused"))}}),e.on("error",r)});function Xt(e={}){let t=e.host||"127.0.0.1";if(!Kt.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 i of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[i]!="function")throw new Error(`signer: ${i} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Ve,n=e.origin||`http://${t}`;return Qi.createServer(async(i,a)=>{try{let s=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!ra(s,e.token))return C(a,401,{error:"unauthorized"});let c=ta(i.headers.host);if(!Kt.has(c))return C(a,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return C(a,403,{error:"origin refused"});if(i.method==="GET"&&i.url==="/status"){let u=typeof e.readPolicy=="function"?e.readPolicy():e.policy,f=new Set(xr),l=Array.isArray(u?.surfaces)?u.surfaces.filter(p=>typeof p=="string"&&f.has(p)):[];return C(a,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:l,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(i.method==="POST"&&i.url==="/disarm")return e.disarm(),r.clear(),C(a,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return C(a,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return C(a,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return C(a,403,{error:"autonomous signer does not issue human confirmation nonces"});let u=await Yt(i),f=X(u.artifact),l=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(l?.confirmationMode!=="exact-human")return C(a,403,{error:"exact-human policy required"});let p=typeof e.nowMs=="function"?e.nowMs():Date.now();if(u.artifact?.version===1&&u.artifact?.surface)We(u.artifact,l,{nowMs:p,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:d,...m}=u.artifact||{};Nr(m,l,{nowMs:p})}return typeof e.confirmArtifact!="function"?C(a,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(u.artifact,f,l)!==!0?C(a,400,{error:"exact human confirmation refused"}):C(a,200,{confirmationNonce:r.issue({artifact:u.artifact,owner:u.artifact?.owner??u.artifact?.from,ttlMs:u.ttlMs})})}if(i.method==="POST"&&i.url==="/execute"){let u=await Yt(i),f=await zt(u.artifact,u.confirmationNonce,{...e,confirmations:r});return C(a,200,f)}return C(a,404,{error:"not found"})}catch(s){return e.onError?.(String(s?.message||s)),C(a,400,{error:"request refused"})}})}import{createCipheriv as Gc,createDecipheriv as na,randomBytes as oa,scryptSync as ia}from"node:crypto";import T from"node:fs";import he from"node:path";var aa="ORACLE-LOCAL-VAULT",sa=1,Ke=Object.freeze({N:1<<17,r:8,p:1}),ca=256*1024*1024,ua=16*1024;function ze(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 la(e,t,r=Ke){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return ia(n,t,32,{...r,maxmem:ca})}function Zt(e,t){if(e?.magic!==aa||e?.version!==sa)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!==Ke.N||e.kdf.r!==Ke.r||e.kdf.p!==Ke.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=ze(e.kdf.salt,32,"salt"),o=ze(e.cipher.iv,12,"iv"),i=ze(e.tag,16,"tag"),a=ze(e.ciphertext,1,"ciphertext",{max:ua}),{ciphertext:s,tag:c,...u}=e,f=la(t,n);try{let l=na("aes-256-gcm",f,o);return l.setAAD(Buffer.from(JSON.stringify(u))),l.setAuthTag(i),Buffer.concat([l.update(a),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{f.fill(0)}}function fa(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 da(e){let t=he.dirname(e),r=T.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=T.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 O(e){let t;try{t=T.openSync(e,T.constants.O_RDONLY|T.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=T.fstatSync(t);if(fa(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=T.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 T.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{T.closeSync(t)}}function Qt(e){return JSON.parse(O(e))}function te(e,t){T.mkdirSync(he.dirname(e),{recursive:!0,mode:448}),da(e);let r=he.join(he.dirname(e),`.${he.basename(e)}.${process.pid}.${oa(6).toString("hex")}.tmp`);try{let n=T.openSync(r,T.constants.O_CREAT|T.constants.O_EXCL|T.constants.O_WRONLY|T.constants.O_NOFOLLOW,384);try{T.writeFileSync(n,String(t)),T.fsyncSync(n)}finally{T.closeSync(n)}T.renameSync(r,e),T.chmodSync(e,384);let o=T.openSync(he.dirname(e),"r");try{T.fsyncSync(o)}finally{T.closeSync(o)}}catch(n){try{T.unlinkSync(r)}catch{}throw n}}import{createHmac as ma,randomBytes as ha,timingSafeEqual as wa}from"node:crypto";import P from"node:fs";import se from"node:path";import{homedir as _r}from"node:os";import{join as Br}from"node:path";var en=process.env.ORACLE_PUBLIC_DESKTOP==="1",pa=en?process.env.ORACLE_CONFIG_DIR||Br(_r(),".config","oracle"):Br(_r(),".config","oracle"),Qc=en?pa:Br(_r(),".config","mad-desk");var ou="0".repeat(64),iu=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 Ye(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Ye).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Ye(e[r])).join(",")+"}"}var au=Promise.resolve();function we(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=a=>{try{return P.realpathSync(a)}catch{return se.resolve(a)}},n=r(se.dirname(se.resolve(e))),o=r(se.dirname(se.resolve(t))),i=(a,s)=>s===a||s.startsWith(a+se.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var ga=864e5,F=(e,t)=>ma("sha256",t).update(Ye(e)).digest("hex"),z=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&wa(r,n)},ya=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Ea(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!z(e.integrity.mac,F(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Ze(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=O(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!z(n?.integrity?.mac,F(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 ba(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 s=Ze(e,r);i=s.present&&s.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(t),policyMac:String(n)};i&&(a.ledgerInitialized=!0),te(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:F(a,r)}})+`
4
- `)}function xa(e,t){let r=Ze(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 ba(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function rn(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=O(t),o;try{o=JSON.parse(O(e))}catch(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=Ea(o,n);we(r,e);let a=Ze(r,n),s=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(s!==a.sequence)throw new Error("policy: rolled back to a superseded policy");if(a.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!z(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Ne(e,t,r,n,o){let i=`${e}.continuity`,a;try{let s=JSON.parse(O(e));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!z(s?.integrity?.mac,F(s.ledger,t)))throw new Error("integrity verification failed");if(a=s.ledger,!Number.isFinite(a?.windowStartMs)||!Array.isArray(a?.entries)||a.sequence!==void 0&&(!Number.isSafeInteger(a.sequence)||a.sequence<0))throw new Error("invalid ledger")}catch(s){if(s?.code==="ENOENT"){if(P.existsSync(i)||P.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=Ze(o,t);if(c.present&&c.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:r,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${s?.message||s}`)}try{let s=JSON.parse(O(i));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!z(s?.integrity?.mac,F(s.marker,t)))throw new Error("continuity verification failed");if(s.marker?.version===2&&(s.marker.sequence!==a.sequence||!z(s.marker.ledgerMac,F(a,t))))throw new Error("continuity rollback detected");if(s.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(P.existsSync(n)&&(s.marker?.version!==2||a.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(s.marker?.version===2){let c=JSON.parse(O(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!z(c?.integrity?.mac,F(c.marker,t))||c.marker?.version!==1||c.marker.sequence!==a.sequence||!z(c.marker.ledgerMac,F(a,t)))throw new Error("checkpoint rollback detected")}}catch(s){throw new Error(`ledger: corrupt or unreadable: ${s?.message||s}`)}if(r-a.windowStartMs>=ga){let s=a.entries.map(c=>c.state==="reserved"?c:{...c,state:"consumed",value:"0",notional:"0"});return{windowStartMs:r,entries:s,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function Xe(e,t,r){return e.filter(n=>(n.unit||"wei")===r).reduce((n,o)=>n+BigInt(o[t]??0),0n)}function tn(e,t){let r=t==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:t==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:t==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:null;if(!r)throw new Error("ledger: unsupported accounting unit");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 _e(e,t){let r=`${e}.lock`,n=ha(16).toString("hex"),o;try{o=P.openSync(r,P.constants.O_CREAT|P.constants.O_EXCL|P.constants.O_WRONLY|(P.constants.O_NOFOLLOW||0),384),P.writeFileSync(o,n),P.fsyncSync(o)}catch(i){throw o!==void 0&&P.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return t()}finally{P.closeSync(o);try{O(r)===n&&P.unlinkSync(r)}catch{}}}function Le(e,t,r,n,o){let i=`${e}.continuity`,a={...t,sequence:(t.sequence??0)+1},s=F(a,r);te(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:s}})+`
5
- `);let c={version:2,sequence:a.sequence,ledgerMac:s};te(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:F(c,r)}})+`
6
- `);let u={version:1,sequence:a.sequence,ledgerMac:s};P.mkdirSync(se.dirname(n),{recursive:!0,mode:448}),te(n,JSON.stringify({marker:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:F(u,r)}})+`
7
- `),o&&xa(o,r)}function nn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:s=0,fee:c,policy:u,nowMs:f=Date.now()}){let l=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(l))throw new Error("ledger: bounded tradeId required");we(r,e);let p=O(t);return _e(e,()=>{let d=Ne(e,p,f,r,n);if(d.entries.some(S=>String(S.tradeId)===l))throw new Error("ledger: replayed tradeId");let m=BigInt(a),y=BigInt(s),[w,h,b]=tn(u,i);if(m<0n||y<0n||y>b)throw new Error("ledger: per-trade cap exceeded");if(Xe(d.entries,"value",i)+m>w||Xe(d.entries,"notional",i)+y>h)throw new Error("ledger: daily cap exceeded");let E={tradeId:l,unit:i,value:m.toString(),notional:y.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:f};return d.entries.push(E),Le(e,d,p,r,n),structuredClone(E)})}function on({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:s=Date.now()}){we(r,e);let c=O(t);return _e(e,()=>{let u=Ne(e,c,s,r,n),f=u.entries.find(y=>String(y.tradeId)===String(o?.tradeId??"")&&y.state==="reserved");if(!f||f.unit!==o.unit||f.value!==o.value||f.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==f.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(f.value)||BigInt(a.notional)>BigInt(f.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=f.unit||"wei",[p,d,m]=tn(i,l);if(BigInt(f.notional)>m)throw new Error("ledger: per-trade cap exceeded");if(Xe(u.entries,"value",l)>p||Xe(u.entries,"notional",l)>d)throw new Error("ledger: daily cap exceeded");return structuredClone(f)})}function an({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){we(r,e);let a=O(t);return _e(e,()=>{let s=Ne(e,a,i,r,n),c=s.entries.find(u=>String(u.tradeId)===String(o??"")&&u.state==="reserved");if(!c||c.state!=="reserved")throw new Error("ledger: reservation unavailable");return c.state="committed",c.committedAtMs=i,Le(e,s,a,r,n),structuredClone(c)})}function sn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){we(r,e);let a=O(t);return _e(e,()=>{let s=Ne(e,a,i,r,n),c=s.entries.findIndex(f=>String(f.tradeId)===String(o??"")&&f.state==="reserved");if(c<0)throw new Error("ledger: reservation unavailable");let[u]=s.entries.splice(c,1);return Le(e,s,a,r,n),structuredClone(u)})}function cn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){we(r,e);let a=O(t);return _e(e,()=>{let s=Ne(e,a,i,r,n),c=s.entries.find(f=>String(f.tradeId)===String(o??"")&&f.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");let u=BigInt(c.fee??0);return u<=0n?(c.state="committed",c.committedAtMs=i,c.value="0",c.notional="0",c.settledAs="no-fee",Le(e,s,a,r,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=u.toString(),c.settledAs="fee-only",Le(e,s,a,r,n),structuredClone(c))})}function un(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:X(ya(t))};return z(e.mac,F(o,O(r)))}function Sa(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function ln(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:X(Sa(t))};return z(e.mac,F(o,O(r)))}import{spawnSync as Aa}from"node:child_process";function fn(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=Aa(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}import{Wallet as Cr}from"ethers";import{base58 as mn}from"@scure/base";import{ed25519 as va}from"@noble/curves/ed25519.js";import{NETWORK as hn,TEST_NETWORK as wn,WIF as Ta,p2wpkh as dn}from"@scure/btc-signer";import{pubECDSA as Ia}from"@scure/btc-signer/utils.js";var ka=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Oa=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},ge=(e,t)=>{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`)};function Pr(e,t){let r=String(t||"").trim();if(e==="evm")return new Cr(r).privateKey;if(e==="btc")for(let i of[hn,wn])try{return Buffer.from(Ta(i).decode(r))}catch{}if(e==="sol")try{return ge(mn.decode(r),"sol")}catch{}let n=ka(r);if(n)return e==="evm"?new Cr(`0x${n.toString("hex")}`).privateKey:ge(n,e);let o=Oa(r);if(o)return ge(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return ge(Uint8Array.from(i),e);let a=i.privateKey??i.secretKey??i.key;if(a)return Pr(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function pn(e,t){if(e==="evm"){let r=new Cr(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=ge(t,"btc"),n=Ia(r);return{kind:e,secret:r.toString("hex"),addresses:[dn(n,hn).address,dn(n,wn).address]}}if(e==="sol"){let r=ge(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[mn.encode(va.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function gn(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:pn(t.kind||"evm",Pr(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=pn(i,Pr(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function Rr(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}function Ca(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||J.join(process.env.XDG_STATE_HOME||J.join(La.homedir(),".local","state"),"oracle"),r=Na("sha256").update(J.resolve(e)).digest("hex").slice(0,16);return{vault:J.join(e,"vault.json"),policy:J.join(e,"signer-policy.json"),policyKey:J.join(e,"policy-integrity-key"),policyAnchor:J.join(t,`signer-policy-${r}.high-water`),ledger:J.join(e,"signer-ledger.json"),ledgerAnchor:J.join(t,`signer-ledger-${r}.high-water`),token:J.join(e,"signer-token"),lock:J.join(t,`signer-${r}.lock`)}}function Pa(e){try{return O(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=_a(32).toString("hex");return te(e,t+`
8
- `),t}function Fr(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 En(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function R(e,t){return e.surfaces.includes(t)}function Ra(e,t,r){let n=e?.version===1&&e?.surface?e:null,o=n?.artifact||e||{},i=[`surface=${n?.surface||"evm"} action=${n?.action||"evm"}`,`chain=${o.chainId??o.network??o.cluster??"n/a"} owner=${n?.owner||o.from||"n/a"}`,`to=${o.to||n?.destination||"n/a"} calldata=${String(o.data||"0x")} value=${o.value??"n/a"}`,`gas=${o.gasLimit??"n/a"} maxFeePerGas=${o.maxFeePerGas??o.gasPrice??"n/a"} maxPriorityFeePerGas=${o.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${o.l1FeeWei??"n/a"} operatorFeeWei=${o.operatorFeeWei??"n/a"}`,`nonce=${o.nonce??"n/a"} type=${o.type??"n/a"} accessList=${Array.isArray(o.accessList)?o.accessList.length:0}`,`slippageBps=${n?.slippageBps??o.slippageBps??"n/a"} expiresAtMs=${n?.expiresAtMs??o.expiresAtMs??"n/a"}`],a=(c,u)=>{if(i.push(`LEG ${u} chain=${c.chainId??"n/a"} from=${c.from??"n/a"} to=${c.to??"n/a"}`),i.push(`LEG ${u} calldata=${String(c.data||"0x")} value=${c.value??"n/a"}`),i.push(`LEG ${u} gas=${c.gasLimit??"n/a"} maxFeePerGas=${c.maxFeePerGas??c.gasPrice??"n/a"} maxPriorityFeePerGas=${c.maxPriorityFeePerGas??"n/a"}`),i.push(`LEG ${u} l1FeeWei=${c.l1FeeWei??"n/a"} operatorFeeWei=${c.operatorFeeWei??"n/a"} nonce=${c.nonce??"n/a"} type=${c.type??"n/a"}`),H(String(c.data||"0x")))try{let f=xe(String(c.data||"0x"));i.push(`LEG ${u} APPROVAL token=${f.token||c.to||"n/a"} spender=${f.spender} amount=${f.amount}`)}catch{i.push(`LEG ${u} APPROVAL spender=undecodable amount=undecodable`)}},s=String(o.data||"0x");if(H(s))try{let c=xe(s);i.push(`APPROVAL token=${c.token||o.to||"n/a"} spender=${c.spender} amount=${c.amount}`)}catch{i.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(o.transactions)&&(i.push(`batchLegs=${o.transactions.length}`),o.transactions.forEach((c,u)=>a(c,u))),n?.surface==="btc"){let c=cr(n,r);i.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(n?.surface==="sol"){let c=mr(n,r);i.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(n?.surface==="hl"){let c=Q(n,r);i.push(`hlKind=${c.kind} actionType=${c.actionType} coin=${c.coin||"n/a"} amount=${c.amount} notionalUsd=${c.notional} submitTo=${c.submitTo}`)}if(n?.surface==="poly"){let c=ee(n,r);i.push(`polyKind=${c.kind} tokenId=${c.tokenId} notionalUsdc=${c.notional} submitTo=${c.submitTo}`)}if(n?.surface==="lighter"){let c=re(n,r);i.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
1
+ import ca from"node:path";import De from"node:fs";import qn from"node:os";import me from"node:path";import{fileURLToPath as Dn}from"node:url";var Un=me.dirname(Dn(import.meta.url)),ma=me.resolve(Un,"../..");function et(){return process.env.ORACLE_FAKE_HOME||qn.homedir()}function jn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function Ue(){return jn()?process.env.ORACLE_CONFIG_DIR||me.join(et(),".config","oracle"):me.join(et(),".config","oracle")}function Wn(){return me.join(Ue(),"desk.json")}function Hn(){return me.join(Ue(),"env")}function pe({force:e=!1}={}){if(pe._done&&!e)return pe._result||null;pe._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=Hn();if(De.existsSync(o))for(let i of De.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let a=s[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(s[1],a)}}catch{}try{let o=Wn();if(De.existsSync(o)){let i=JSON.parse(De.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)),pe._result=Object.keys(t).length?t:null,pe._result}try{pe()}catch{}import kn from"node:fs";import z from"node:path";import Hs from"node:os";import{createHash as Js,randomBytes as Gs}from"node:crypto";import{Transaction as Gr}from"@scure/btc-signer";import{ed25519 as zs}from"@noble/curves/ed25519.js";import ms from"node:http";import{timingSafeEqual as hs}from"node:crypto";import{createHash as ts,randomBytes as ns,timingSafeEqual as os}from"node:crypto";import{base58 as en}from"@scure/base";import{Interface as so,MaxUint256 as ao,isAddress as co,keccak256 as Za,toUtf8Bytes as Qa}from"ethers";import{Interface as oo,isAddress as Ca}from"ethers";import{isAddress as ka}from"ethers";import{createHash as Kn,createHmac as Yn,timingSafeEqual as Xn}from"node:crypto";import{readFileSync as Jn}from"node:fs";import{homedir as Gn}from"node:os";import{join as je}from"node:path";function zn(){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=Gn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||je(t,".config","oracle")).trim();return[e,je(r,"exec.env")].filter(Boolean)}return[e,je(t,".config","oracle","exec.env"),je(t,".config","mad-desk","exec.env")].filter(Boolean)}function Oe(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of zn())try{let i=Jn(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 he(e,t,r="guard"){let n=Number(t);if(t==null||!Number.isFinite(n))throw new Error(`${r}: current time must be a finite number (got ${Vn(t)})`);let 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 Vn(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var rt=100;function lr(e){return Array.isArray(e)?`[${e.map(lr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${lr(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Zn(e,{required:t=!1}={}){try{return Oe(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Qn(e){let{signature:t,...r}=e;return r}function eo(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 Kn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function ro(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:Xn(r,n)}function to(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 dr(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 a=Zn(o,{required:s});if(s&&!a)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(a){let p=Yn("sha256",a).update(lr(Qn(e))).digest("hex");if(!ro(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 c=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>rt)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>rt||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{he({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 f=d*BigInt(1e4-c),m=f/10000n;if(f%10000n!==0n&&(m+=1n),l<m)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let p=to(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==eo(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 g=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${g}; 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 Ra=new oo(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as io,isAddress as Da}from"ethers";var Ha=new io(["function approve(address spender,uint256 amount) returns (bool)"]),Ja=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function k(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 R(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function Q(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=k(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 fr(e,t="amount"){let r=Q(e,t);if(r<=0n)throw new Error(`${t} must be positive`);return r}function _(e,t,r="amount"){let n=k(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",a=""]=i.split(".");if(a.length>t)throw new Error(`${r} has more than ${t} decimal places, which would lose precision`);let c=BigInt((s||"0")+a.padEnd(t,"0"));return o?-c:c}var ic=new so(["function approve(address spender,uint256 amount) returns (bool)"]);function tt(e,t){let r=String(e||"").trim();if(!co(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function uo(e,t="approval amount",{allowZero:r=!1}={}){let n=Q(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=ao)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var nt=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),lo=new Set(["0x39509351","0xf9255c1f"]);function V(e){let t=String(e||"").toLowerCase();return t.length<10?!1:nt.has(t.slice(0,10))}function Le(e){if(!V(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=u=>n[u]?"0x"+n[u].slice(24):null,i=u=>n[u]?BigInt("0x"+n[u]):null,s=null,a=null,c=null;switch(r){case"0x095ea7b3":case"0x39509351":s=o(0),a=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),s=o(1),a=i(2);break;case"0xd505accf":s=o(1),a=i(2);break;case"0x8fcbaf0c":{s=o(1),a=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),s=o(1),a=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(s==null||a==null)throw new Error("invalid approve calldata");return{spender:tt(s,"approval spender"),token:c==null?null:tt(c,"approval token"),amount:uo(a,"approval amount",{allowZero:!0}),selector:r,additive:lo.has(r)}}import{createHash as fo,createHmac as cc,timingSafeEqual as uc}from"node:crypto";var po=2,pr=300*1e3,ot=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function mo(e){let t=e==null||e===""?pr:Number(e);return!Number.isFinite(t)||t<0?pr:Math.min(t,ot)}function mr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(mr).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${mr(e[r])}`).join(",")}}`}function ho(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function wo(e){let t=ho(e);return fo("sha256").update(mr(t)).digest("hex")}function it(e,{maxAgeMs:t=pr,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)!==po)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=wo(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let a=Number(e.preparedAt),c=Number(e.expiresAt),u=mo(t),d=r-a,l=c-a;if(!Number.isFinite(d)||!Number.isFinite(c)||!Number.isFinite(l)||d<0||l<=0||l>ot||d>u||r>c)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${u})`);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 We=e=>String(e||"").toLowerCase(),go=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),yo=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function K(e){try{return yo.has(BigInt(e))}catch{return!1}}var H=(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`)}},st=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ne=(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 He(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(m=>!go.has(m)))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].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");let i=(m,p)=>{try{return BigInt(m)===BigInt(p)}catch{return String(m)===String(p)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(m=>i(m,e.chainId)))throw new Error("policy: chain not allowed");if(Ne(e.to,t.destinations,"destination",We),Ne(String(e.data||"0x").slice(0,10),t.selectors,"selector",m=>String(m).toLowerCase()),Ne(e.from,t.owners,"owner",We),V(e.data)){let m;try{m=Le(e.data)}catch(g){throw new Error(`policy: malformed approval calldata: ${g?.message||g}`)}Ne(m.spender,t.spenders,"spender",We),Ne(m.token||e.to,t.erc20Tokens,"ERC-20 token",We);let p=H(t.maxApproval,"maxApproval");if(BigInt(m.amount)>p)throw new Error("policy: approval exceeds cap");if(m.additive)throw new Error("policy: additive approval cannot be bounded; use approve() with an absolute amount")}if(H(e.value,"value")>H(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=H(e.gasLimit,"gasLimit");if(s>H(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let a=e.maxFeePerGas??e.gasPrice,c=H(a,"feePerGas")*s,u=0n;try{if(K(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&&(u+=H(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(u+=H(e.operatorFeeWei,"operatorFeeWei")),K(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let m=H(n.l1FeeWei,"estimated l1FeeWei")+H(n.operatorFeeWei,"estimated operatorFeeWei");if(u<m)throw new Error("policy: rollup fee attestation understates estimate")}if(c+u>H(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=st(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 f=st(t.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-r>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as at}from"node:crypto";import{Address as Eo,NETWORK as xo,OutScript as ct,RawTx as bo,SigHash as ut,TEST_NETWORK as So,Transaction as Ao}from"@scure/btc-signer";var lt=(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`)}},vo=(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},Io=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,To=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),ue=e=>To(e)?String(e).toLowerCase():String(e),hr=(e,t)=>Array.isArray(t)&&t.some(r=>ue(r)===ue(e)),ko=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function Oo(e){let t=Buffer.from(bo.encode(e)),r=at("sha256").update(t).digest();return Buffer.from(at("sha256").update(r).digest()).reverse().toString("hex")}function Lo(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(Oo(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)||!ko(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function wr(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(!hr(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?xo:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?So:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Ao.fromPSBT(vo(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=Eo(n);for(let l=0;l<o.inputsLength;l++){let f=o.getInput(l);for(let g of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(Io(f[g]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==ut.DEFAULT&&f.sighashType!==ut.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let m=Lo(f),p;try{let g=ct.decode(m.script);if(!["wpkh"].includes(g.type))throw new Error("unsupported input");p=i.encode(g)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!hr(p,t.owners)||ue(p)!==ue(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let s=new Set([e.owner,...t.changeAddresses||[]].map(l=>ue(l))),a=0n,c=!1,u=[];for(let l=0;l<o.outputsLength;l++){let f=o.getOutput(l),m;try{m=i.encode(ct.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let p=ue(m);if(u.push(`${m}:${f.amount}`),p===ue(e.destination)){c=!0,a+=f.amount;continue}if(hr(m,t.destinations)){a+=f.amount;continue}if(!s.has(p))throw new Error("policy: Bitcoin output destination not allowed")}if(!c)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>lt(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(a>lt(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:a.toString(),notional:(a+d).toString(),fee:d.toString(),outputs:Object.freeze(u)})}function gr(e,t){let{unit:r,value:n,notional:o,fee:i}=wr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as Er}from"node:crypto";import{base58 as wt}from"@scure/base";import{getCompiledTransactionMessageDecoder as No}from"@solana/transaction-messages";var xr="11111111111111111111111111111111",_o="ComputeBudget111111111111111111111111111111",Bo="So11111111111111111111111111111111111111112",gt="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var yt="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Co=5000n,Po=2039280n,$o=37095705934669439343138083508754565189542113879843219016388785533085940283555n,B=57896044618658097711785492504343953926634992332820282019728792003956564819949n,dt=19681161376707505956807079304988542015446066515923890162744021073123829784752n,ft=e=>Er("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Mo=new Map([[ft("route"),{name:"route",prefixBytes:0}],[ft("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),j=(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`)}},Ro=(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},ee=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),J=e=>String(e||""),Fo=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,Ge=e=>Er("sha256").update(e).digest("hex");function Je(e,t){try{let r=Buffer.from(wt.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function U(e){let t=e%B;return t>=0n?t:B+t}function Y(e,t){let r=e;for(;t-- >0n;)r=r*r%B;return r}function qo(e){let r=e*e%B*e%B,n=Y(r,2n)*r%B,o=Y(n,1n)*e%B,i=Y(o,5n)*o%B,s=Y(i,10n)*i%B,a=Y(s,20n)*s%B,c=Y(a,40n)*a%B,u=Y(c,80n)*c%B,d=Y(u,80n)*c%B,l=Y(d,10n)*i%B;return Y(l,2n)*e%B}function Do(e,t){let r=U(t*t*t),n=U(r*r*t),o=qo(e*n),i=U(e*r*o),s=U(t*i*i),a=i,c=U(i*dt),u=s===e,d=s===U(-e),l=s===U(-e*dt);return u&&(i=a),(d||l)&&(i=c),(U(i)&1n)===1n&&(i=U(-i)),!u&&!d?null:i}function Uo(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=U(t*t),n=Do(U(r-1n),U($o*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function jo(e,t){let r=Buffer.concat([...e,Je(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=Er("sha256").update(r).digest();if(Uo(n))throw new Error("envelope: derived Solana program address is on curve");return wt.encode(n)}function br(e,t,r=gt){let n=[Je(e,"owner"),Je(r,"token program"),Je(t,"mint")];for(let o=255;o>=0;o--)try{return jo([...n,Buffer.from([o])],yt)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function Wo(e,t){return(t.accountIndices||[]).map(r=>J(e.staticAccounts[r]))}function _e(e){return Buffer.from(e.data||[])}function Ho(e,t){return J(e.staticAccounts[t.programAddressIndex])}function Et(e,t){return Number(t)<e.header.numSignerAccounts}function Jo(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 Be(e){return e.accountIndices||[]}function yr(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function pt(e,t){let r=Be(t).map(n=>{let o=Et(e,n)?"s":"n",i=Jo(e,n)?"w":"r";return`${n}:${J(e.staticAccounts[n])}:${o}:${i}`});return Ge(Buffer.from(r.join(`
2
+ `)))}function mt(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function Go(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function zo(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function Vo(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,a=0,c=[];for(let u=0;u<t;u++){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 f=e.subarray(s,s+l);s+=l;let m=f.toString("hex"),p=r.jupiterRouteVariantPayloads?.[String(d)];if(!Array.isArray(p)||!p.map(String).includes(m))throw new Error("policy: Jupiter route variant payload not allowed");let g=e[s++],w=e[s++],h=e[s++];if(g<1||g>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(w!==u||h!==u+1)throw new Error("envelope: unsupported Jupiter route-plan token index");a+=g,c.push(Object.freeze({swapVariant:d,variantPayloadHex:m,percent:g,inputIndex:w,outputIndex:h}))}if(s!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(a!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function Ko(e,t){let r=_e({data:e}),n=r.subarray(0,8).toString("hex"),o=Mo.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 a=8+o.prefixBytes,c=a+4,u=r.length-i;if(u<=c)throw new Error("envelope: malformed Jupiter route payload");let d=zo(r,a,"route plan length"),l=r.subarray(c,u),f=Vo(l,d,t);return Object.freeze({instruction:o.name,routeId:s,routePlanSteps:d,routePlan:f,routePlanHash:Ge(l),inAmount:mt(r,u,"in_amount"),quotedOutAmount:mt(r,u+8,"quoted_out_amount"),slippageBps:Go(r,u+16,"slippage_bps"),platformFeeBps:r[u+18],instructionHash:Ge(r)})}function Yo(e,t,r){let n=Wo(e,t),o=(i,s)=>{let a=n[i];if(!a)throw new Error(`envelope: Jupiter ${s} account missing`);return a};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 ht(e,t){return e&&e!==t?e:null}function W(e,t,r){let n=J(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function Xo(e,t){let r=_e(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 Zo(e,t,r,n,o,i){let s=_e(t);if(s.length!==1||s[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let a=Be(t);if(a.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=W(e,a[0],"ATA payer"),u=W(e,a[1],"ATA account"),d=W(e,a[2],"ATA owner"),l=W(e,a[3],"ATA mint"),f=W(e,a[4],"ATA system program"),m=W(e,a[5],"ATA token program");if(c!==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(f!==xr)throw new Error("envelope: Jupiter ATA system program mismatch");if(m!==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(u!==br(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:u,debit:i}}function Qo(e,t,r,n,o){let i=Be(t),s=_e(t);if(i.length!==2||s.length!==12||s.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let a=W(e,i[0],"wrap payer"),c=W(e,i[1],"wrap target"),u=s.readBigUInt64LE(4);if(a!==r.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(u!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return u}function ei(e,t,r,n){let o=Be(t),i=_e(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||W(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=W(e,o[0],"closeAccount source"),a=W(e,o[1],"closeAccount destination"),c=W(e,o[2],"closeAccount authority");if(s!==n||a!==r.owner||c!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function ri(e,t,r,n,o,i,s){let a=br(t.owner,t.artifact.inputMint,s);if(o.userSourceTokenAccount!==a)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=j(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<Po)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let u=new Map,d=0n,l=!1,f=!1;for(let m of e.instructions){if(m===n)continue;let p=Ho(e,m);if(p===_o)Xo(m,r);else if(p===yt){let{ata:g,debit:w}=Zo(e,m,t,t.artifact,s,c);u.set(g,w)}else if(p===xr)d+=Qo(e,m,t,a,i);else if(p===s){let g=ei(e,m,t,a);g.kind==="syncNative"&&(l=!0),g.kind==="closeAccount"&&(f=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(d>0n&&(!l||!f))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(d!==0n&&d!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...u.values()].reduce((m,p)=>m+p,0n)}function ti(e){let t;try{t=No().decode(Ro(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 ni(e,t,r){if(e.header.numSignerAccounts!==1||J(e.staticAccounts[0])!==t.owner||!ee(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 n=[];for(let o of e.instructions){let i=J(e.staticAccounts[o.programAddressIndex]);if(!i||!ee(i,r.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function oi(e,t,r){let n=j(r.lamportsPerSignature,"lamportsPerSignature");if(n<Co)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:j(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,a=i*o;if(t.exactFeeLamports!==void 0){let u=j(t.exactFeeLamports,"exactFeeLamports");if(u<s)throw new Error("policy: Solana exact fee below the base signature fee");if(u>a)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=a;if(c>j(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function ii(e,t,r,n){let o=0n,i=!1;for(let s of e.instructions){if(J(e.staticAccounts[s.programAddressIndex])!==xr)throw new Error("envelope: unsupported Solana program decoder");let c=s.accountIndices||[];if(c.length!==2||J(e.staticAccounts[c[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let u=J(e.staticAccounts[c[1]]);if(u!==t.destination||!ee(u,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>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function si(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!==Bo)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!ee(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Fo(r);if(!ee(o.inputMint,i)||!ee(o.outputMint,i))throw new Error("policy: Solana token not allowed");let s=j(o.inAmount,"inAmount"),a=j(o.outAmount,"outAmount"),c=j(o.otherAmountThreshold,"otherAmountThreshold");if(s<=0n||s>j(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(s>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(a<=0n||c<=0n||c>a)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let u=J(o.jupiterProgram);if(!u||!ee(u,r.programs)||!n.includes(u))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(v=>J(e.staticAccounts[v.programAddressIndex])===u);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=d[0],f=Ko(l.data,r);if(f.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(f.routeId)))throw new Error("policy: Jupiter shared route id not allowed")}else if(f.routeId!=null)throw new Error("envelope: unexpected Jupiter shared route id");if(!yr(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(f.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(f.inAmount!==s)throw new Error("envelope: Jupiter route in_amount mismatch");if(f.quotedOutAmount!==a)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(f.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let m=f.quotedOutAmount-f.quotedOutAmount*BigInt(f.slippageBps)/10000n;if(c!==m)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(f.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let p=Yo(e,l,f),g=Be(l),w=f.instruction==="shared_accounts_route"?2:1;if(!Et(e,g[w]))throw new Error("envelope: Jupiter transfer authority must be signer");if(p.program!==u)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:[gt];if(!ee(p.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let x=br(t.owner,o.outputMint,p.tokenProgram);if(p.userDestinationTokenAccount!==x)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=ht(p.destinationTokenAccount,u);if(E&&E!==x)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(ht(p.platformFeeAccount,u))throw new Error("policy: Jupiter platform fee account not allowed");if(!yr(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(pt(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let b=Ge(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,pt(e,l)].join(`
3
+ `)));if(!yr(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(b))throw new Error("policy: Jupiter route review hash not allowed");let T=ri(e,t,r,l,p,s,p.tokenProgram),O=s+T;if(O>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:O,programs:n}}function Sr(e,t){if(e.action!=="transfer"&&e.action!=="swap")throw new Error("envelope: Solana decoder requires transfer or swap action");let r=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(r||{}).some(c=>!n.includes(c)))throw new Error("envelope: unexpected Solana artifact field");if(!ee(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=ti(r),i=ni(o,e,t),s=e.action==="transfer"?ii(o,e,t,i):si(o,e,t,i),a=oi(o,r,t);return Object.freeze({unit:"lamports",value:s.value.toString(),notional:(s.value+a).toString(),fee:a.toString(),programs:Object.freeze(s.programs)})}function Ar(e,t){let{unit:r,value:n,notional:o,fee:i}=Sr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}var ai=1e8;function vr(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=ai+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var ci=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),ui=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),li=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"}),di=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"}),oe=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function fi(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 xt(e,t){let r=k(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 X(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=>X(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)}:${X(e[n],t)}`).join(",")}}`}function pi(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)||X(r,"declared order type")!==X({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(X(r,"declared order type")!==X({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||X(r,"declared order type")!==X({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 mi(e,t,r){let n=xt(e.s,"signed size"),o=xt(e.p,"signed price"),i=n.decimals+o.decimals,s=n.raw*o.raw,a=_(t.notionalUsd,i,"hl: notionalUsd");if(a<=0n||s!==a)throw new Error("hl: signed notional must match");let c=_(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>c)throw new Error("hl: notional exceeds cap")}function hi(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=oe(r.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(R(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(a=>String(a).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=Q(r.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let s=_(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function bt(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(k(e.s,"hl: signed size")!==k(t.size,"hl: size"))throw new Error("hl: signed size must match");if(k(e.p,"hl: signed price")!==k(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(X(e.t,"signed order type")!==X(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 St(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(k(e.s,"hl: bracket protection size")!==k(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(k(e.p,"hl: bracket protection price")!==k(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(k(i.triggerPx,"hl: triggerPx")!==k(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function wi(e){let t=String(e||"").replace(/\/$/,"");if(!ci.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function Ir(e){return vr(e)!=null}function gi(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(Ir(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 yi(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(s=>{if(typeof s=="string"){let[a,c]=String(s).split(":");return a===e&&Number(c)===t}return String(s?.coin)===e&&Number(s?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(Ir(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 ie(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=oe(r.kind,"kind",48),o=li[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=wi(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!==di[n])throw new Error("hl: action type must match kind");let a=r.notionalUsd??0;if(ui.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let c=oe(r.coin,"coin",64),u=r.assetId??r.assetIndex;if(!Number.isSafeInteger(u)||u<0)throw new Error("hl: assetId required");if(n==="hip4-order"||u>=1e8){let d=vr(c);if(!d||d.coin!==c)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==u)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(gi(c,t),yi(c,u,t),n==="hip4-order"&&!Ir(c))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");pi(r);let d=r.action.orders;if(n==="perp-bracket"){let l=r.takeProfitPx,f=r.stopLossPx,m=1+(l==null?0:1)+(f==null?0:1);if(m<2||d.length!==m||r.grouping!=="normalTpsl"||r.action.grouping!==r.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");bt(d[0],r,u);let p=1;l!=null&&St(d[p++],r,u,l,"tp"),f!=null&&St(d[p],r,u,f,"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");bt(d[0],r,u)}mi(d[0],r,t),hi(r,t),a=k(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!==u)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!==u)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!==u)throw new Error("hl: signed margin asset must match assetId");let d=oe(r.usd,"margin usd",64),l=_(d,6,"hl: margin usd");if(Q(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 m=_(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),p=l<0n?-l:l;if(p>m)throw new Error("hl: margin notional exceeds cap");a=fi(p,6)}}if(n==="builder-fee-approval"){let c=oe(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(oe(r.action.builder,"signed builder",42).toLowerCase()!==c)throw new Error("hl: signed builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(p=>String(p).toLowerCase()):[]).includes(c))throw new Error("hl: builder not allowed");let d=oe(r.maxFeeRate,"maxFeeRate",32);if(oe(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=_(d.slice(0,-1),12,"hl: builder fee percent"),f=_(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(f<0n||l*100n>f)throw new Error("hl: builder fee exceeds cap");if(Number(r.action.nonce)!==s)throw new Error("hl: signed builder nonce must match");let m=i.includes("testnet")?"Testnet":"Mainnet";if(r.hyperliquidChain!==m||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 c=n==="hype-undelegate";if(typeof r.action.isUndelegate!="boolean"||r.action.isUndelegate!==c)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(a??r.action.wei??0),notional:String(a??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??a??0),coin:r.coin||null,submitTo:i})}import{createHmac as Ei}from"node:crypto";var we="0x"+"00".repeat(32);function Tr(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 At({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)),a=String(r||"").toUpperCase(),c=String(n||"");if(a!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let u=s+a+c+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),f=Ei("sha256",l).update(u).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:f,POLY_TIMESTAMP:s,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function xi(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 vt(e,t){let r=BigInt(k(e.makerAmount,"poly: makerAmount")),n=BigInt(k(e.takerAmount,"poly: takerAmount"));if(r<=0n||n<=0n)throw new Error("poly: order amounts must be positive integer micro-units");return Number(t==="BUY"?r:n)/1e6}function bi(e){let t=typeof e=="bigint"?e.toString(10):k(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 It({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=xi(e,t);if(R(e.metadata||we,"poly: metadata").toLowerCase()!==we)throw new Error("poly: metadata must be zero");if(R(e.builder||we,"poly: builder").toLowerCase()!==we)throw new Error("poly: builder must be zero");let s=bi(e.salt);return{deferExec:!1,order:{builder:we,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:we,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 Si=new Set(["https://clob.polymarket.com/order"]),Ce=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Dc=Object.freeze(Ce.map(e=>e[0])),Ai=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),vi="0xe111180000d2663c0091e4f400237545b87b996b",Ii="0xe2222d279d744050d28e00520010520000310f59",Tt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function kt(e){let t=String(e||"").replace(/\/$/,"");if(!Si.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function Ot(e){let t=R(e,"poly: exchange").toLowerCase();if(!Ai.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function se(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=Tt(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(R(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(kt(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(Ot(o.verifyingContract),Ot(r.exchange),R(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==R(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?Ii:vi;if(R(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 a=r.types?.Order;if(!Array.isArray(a)||a.length!==Ce.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let w=0;w<Ce.length;w+=1)if(a[w]?.name!==Ce[w][0]||a[w]?.type!==Ce[w][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 c=String(e.owner||"").toLowerCase();if(R(s.maker,"poly: maker").toLowerCase()!==c)throw new Error("poly: maker must equal owner");if(R(s.signer,"poly: signer").toLowerCase()!==c)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 u=Tt(r.tokenId,"tokenId",80);if(R(s.tokenId,"poly: tokenId")!==u)throw new Error("poly: tokenId mismatch");let d=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(d.length&&!d.includes(u)&&!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 f=vt(s,l),m=_(r.notionalUsdc,6,"poly: notionalUsdc"),p=_(f,6,"poly: computed notional");if(m!==p)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let g=t.maxNotionalUsd??t.maxNotionalUsdc;if(g!=null){let w=_(g,6,"poly: maxNotionalUsd");if(p>w)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:String(f),notional:String(f),fee:"0",kind:n,tokenId:u,side:l,submitTo:kt(r.submitTo)})}var Ti=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),kr=14,Lt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function ge(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function Or(e){let t=String(e||"").replace(/\/$/,"");if(!Ti.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function ae(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=Lt(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=Or(r.submitTo),i=r.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let s=Number(Q(r.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(s)||s<0)throw new Error("lighter: accountIndex required");let a=Number(Q(r.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: clientOrderIndex required");ge(r.orderType,0,"orderType"),ge(r.timeInForce,1,"timeInForce"),ge(r.reduceOnly,0,"reduceOnly"),ge(r.triggerPrice,0,"triggerPrice"),ge(r.orderExpiry,-1,"orderExpiry");let c=Lt(r.symbol||r.coin,"symbol",32),u=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(u.length&&!u.includes(c)&&!u.includes(String(i))&&!u.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=fr(r.baseAmount,"lighter: baseAmount"),l=fr(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 f=Number(d),m=Number(l),p=Number(r.sizeDecimals??0),g=Number(r.priceDecimals??0);if(!Number.isInteger(p)||p<0||p>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(g)||g<0||g>12)throw new Error("lighter: priceDecimals required");let w=p+g,h=d*l,x=_(r.notionalUsd,w,"lighter: notionalUsd");if(x<=0n)throw new Error("lighter: notionalUsd required");if(h!==x)throw new Error("lighter: notionalUsd must match size and price");let E=_(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,w,"lighter: maxNotionalUsd");if(h>E)throw new Error("lighter: notional exceeds cap");let b=k(r.notionalUsd,"lighter: notionalUsd");return ge(r.txType,kr,"txType"),Object.freeze({unit:"usd",value:String(b),notional:String(b),fee:"0",kind:n,symbol:c,marketIndex:i,side:r.side,baseAmount:f,price:m,submitTo:o,actionType:"create-order",amount:String(b)})}var Bt=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var Nr=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0,delegate:0}),ki=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Ct=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"}}),Oi=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"}}),Li=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 ze=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},S=(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`)}},Nt=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ni=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},C=(e,t,r)=>{if(!Ni(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Lr=(e,t,r)=>{Array.isArray(t)&&t.length&&C(e,t,r)},re=(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},le=e=>String(e||"0x").slice(0,10).toLowerCase(),Pt=e=>S(e.gasLimit,"gasLimit")*S(e.maxFeePerGas??e.gasPrice,"feePerGas")+S(e.l1FeeWei??0,"l1FeeWei")+S(e.operatorFeeWei??0,"operatorFeeWei");function ye(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 P(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function G(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function _i(e){if(le(e)!=="0x095ea7b3")return null;let t=ye(e,2,"approval");return{kind:"approval",spender:P(t.word(0),"approval spender"),amount:G(t.word(1),"approval amount")}}function $t(e,t){let r=t==="router02-exact-input-single"?7:8,n=ye(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:P(n.word(0),"input token"),outputToken:P(n.word(1),"output token"),recipient:P(n.word(3),"recipient"),amountIn:G(n.word(o),"amountIn"),minimumOut:G(n.word(o+1),"amountOutMinimum")}}function Bi(e){let t=ye(e,12,"Across depositV3",{dynamicTail:!0}),r=G(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:P(t.word(0),"depositor"),recipient:P(t.word(1),"recipient"),inputToken:P(t.word(2),"input token"),outputToken:P(t.word(3),"output token"),amountIn:G(t.word(4),"inputAmount"),minimumOut:G(t.word(5),"outputAmount"),destinationChainId:G(t.word(6),"destinationChainId")}}function Ci(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 _t(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 w=10;w+64<=r.length;w+=64)n.push(r.slice(w,w+64));let o=(w,h)=>{if(!n[w])throw new Error(`envelope: malformed ${h}`);return BigInt(`0x${n[w]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let s=i/32,a=Number(o(s,"path offset")),c=n[s+1],u=o(s+(t?3:2),"amountIn"),d=o(s+(t?4:3),"amountOutMinimum"),l=s+a/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let f=Number(o(l,"path length")),m=r.slice(10+(l+1)*64,10+(l+1)*64+f*2),{inputToken:p,outputToken:g}=Ci(`0x${m}`);return{kind:"action",action:"swap",inputToken:p,outputToken:g,recipient:P(c,"recipient"),amountIn:u,minimumOut:d}}function Pi(e){let t=ye(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:P(t.word(0),"input token"),outputToken:P(t.word(1),"output token"),recipient:P(t.word(3),"recipient"),amountIn:G(t.word(5),"amountIn"),minimumOut:G(t.word(6),"amountOutMinimum")}}function $i(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let f=10;f+64<=t.length;f+=64)r.push(t.slice(f,f+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]}`)),a=o+1+s/32,c=Number(BigInt(`0x${r[a]}`)),d=`0x${t.slice(10+(a+1)*64,10+(a+1)*64+c*2)}`,l=le(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return $t(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function Mi(e,t){let r=le(e),n=Ct[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{...$t(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{..._t(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{..._t(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...$i(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Pi(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...Bi(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Ri(e){let t=ye(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",contract:P(t.word(0),"mint NFT contract"),feeRecipient:P(t.word(1),"mint fee recipient"),recipient:P(t.word(2),"mint recipient"),quantity:G(t.word(3),"mint quantity")}}function Fi(e,t){let r=le(e);if(String(t).toLowerCase()==="nft-mint")return qi(e);let n=Oi[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{...Ri(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function qi(e){let t=le(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=Li[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=ye(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:G(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function Ve(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 Mt(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let s=re(e.owner,"owner"),a=e.artifact,c=Number(a?.chainId??Ve(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(C(c,t.chains,"chain"),a?.owner!==void 0&&re(a.owner,"batch owner")!==s)throw new Error("envelope: explicit batch owner mismatch");let u=Ve(e);if(!u.length||u.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,l=0n,f=0n;for(let m of u){if(!m||typeof m!="object"||Array.isArray(m))throw new Error("envelope: structured EVM transaction required");if(Number(m.chainId)!==c)throw new Error("envelope: every batch leg must use the same chain");if(re(m.from,"transaction owner")!==s)throw new Error("envelope: every batch leg must use the same owner");if(C(le(m.data),t.selectors,"selector"),d+=S(m.value??0,"value"),l+=S(m.gasLimit,"gasLimit"),f+=Pt(m),K(c)&&(m.l1FeeWei===void 0||m.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>S(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>S(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(f>S(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:u,chainId:c,owner:s,totalValue:d,totalGas:l,totalFee:f}}function Rt(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=ze(e.provider,"provider",64).toLowerCase();C(i,t.providers,"provider");let s=Mt(e,t,o,{nowMs:r}),a=[],c=-1;for(let p=0;p<s.transactions.length;p++){let g=s.transactions[p],w=_i(g.data),h;if(w){if(c!==-1)throw new Error("envelope: approval must be before action");if(S(g.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let b=re(g.to,"approval token");if(C(b,t.tokens,"token"),C(w.spender,t.spenders,"spender"),w.amount>S(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...w,token:b,index:p}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");C(g.to,t.destinations,"destination"),h={...Mi(g.data,i),target:re(g.to,"action target"),index:p},c=p}let x=S(g.value??0,"value"),E=S(g.gasLimit,"gasLimit");a.push({...h,value:x,gas:E,fee:Pt(g)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let u=a[c],d=o==="evm-swap"?"swap":"bridge";if(u.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if(re(e.destination,"destination")!==u.target)throw new Error("envelope: destination must equal decoded action target");if(u.recipient!==s.owner)throw new Error("envelope: decoded recipient must equal owner");if(u.depositor&&u.depositor!==s.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(C(u.inputToken,t.tokens,"input token"),C(u.outputToken,t.tokens,"output token"),u.amountIn<=0n||u.amountIn>S(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(u.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(dr(e.autoSlippage,{nowMs:r,chainId:s.chainId,venue:i,tx:s.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(u.minimumOut!==S(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(u.action==="bridge"&&S(e.toChainId,"toChainId")!==u.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=a.filter(p=>p.kind==="approval");if(!new Set([...ki,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(p=>String(p).toLowerCase()):[]]).has(u.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(u.value!==u.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let m=Object.freeze({quoteAmountOut:S(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:S(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...s,decoded:a,action:u,provider:i,authenticatedQuote:m}}function Ft(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 action");let n=ze(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Lr(n,t.providers,"provider");let o=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;o?.oraclePrepared===!0&&it(o,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"});let i=Mt(e,t,"evm-nft",{nowMs:r});if(i.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let s=i.transactions[0],a=le(s.data);C(a,t.selectors,"selector"),C(s.to,t.destinations,"destination");let c=Fi(s.data,n),u=re(e.contract??e.artifact?.contract,"NFT contract");if(Lr(u,t.nftContracts,"NFT contract"),(c.contract||re(s.to,"NFT contract"))!==u)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==i.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&Lr(c.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let l=S(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>S(t.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(c.quantity!==l)throw new Error("envelope: mint calldata quantity mismatch");let f=S(e.totalWei??e.artifact?.totalWei,"totalWei");if(i.totalValue!==f)throw new Error("envelope: mint value does not match declared totalWei");if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&S(e.priceWei??e.artifact.priceWei,"priceWei")*l!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>S(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...i,provider:n,decoded:[{...c,target:re(s.to,"mint target"),value:i.totalValue,gas:i.totalGas,fee:i.totalFee}]}}function Di(e,{localsWaiver:t=!1}={}){if(!(e in Nr))throw new Error("fee: unknown action");return t?0:Nr[e]}function Ke(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 a=ze(e.surface,"surface",16);if(!Bt.has(a))throw new Error("envelope: unsupported public surface");let c=ze(e.action,"action",32);C(a,t.surfaces,"surface"),C(c,t.actions,"action"),C(e.owner,t.owners,"owner"),C(e.destination,t.destinations,"destination");let u=Nt(t.maxTtlMs,"maxTtlMs"),d=Nt(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>u)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(a==="evm-swap"||a==="evm-bridge")Rt(e,t,{nowMs:r,routeAttestationSecret:o});else if(a==="evm-nft")Ft(e,t,{nowMs:r});else if(a==="evm"){if(!["transfer","approve"].includes(c))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");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");He({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:s});let p=String(l.data||"0x").toLowerCase(),g=S(l.value,"EVM value");if(p==="0x"){if(g===0n)throw new Error("envelope: native EVM transfer value required")}else if(V(p)){if(g!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else a==="btc"?gr(e,t):a==="sol"?Ar(e,t):a==="hl"?ie(e,t):a==="poly"?se(e,t):a==="lighter"&&ae(e,t);let f=Number(e.fee?.oracleFeeBps)===0&&Nr[c]!==0;if(e.fee?.waiver||f&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(f&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let m=Di(c,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==m)throw new Error("fee: final artifact fee mismatch");return!0}var _r=Object.freeze([...Bt]),Qc=Object.freeze({...Ct});function Br(e,t){if(e.surface==="hl")return ie(e,t);if(e.surface==="poly")return se(e,t);if(e.surface==="lighter")return ae(e,t);if(e.surface==="btc")return gr(e,t);if(e.surface==="sol")return Ar(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Rt(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=Ft(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(String(e.surface).startsWith("evm")){let r=S(e.artifact?.value,"EVM value"),n=S(e.artifact?.gasLimit,"EVM gasLimit"),o=S(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+S(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+S(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 qt(e={}){let t={};for(let r of _r){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 Ye(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 Gt}from"node:crypto";import{ed25519 as Xi}from"@noble/curves/ed25519.js";import{base58 as Yt}from"@scure/base";import{RawTx as Mr,SigHash as de,Transaction as Rr}from"@scure/btc-signer";import{Transaction as Fr,keccak256 as zt,verifyTypedData as Vt}from"ethers";import{encode as Ui}from"@msgpack/msgpack";import{keccak256 as ji,verifyTypedData as Wi}from"ethers";var Ee=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Cr=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Dt(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 Hi(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Ui(e)),Dt(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]),Dt(n)),ji(Buffer.concat(i))}function Pr(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:Hi(e,t,{vaultAddress:n,expiresAfter:o})}}function Ut(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=Pr(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==Ee.name||String(t.domain?.version)!==Ee.version||Number(t.domain?.chainId)!==Ee.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(Ee.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(Cr.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 jt({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=Pr(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(Ee,Cr,s)}function Wt({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:s=null}){try{let a=Pr(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:s}),c=Wi(Ee,Cr,a,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var Ji=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function $r(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)$r(t);return}for(let t of Object.values(e))$r(t)}}}function Gi(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 $r(e),JSON.parse(JSON.stringify(e))}function Xe(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 zi(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 Ht(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 be(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=>Ht(e[s],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function Vi(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 xe(e,t,r,n){let o=be(e,t,n);if(BigInt(o)!==Xe(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Ki(e,t,r,n){let o=be(e,t,n,{signed:!0});if(BigInt(o)!==zi(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Yi(e){let t={};for(let[r,n]of Ji.entries()){let o=n.filter(s=>e[s]!==void 0&&e[s]!==null);if(!o.length)continue;let i=o.map(s=>{let a=e[s];if(r<3)return Ht(a,n[0]);if(typeof a!="string"||a.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return a});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);t[n[0]]=i[0]}return t}function Pe(e,t){let r=Gi(t),n=xe(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=xe(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=xe(r,["Type","type"],e.orderType,"Type"),s=xe(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),a=xe(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),c=xe(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),u=Ki(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=be(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=be(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),f=be(r,["Price","price"],"Price");if(BigInt(d)!==Xe(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==Xe(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==Xe(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let m=Vi(r,["IsAsk","is_ask","isAsk"],"IsAsk");if(typeof m!="number"||m!==0&&m!==1)throw new Error("lighter: signed IsAsk must be exact numeric 0 or 1");let p=m===1,g=e.side==="sell";if(p!==g)throw new Error("lighter: signed IsAsk must match the prepared side");let w=be(r,["txType","tx_type","TxType"],"txType");if(w!==kr)throw new Error("lighter: signed txType must be official create-order");let h={...Yi(r),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:s,ReduceOnly:a,TriggerPrice:c,OrderExpiry:u,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(f),IsAsk:p?1:0,txType:w},x=JSON.stringify(h),E=JSON.parse(x);if(E.MarketIndex!==Number(d)||E.BaseAmount!==Number(l)||E.Price!==Number(f)||E.IsAsk!==(p?1:0)||E.txType!==w)throw new Error("lighter: canonical tx_info mutated");return{txType:w,txInfo:x,submitTo:Or(e.submitTo)}}function Jt(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var Se=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},Ze=e=>String(e||"").toLowerCase();function Zi(e,t){if(typeof e!="string")return!1;let r,n;try{r=Fr.from(e),n=Fr.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})}catch{return!1}return Ze(r.from)!==Ze(t.from)||Ze(r.to)!==Ze(t.to)?!1:r.unsignedHash===n.unsignedHash}function Qi(e){let t=Buffer.from(Mr.encode(e)),r=Gt("sha256").update(t).digest();return Buffer.from(Gt("sha256").update(r).digest()).reverse().toString("hex")}function Kt(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Qi(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 es(e,t){let r=Se(e),n=Se(t.psbt);if(!r||!n)return!1;try{let o=Rr.fromPSBT(n),i=Rr.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 a=i.getInput(s),c=o.getInput(s);if(!Kt(c)||!Kt(a))return!1;let u=(h,x)=>{if(h==null&&x==null)return!0;if(h==null||x==null)return!1;try{return Buffer.from(h).equals(Buffer.from(x))}catch{return!1}},d=(h,x)=>{if(h==null&&x==null)return!0;if(h==null||x==null)return!1;try{return Buffer.from(Mr.encode(h)).equals(Buffer.from(Mr.encode(x)))}catch{return u(h,x)}};if(!!a.witnessUtxo!=!!c.witnessUtxo||a.witnessUtxo&&(BigInt(a.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!u(a.witnessUtxo.script,c.witnessUtxo.script))||!d(a.nonWitnessUtxo,c.nonWitnessUtxo)||!u(a.redeemScript,c.redeemScript)||!u(a.witnessScript,c.witnessScript)||a.sighashType!==void 0&&a.sighashType!==de.DEFAULT&&a.sighashType!==de.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===de.ALL,f=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===de.ALL:!1;for(let h of a.partialSig||[]){let x=Array.isArray(h)?h[1]:h;if(!l(x))return!1}if(a.tapKeySig&&!f(a.tapKeySig))return!1;for(let h of a.tapScriptSig||[]){let x=Array.isArray(h)?h[1]:h;if(!f(x))return!1}let m=h=>h[h.length-1]===de.ALL,p=h=>h.length>=9&&h.length<=73&&h[1]===h.length-3&&h[2]===2,g=h=>{let x=!1;for(let E of h)if(E instanceof Uint8Array){if(E[0]===48){if(!p(E)||!m(E))return!1;x=!0;continue}if(E.length===64){x=!0;continue}if(E.length===65){if(E[64]!==de.ALL&&E[64]!==de.DEFAULT)return!1;x=!0}}return x};if(a.finalScriptWitness){let h;if(Array.isArray(a.finalScriptWitness))h=a.finalScriptWitness;else if(a.finalScriptWitness instanceof Uint8Array){let x=a.finalScriptWitness,E=O=>{let v=x[O];return v===void 0?null:v<253?{value:v,next:O+1}:v===253?{value:x[O+1]|x[O+2]<<8,next:O+3}:null},b=E(0);if(!b)return!1;h=[];let T=b.next;for(let O=0;O<b.value;O++){let v=E(T);if(!v||T+v.value>x.length)return!1;h.push(x.slice(v.next,v.next+v.value)),T=v.next+v.value}if(T!==x.length)return!1}else return!1;if(!h.length||!g(h))return!1}if(a.finalScriptSig instanceof Uint8Array&&a.finalScriptSig.length){let h=a.finalScriptSig,x=[],E=0;for(;E<h.length;){let b=h[E];if(b>=1&&b<=75){if(E+1+b>h.length)return!1;x.push(h.slice(E+1,E+1+b)),E+=1+b;continue}if(b===76){let T=h[E+1];if(T===void 0||E+2+T>h.length)return!1;x.push(h.slice(E+2,E+2+T)),E+=2+T;continue}return!1}if(!x.length||!g(x))return!1}if(![a.partialSig,a.tapKeySig,a.tapScriptSig,a.finalScriptSig,a.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function Xt(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 rs(e,t,r){let n=Se(e),o=Se(t.messageBase64);if(!n||!o)return!1;let i=Xt(n);if(!i||i.value!==1||i.offset!==1)return!1;let s=i.offset+64;if(s>=n.length)return!1;let a=n.subarray(i.offset,s),c=n.subarray(s);if(!c.equals(o))return!1;try{let u=Yt.decode(String(r));return u.length===32&&Xi.verify(a,c,u)}catch{return!1}}function Zt(e,t,r,n){if(String(e).startsWith("evm"))return Zi(t,r);if(e==="btc")return es(t,r);if(e==="sol")return rs(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String(Vt(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return Wt({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(Vt(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Pe(r,t),!0}catch{return!1}return!1}function Qt(e,t){try{if(String(e).startsWith("evm"))return Fr.from(t).hash;if(e==="btc"){let r=Se(t);if(!r)return null;let n=Rr.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=Se(t);if(!r)return null;let n=Xt(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Yt.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return zt(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return zt(t)}catch{}return null}var is=e=>String(e||"").toLowerCase();function te(e){return ts("sha256").update(JSON.stringify(e)).digest("hex")}function Dr(e,t,r={}){return He(e,t,r)}async function ss(e,t={}){if(!K(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 rn(e,t,r=!1){if(!K(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}var Qe=class{#e=new Map;constructor({now:t=Date.now}={}){this.now=t}issue({artifact:t,owner:r,ttlMs:n=6e4}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=ns(32).toString("hex");return this.#e.set(o,{digest:te(t),owner:is(r),expiresAtMs:this.now()+n}),o}consume(t,r){let n=this.#e.get(String(t));if(!n)throw new Error("confirmation: used or unknown nonce");if(n.expiresAtMs<=this.now())throw this.#e.delete(String(t)),new Error("confirmation: expired nonce");let o=Buffer.from(n.digest,"hex"),i=Buffer.from(te(r),"hex");if(!os(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(t)),n}clear(){this.#e.clear()}};function as(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(V(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 cs(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 er(e,t){let r=String(t||"");if(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=en.decode(r);return n.length===64&&en.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 tn(e,t,r){return!er(e,t)||!er(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function us(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 qr({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:s,nowMs:a}){let c=us(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="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,a())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="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);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=a())throw new Error("confirmation: expired nonce");return i}function ls(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function ds(e,t){return e&&ls(e.surface)?Ve(e):[t]}function fs(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!tn(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function ps(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:cs(r,n)}}async function nn(e,t,r){if(!r.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:w,...h}=e||{};return h})(),i=ds(n,o),s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,a=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:null,consumeNonce:!0,nowMs:a}),u=te(e),d=(w={})=>{n?Ke(n,s,w):(Dr(o,s,{nowMs:w.nowMs,networkFees:w.networkFees,requireNetworkFees:w.requireNetworkFees}),as(o))},l=async w=>{let h=n&&!String(n.surface||"").startsWith("evm")?void 0:await ss(w,r);return{nowMs:a(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:h,requireNetworkFees:K(w?.chainId)}};d({nowMs:a(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let w of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[w]!="function")throw new Error(`signer: ${w} is required`);let f=r.reserveLedger(n||e,s);if(!f)throw new Error("signer: ledger reservation required");let m=!1,p=[];try{for(let w of i){if(typeof r.simulate!="function"||await r.simulate(w,n)!==!0)throw new Error("signer: strict affirmative simulation required");let h=await l(w);if(rn(w,h.networkFees,h.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:c,consumeNonce:!1,nowMs:a}),d(h),r.validateReservation(f,s,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,s):void 0),m=!0;let x=await r.sign(w,n);if(typeof r.verifySigned!="function"||await r.verifySigned(x,w,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!r.isArmed())throw new Error("signer: disarmed before broadcast");if(te(e)!==u)throw new Error("signer: artifact mutated after signing");s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:c,consumeNonce:!1,nowMs:a});let E=await l(w);rn(w,E.networkFees,E.requireNetworkFees),d(E),r.validateReservation(f,s,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,s):void 0);let b=await r.broadcast(x,w,n),T=b?.status,O=n?.surface||"evm",v=fs(b,O),Te=Qt(O,x);if(!tn(O,v,Te))throw new Error("signer: receipt transaction hash does not match signed bytes");if(T===0||T==="0x0")throw er(O,v)?(r.settleFailedLedger(f),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(T!==1&&T!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!er(O,v))throw new Error("signer: successful broadcast requires a valid transaction hash");p.push(ps(b,v))}}catch(w){throw m||r.releaseLedger(f),w}if(r.commitLedger(f),p.length===1){let w={receipt:p[0]};return n?.surface==="evm-bridge"&&(w.originStatus="success",w.destinationStatus="unverified",w.destinationSuccess=!1,w.note="Origin-chain receipts do not prove destination-chain settlement."),w}let g={receipts:p,status:"success"};return n?.surface==="evm-bridge"&&(g.originStatus="success",g.destinationStatus="unverified",g.destinationSuccess=!1,g.note="Origin-chain receipts do not prove destination-chain settlement."),g}var on=new Set(["127.0.0.1","::1","localhost"]),ws=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&hs(r,n)},$=(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 gs(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 sn=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)});function an(e={}){let t=e.host||"127.0.0.1";if(!on.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 i of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[i]!="function")throw new Error(`signer: ${i} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Qe,n=e.origin||`http://${t}`;return ms.createServer(async(i,s)=>{try{let a=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!ws(a,e.token))return $(s,401,{error:"unauthorized"});let c=gs(i.headers.host);if(!on.has(c))return $(s,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return $(s,403,{error:"origin refused"});if(i.method==="GET"&&i.url==="/status"){let u=typeof e.readPolicy=="function"?e.readPolicy():e.policy,d=new Set(_r),l=Array.isArray(u?.surfaces)?u.surfaces.filter(f=>typeof f=="string"&&d.has(f)):[];return $(s,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:l,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(i.method==="POST"&&i.url==="/disarm")return e.disarm(),r.clear(),$(s,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return $(s,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return $(s,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return $(s,403,{error:"autonomous signer does not issue human confirmation nonces"});let u=await sn(i),d=te(u.artifact),l=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(l?.confirmationMode!=="exact-human")return $(s,403,{error:"exact-human policy required"});let f=typeof e.nowMs=="function"?e.nowMs():Date.now();if(u.artifact?.version===1&&u.artifact?.surface)Ke(u.artifact,l,{nowMs:f,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:m,...p}=u.artifact||{};Dr(p,l,{nowMs:f})}return typeof e.confirmArtifact!="function"?$(s,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(u.artifact,d,l)!==!0?$(s,400,{error:"exact human confirmation refused"}):$(s,200,{confirmationNonce:r.issue({artifact:u.artifact,owner:u.artifact?.owner??u.artifact?.from,ttlMs:u.ttlMs})})}if(i.method==="POST"&&i.url==="/execute"){let u=await sn(i),d=await nn(u.artifact,u.confirmationNonce,{...e,confirmations:r});return $(s,200,d)}return $(s,404,{error:"not found"})}catch(a){return e.onError?.(String(a?.message||a)),$(s,400,{error:"request refused"})}})}import{createCipheriv as ku,createDecipheriv as ys,randomBytes as Es,scryptSync as xs}from"node:crypto";import I from"node:fs";import Ae from"node:path";var bs="ORACLE-LOCAL-VAULT",Ss=1,tr=Object.freeze({N:1<<17,r:8,p:1}),As=256*1024*1024,vs=16*1024;function rr(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 Is(e,t,r=tr){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return xs(n,t,32,{...r,maxmem:As})}function cn(e,t){if(e?.magic!==bs||e?.version!==Ss)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!==tr.N||e.kdf.r!==tr.r||e.kdf.p!==tr.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=rr(e.kdf.salt,32,"salt"),o=rr(e.cipher.iv,12,"iv"),i=rr(e.tag,16,"tag"),s=rr(e.ciphertext,1,"ciphertext",{max:vs}),{ciphertext:a,tag:c,...u}=e,d=Is(t,n);try{let l=ys("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(u))),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 Ts(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 ks(e){let t=Ae.dirname(e),r=I.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=I.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=I.openSync(e,I.constants.O_RDONLY|I.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=I.fstatSync(t);if(Ts(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=I.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 I.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{I.closeSync(t)}}function un(e){return JSON.parse(L(e))}function ce(e,t){I.mkdirSync(Ae.dirname(e),{recursive:!0,mode:448}),ks(e);let r=Ae.join(Ae.dirname(e),`.${Ae.basename(e)}.${process.pid}.${Es(6).toString("hex")}.tmp`);try{let n=I.openSync(r,I.constants.O_CREAT|I.constants.O_EXCL|I.constants.O_WRONLY|I.constants.O_NOFOLLOW,384);try{I.writeFileSync(n,String(t)),I.fsyncSync(n)}finally{I.closeSync(n)}I.renameSync(r,e),I.chmodSync(e,384);let o=I.openSync(Ae.dirname(e),"r");try{I.fsyncSync(o)}finally{I.closeSync(o)}}catch(n){try{I.unlinkSync(r)}catch{}throw n}}import{createHmac as Ls,randomBytes as Ns,timingSafeEqual as _s}from"node:crypto";import M from"node:fs";import fe from"node:path";import{homedir as Ur}from"node:os";import{join as jr}from"node:path";var ln=process.env.ORACLE_PUBLIC_DESKTOP==="1",Os=ln?process.env.ORACLE_CONFIG_DIR||jr(Ur(),".config","oracle"):jr(Ur(),".config","oracle"),Cu=ln?Os:jr(Ur(),".config","mad-desk");var Fu="0".repeat(64),qu=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 nr(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(nr).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+nr(e[r])).join(",")+"}"}var Du=Promise.resolve();function ve(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=s=>{try{return M.realpathSync(s)}catch{return fe.resolve(s)}},n=r(fe.dirname(fe.resolve(e))),o=r(fe.dirname(fe.resolve(t))),i=(s,a)=>a===s||a.startsWith(s+fe.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var Bs=864e5,D=(e,t)=>Ls("sha256",t).update(nr(e)).digest("hex"),Z=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&_s(r,n)},Cs=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Ps(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Z(e.integrity.mac,D(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function ir(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(!Z(n?.integrity?.mac,D(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 $s(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 a=ir(e,r);i=a.present&&a.ledgerInitialized===!0}catch{i=!1}let s={policySequence:Number(t),policyMac:String(n)};i&&(s.ledgerInitialized=!0),ce(e,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:D(s,r)}})+`
4
+ `)}function Ms(e,t){let r=ir(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 $s(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function dn(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(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=Ps(o,n);ve(r,e);let s=ir(r,n),a=Number(i.policySequence||0);if(!s.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(a!==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(!Z(s.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Me(e,t,r,n,o){let i=`${e}.continuity`,s;try{let a=JSON.parse(L(e));if(a?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Z(a?.integrity?.mac,D(a.ledger,t)))throw new Error("integrity verification failed");if(s=a.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(a){if(a?.code==="ENOENT"){if(M.existsSync(i)||M.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=ir(o,t);if(c.present&&c.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:r,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${a?.message||a}`)}try{let a=JSON.parse(L(i));if(a?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Z(a?.integrity?.mac,D(a.marker,t)))throw new Error("continuity verification failed");if(a.marker?.version===2&&(a.marker.sequence!==s.sequence||!Z(a.marker.ledgerMac,D(s,t))))throw new Error("continuity rollback detected");if(a.marker?.version!==2&&s.sequence!==void 0)throw new Error("continuity rollback detected");if(M.existsSync(n)&&(a.marker?.version!==2||s.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(a.marker?.version===2){let c=JSON.parse(L(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Z(c?.integrity?.mac,D(c.marker,t))||c.marker?.version!==1||c.marker.sequence!==s.sequence||!Z(c.marker.ledgerMac,D(s,t)))throw new Error("checkpoint rollback detected")}}catch(a){throw new Error(`ledger: corrupt or unreadable: ${a?.message||a}`)}if(r-s.windowStartMs>=Bs){let a=s.entries.map(c=>c.state==="reserved"?c:{...c,state:"consumed",value:"0",notional:"0"});return{windowStartMs:r,entries:a,sequence:s.sequence??0}}return{...s,sequence:s.sequence??0}}function or(e,t,r){return e.filter(n=>(n.unit||"wei")===r).reduce((n,o)=>n+BigInt(o[t]??0),0n)}function fn(e,t){let r=t==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:t==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:t==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:null;if(!r)throw new Error("ledger: unsupported accounting unit");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 Re(e,t){let r=`${e}.lock`,n=Ns(16).toString("hex"),o;try{o=M.openSync(r,M.constants.O_CREAT|M.constants.O_EXCL|M.constants.O_WRONLY|(M.constants.O_NOFOLLOW||0),384),M.writeFileSync(o,n),M.fsyncSync(o)}catch(i){throw o!==void 0&&M.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return t()}finally{M.closeSync(o);try{L(r)===n&&M.unlinkSync(r)}catch{}}}function $e(e,t,r,n,o){let i=`${e}.continuity`,s={...t,sequence:(t.sequence??0)+1},a=D(s,r);ce(e,JSON.stringify({ledger:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:a}})+`
5
+ `);let c={version:2,sequence:s.sequence,ledgerMac:a};ce(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:D(c,r)}})+`
6
+ `);let u={version:1,sequence:s.sequence,ledgerMac:a};M.mkdirSync(fe.dirname(n),{recursive:!0,mode:448}),ce(n,JSON.stringify({marker:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:D(u,r)}})+`
7
+ `),o&&Ms(o,r)}function pn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:s=0,notional:a=0,fee:c,policy:u,nowMs:d=Date.now()}){let l=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(l))throw new Error("ledger: bounded tradeId required");ve(r,e);let f=L(t);return Re(e,()=>{let m=Me(e,f,d,r,n);if(m.entries.some(b=>String(b.tradeId)===l))throw new Error("ledger: replayed tradeId");let p=BigInt(s),g=BigInt(a),[w,h,x]=fn(u,i);if(p<0n||g<0n||g>x)throw new Error("ledger: per-trade cap exceeded");if(or(m.entries,"value",i)+p>w||or(m.entries,"notional",i)+g>h)throw new Error("ledger: daily cap exceeded");let E={tradeId:l,unit:i,value:p.toString(),notional:g.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:d};return m.entries.push(E),$e(e,m,f,r,n),structuredClone(E)})}function mn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:s,nowMs:a=Date.now()}){ve(r,e);let c=L(t);return Re(e,()=>{let u=Me(e,c,a,r,n),d=u.entries.find(g=>String(g.tradeId)===String(o?.tradeId??"")&&g.state==="reserved");if(!d||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",[f,m,p]=fn(i,l);if(BigInt(d.notional)>p)throw new Error("ledger: per-trade cap exceeded");if(or(u.entries,"value",l)>f||or(u.entries,"notional",l)>m)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function hn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ve(r,e);let s=L(t);return Re(e,()=>{let a=Me(e,s,i,r,n),c=a.entries.find(u=>String(u.tradeId)===String(o??"")&&u.state==="reserved");if(!c||c.state!=="reserved")throw new Error("ledger: reservation unavailable");return c.state="committed",c.committedAtMs=i,$e(e,a,s,r,n),structuredClone(c)})}function wn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ve(r,e);let s=L(t);return Re(e,()=>{let a=Me(e,s,i,r,n),c=a.entries.findIndex(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(c<0)throw new Error("ledger: reservation unavailable");let[u]=a.entries.splice(c,1);return $e(e,a,s,r,n),structuredClone(u)})}function gn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ve(r,e);let s=L(t);return Re(e,()=>{let a=Me(e,s,i,r,n),c=a.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");let u=BigInt(c.fee??0);return u<=0n?(c.state="committed",c.committedAtMs=i,c.value="0",c.notional="0",c.settledAs="no-fee",$e(e,a,s,r,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=u.toString(),c.settledAs="fee-only",$e(e,a,s,r,n),structuredClone(c))})}function yn(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:te(Cs(t))};return Z(e.mac,D(o,L(r)))}function Rs(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function En(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:te(Rs(t))};return Z(e.mac,D(o,L(r)))}import{spawnSync as Fs}from"node:child_process";function xn(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=Fs(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}import{Wallet as Wr}from"ethers";import{base58 as An}from"@scure/base";import{ed25519 as qs}from"@noble/curves/ed25519.js";import{NETWORK as vn,TEST_NETWORK as In,WIF as Ds,p2wpkh as bn}from"@scure/btc-signer";import{pubECDSA as Us}from"@scure/btc-signer/utils.js";var js=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Ws=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},Ie=(e,t)=>{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`)};function Hr(e,t){let r=String(t||"").trim();if(e==="evm")return new Wr(r).privateKey;if(e==="btc")for(let i of[vn,In])try{return Buffer.from(Ds(i).decode(r))}catch{}if(e==="sol")try{return Ie(An.decode(r),"sol")}catch{}let n=js(r);if(n)return e==="evm"?new Wr(`0x${n.toString("hex")}`).privateKey:Ie(n,e);let o=Ws(r);if(o)return Ie(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Ie(Uint8Array.from(i),e);let s=i.privateKey??i.secretKey??i.key;if(s)return Hr(e,Array.isArray(s)?JSON.stringify(s):String(s))}throw new Error(`${e}: unsupported private key format`)}function Sn(e,t){if(e==="evm"){let r=new Wr(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=Ie(t,"btc"),n=Us(r);return{kind:e,secret:r.toString("hex"),addresses:[bn(n,vn).address,bn(n,In).address]}}if(e==="sol"){let r=Ie(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[An.encode(qs.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function Tn(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:Sn(t.kind||"evm",Hr(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Sn(i,Hr(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function Jr(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}function Vs(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||z.join(process.env.XDG_STATE_HOME||z.join(Hs.homedir(),".local","state"),"oracle"),r=Js("sha256").update(z.resolve(e)).digest("hex").slice(0,16);return{vault:z.join(e,"vault.json"),policy:z.join(e,"signer-policy.json"),policyKey:z.join(e,"policy-integrity-key"),policyAnchor:z.join(t,`signer-policy-${r}.high-water`),ledger:z.join(e,"signer-ledger.json"),ledgerAnchor:z.join(t,`signer-ledger-${r}.high-water`),token:z.join(e,"signer-token"),lock:z.join(t,`signer-${r}.lock`)}}function Ks(e){try{return L(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=Gs(32).toString("hex");return ce(e,t+`
8
+ `),t}function zr(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 On(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function F(e,t){return e.surfaces.includes(t)}function Ys(e,t,r){let n=e?.version===1&&e?.surface?e:null,o=n?.artifact||e||{},i=[`surface=${n?.surface||"evm"} action=${n?.action||"evm"}`,`chain=${o.chainId??o.network??o.cluster??"n/a"} owner=${n?.owner||o.from||"n/a"}`,`to=${o.to||n?.destination||"n/a"} calldata=${String(o.data||"0x")} value=${o.value??"n/a"}`,`gas=${o.gasLimit??"n/a"} maxFeePerGas=${o.maxFeePerGas??o.gasPrice??"n/a"} maxPriorityFeePerGas=${o.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${o.l1FeeWei??"n/a"} operatorFeeWei=${o.operatorFeeWei??"n/a"}`,`nonce=${o.nonce??"n/a"} type=${o.type??"n/a"} accessList=${Array.isArray(o.accessList)?o.accessList.length:0}`,`slippageBps=${n?.slippageBps??o.slippageBps??"n/a"} expiresAtMs=${n?.expiresAtMs??o.expiresAtMs??"n/a"}`],s=(c,u)=>{if(i.push(`LEG ${u} chain=${c.chainId??"n/a"} from=${c.from??"n/a"} to=${c.to??"n/a"}`),i.push(`LEG ${u} calldata=${String(c.data||"0x")} value=${c.value??"n/a"}`),i.push(`LEG ${u} gas=${c.gasLimit??"n/a"} maxFeePerGas=${c.maxFeePerGas??c.gasPrice??"n/a"} maxPriorityFeePerGas=${c.maxPriorityFeePerGas??"n/a"}`),i.push(`LEG ${u} l1FeeWei=${c.l1FeeWei??"n/a"} operatorFeeWei=${c.operatorFeeWei??"n/a"} nonce=${c.nonce??"n/a"} type=${c.type??"n/a"}`),V(String(c.data||"0x")))try{let d=Le(String(c.data||"0x"));i.push(`LEG ${u} APPROVAL token=${d.token||c.to||"n/a"} spender=${d.spender} amount=${d.amount}`)}catch{i.push(`LEG ${u} APPROVAL spender=undecodable amount=undecodable`)}},a=String(o.data||"0x");if(V(a))try{let c=Le(a);i.push(`APPROVAL token=${c.token||o.to||"n/a"} spender=${c.spender} amount=${c.amount}`)}catch{i.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(o.transactions)&&(i.push(`batchLegs=${o.transactions.length}`),o.transactions.forEach((c,u)=>s(c,u))),n?.surface==="btc"){let c=wr(n,r);i.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(n?.surface==="sol"){let c=Sr(n,r);i.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(n?.surface==="hl"){let c=ie(n,r);i.push(`hlKind=${c.kind} actionType=${c.actionType} coin=${c.coin||"n/a"} amount=${c.amount} notionalUsd=${c.notional} submitTo=${c.submitTo}`)}if(n?.surface==="poly"){let c=se(n,r);i.push(`polyKind=${c.kind} tokenId=${c.tokenId} notionalUsdc=${c.notional} submitTo=${c.submitTo}`)}if(n?.surface==="lighter"){let c=ae(n,r);i.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
9
9
  Confirm exact action
10
10
  ${i.join(`
11
11
  `)}
12
- Type digest ${t}: `}async function Qe(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 bn(e,t){return Buffer.concat([Buffer.from([1]),Buffer.from(t),Buffer.from(e)]).toString("base64")}async function Sn(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 Qe(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function Ma(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let a=await fetch(`${o}/tx/${t}/outspend/${r}`);if(a.ok){let s=await a.json();if(s?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(s?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await Sn(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Fa(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 qa(e,t){return{simulate:async(r,n)=>(Q(n,e()),!0),sign:async(r,n)=>{Q(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return r?.typedData?(Ct(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Pt({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{Q(o,e());let{Signature:i,keccak256:a}=await import("ethers"),s=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:s.r,s:s.s,v:s.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(r),status:1}}}}function $a(e){return{simulate:async(t,r)=>(re(r,e()),!0),sign:async(t,r)=>{re(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 Oe(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=re(n,e()),i=Oe(r,t),a=Mt(i),s=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),c=await s.json().catch(()=>({}));if(!s.ok||Number(c?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(c?.tx_hash||c?.txHash||"lighter"),status:1}}}}function Da(e,t){return{simulate:async(r,n)=>(ee(n,e()),!0),sign:async(r,n)=>{ee(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),a=ee(o,i),s=gr(i),{keccak256:c}=await import("ethers"),u=gt({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:s.key}),f=JSON.stringify(u),l=ht({creds:s,address:o.owner,method:"POST",path:"/order",body:f}),p=await fetch(a.submitTo,{method:"POST",headers:l,body:f}),d=await p.json().catch(()=>({}));if(!p.ok||d?.success===!1||d?.error||d?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:c(r),status:1}}}}function Ua(e,t){let r=Rr(t);return{simulate:async n=>{let o=e(),i=Mr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let a=0;a<i.inputsLength;a++){let s=i.getInput(a),c=Buffer.from(s.txid||[]).toString("hex");await Ma(o,c,s.index)}return!0},sign:n=>{let o=Mr.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(r),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let a=Mr.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let s;try{let u=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(s=(await u.text()).trim(),!u.ok)throw new Error(`signer: Bitcoin broadcast failed ${u.status}`)}catch(u){if(!/Bitcoin broadcast failed 404/.test(String(u?.message||u)))throw u;s=await Sn(o,"sendrawtransaction",[a.hex])}if(s&&String(s).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let u=i.endsWith("/tx")?i.slice(0,-3):i,f=await fetch(`${u}/tx/${a.id}/status`);f.ok&&(c=(await f.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:c}}}}function ja(e,t){let r=Rr(t);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let a=Buffer.from(n.messageBase64,"base64"),s=bn(a,new Uint8Array(64)),c=await Qe(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[s,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Fa(c)},sign:n=>bn(Buffer.from(n.messageBase64,"base64"),Ba.sign(Buffer.from(n.messageBase64,"base64"),r)),broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let a=await Qe(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await Qe(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:a,status:0};let u=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:a,status:u?1:null}}}}function Wa(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 An({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:s,Wallet:c}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(a<1e3||a>12e4)throw new Error("signer: session must be at most 120 seconds");let u=Ca(e),f=()=>Object.freeze(rn(u.policy,u.policyKey,{sequenceAnchorFile:u.policyAnchor})),l=f();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(g=>String(g).startsWith("evm"))&&p.push("chains","spenders");for(let g of p)if(!Array.isArray(l[g])||l[g].length===0)throw new Error(`signer: ${g} allowlist is empty`);if(l.surfaces.some(g=>g==="evm-swap"||g==="evm-bridge"||g==="evm-nft")){for(let g of["providers"])if(!Array.isArray(l[g])||l[g].length===0)throw new Error(`signer: ${g} allowlist is empty`)}if(l.surfaces.some(g=>g==="evm-swap"||g==="evm-bridge")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(g=>String(g).startsWith("evm"))&&(!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(R(l,"poly")&&(gr(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(R(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(R(l,"hl")){let g=Array.isArray(l.coins)?l.coins.map(String):[],A=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(g.filter(M=>M!=="*"&&M!=="#*").length&&!g.includes("*")&&A.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let d=r?fn(r):O(t),m=Qt(u.vault),y=Zt(m,d),w;try{w=gn(y,m.meta)}finally{y.fill(0)}(En(l)||R(l,"hl")||R(l,"poly"))&&Fr("evm",w.evm,l.owners),R(l,"btc")&&Fr("btc",w.btc,l.owners),R(l,"sol")&&Fr("sol",w.sol,l.owners);let h=Array.isArray(l.chains)?l.chains.filter(g=>Number.isInteger(Number(g))&&String(g).trim()!==""):[],b=En(l);if(b&&(h.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(R(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(R(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=b?new s(l.rpcUrl,Number(h[0])):null,S=w.evm&&(b||R(l,"hl")||R(l,"poly"))?E?new c(w.evm.secret).connect(E):new c(w.evm.secret):null,I=E?{simulate:async g=>{if((await E.getNetwork()).chainId!==BigInt(g.chainId))throw new Error("signer: RPC chain mismatch");return await E.call(g),!0},sign:g=>S.signTransaction(g),broadcast:async(g,A)=>{if((await E.getNetwork()).chainId!==BigInt(A.chainId))throw new Error("signer: RPC chain mismatch");let M={native:(await E.getBalance(A.from)).toString()},Ee=await E.broadcastTransaction(g),Z=await Ee.wait(),Ce={native:(await E.getBalance(A.from)).toString()};return{hash:Z?.hash??Ee.hash,status:Z?.status??null,verifiedBefore:M,verifiedAfter:Ce}}}:null,k=E?async g=>Ja(E,g):void 0,v={...I?{evm:I,"evm-swap":I,"evm-bridge":I,"evm-nft":I}:{},...w.btc?{btc:Ua(f,w.btc)}:{},...w.sol?{sol:ja(f,w.sol)}:{},...S&&R(l,"hl")?{hl:qa(f,S)}:{},...S&&R(l,"poly")?{poly:Da(f,S)}:{},...R(l,"lighter")?{lighter:$a(f)}:{}};Wa(v,n);let ye=_t({...v,...n}),Tn=new Set(Object.keys(v)),In=new Set(Object.keys(n||{})),qr=l.surfaces.filter(g=>!Tn.has(g)&&!In.has(g));if(qr.length)throw new Error(`signer: ${qr.join(",")} require local keys or injected surface transports`);let kn=Date.now(),$r=kn+a,tr=!1,On=()=>tr?!1:yn.existsSync(u.lock)?(tr=!0,!1):yn.existsSync(u.vault)&&Date.now()<$r,Ln=()=>(tr=!0,te(u.lock,`disarmed ${new Date().toISOString()}
13
- `),!0),Be=Xt({host:o,port:i,token:Pa(u.token),policy:l,readPolicy:f,isArmed:On,disarm:Ln,sessionExpiresAtMs:$r,nowMs:Date.now,simulate:(g,A)=>Je(A,ye).simulate(g,A),estimateNetworkFees:k,sign:(g,A)=>Je(A,ye).sign(g,A),verifySigned:(g,A,L)=>Wt(L?.surface||"evm",g,A,L),broadcast:(g,A,L)=>Je(L,ye).broadcast(g,A,L),confirmArtifact:Va,decodeEconomics:(g,A)=>Sr(g,A),reserveLedger:(g,A)=>{let L=g?.version===1&&g?.surface?g:null,M=L?.artifact||g,Ee=L?.tradeId||M?.tradeId;if(!Ee)throw new Error("ledger: executable artifact requires a tradeId");let Z;if(L)Z=Sr(L,A);else{if(M?.value===void 0)throw new Error("ledger: executable artifact value required");let Ce=BigInt(M.value),Ur=BigInt(M.gasLimit??0),jr=BigInt(M.maxFeePerGas??M.gasPrice??0);if(Ur<=0n||jr<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let Wr=Ur*jr+BigInt(M.l1FeeWei??0)+BigInt(M.operatorFeeWei??0);Z={unit:"wei",value:Ce.toString(),notional:(Ce+Wr).toString(),fee:Wr.toString()}}if(Z.value===void 0||Z.notional===void 0)throw new Error("ledger: decoded value and notional required");return nn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:Ee,...Z,policy:A})},commitLedger:g=>an({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),releaseLedger:g=>sn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),settleFailedLedger:g=>cn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),validateReservation:(g,A,L)=>on({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,reservation:g,policy:A,economics:L}),verifyFeeWaiver:(g,A)=>ln(g,A,u.policyKey),verifyTriggerAttestation:(g,A,L)=>un(g,A,u.policyKey,L),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),Dr=setTimeout(()=>Be.close(),a);return Dr.unref(),Be.on("close",()=>{clearTimeout(Dr)}),Be.listen(i,o),Be}var er="0x420000000000000000000000000000000000000F";function xn(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 Ja(e,t){if(!V(t?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:r,Transaction:n}=await import("ethers"),o=new r(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce??0,type:t.type,accessList:t.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let a;try{let s=await e.call({to:er,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",s)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await Ha(e,o,t.gasLimit)}}async function Ha(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:er,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!xn(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:er,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:er,data:t.encodeFunctionData("operatorFeeConstant")}),a=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),s=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+s).toString()}catch(o){if(!xn(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function Va(e,t,r){return process.stdin.isTTY?(process.stderr.write(Ra(e,t,r)),process.stdin.resume(),new Promise(n=>{let o=i=>{process.stdin.off("data",o),process.stdin.pause(),n(String(i).trim()===t)};process.stdin.once("data",o)})):!1}var vn=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
14
- Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,rr=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function za(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(vn+`
15
- `),0;let r=rr(e,"--passphrase-file"),n=await An({configDir:Ga.join(t.configDir||Re(),"signer"),passphraseFile:r,credentialService:rr(e,"--credential-service"),port:Number(rr(e,"--port",9462)),sessionMs:Number(rr(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
16
- `),await new Promise(o=>n.on("close",o)),0}var Zu={name:"signer",summary:"run the short-lived loopback signer",usage:vn,run:e=>za(e.argv||[])};export{Zu as default,za as run};
12
+ Type digest ${t}: `}async function sr(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 Ln(e,t){return Buffer.concat([Buffer.from([1]),Buffer.from(t),Buffer.from(e)]).toString("base64")}async function _n(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 sr(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function Xs(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 a=await s.json();if(a?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(a?.spent===!1)return!0}}catch(s){if(/already spent/.test(String(s?.message||s)))throw s}if(!await _n(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Zs(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 Qs(e,t){return{simulate:async(r,n)=>(ie(n,e()),!0),sign:async(r,n)=>{ie(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?(Ut(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):jt({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{ie(o,e());let{Signature:i,keccak256:s}=await import("ethers"),a=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:a.r,s:a.s,v:a.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:s(r),status:1}}}}function ea(e){return{simulate:async(t,r)=>(ae(r,e()),!0),sign:async(t,r)=>{ae(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 Pe(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=ae(n,e()),i=Pe(r,t),s=Jt(i),a=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s}),c=await a.json().catch(()=>({}));if(!a.ok||Number(c?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(c?.tx_hash||c?.txHash||"lighter"),status:1}}}}function ra(e,t){return{simulate:async(r,n)=>(se(n,e()),!0),sign:async(r,n)=>{se(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=se(o,i),a=Tr(i),{keccak256:c}=await import("ethers"),u=It({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:a.key}),d=JSON.stringify(u),l=At({creds:a,address:o.owner,method:"POST",path:"/order",body:d}),f=await fetch(s.submitTo,{method:"POST",headers:l,body:d}),m=await f.json().catch(()=>({}));if(!f.ok||m?.success===!1||m?.error||m?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:c(r),status:1}}}}function ta(e,t){let r=Jr(t);return{simulate:async n=>{let o=e(),i=Gr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let s=0;s<i.inputsLength;s++){let a=i.getInput(s),c=Buffer.from(a.txid||[]).toString("hex");await Xs(o,c,a.index)}return!0},sign:n=>{let o=Gr.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=Gr.fromPSBT(Buffer.from(n,"base64"));s.finalize(),s.extract();let a;try{let u=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:s.hex});if(a=(await u.text()).trim(),!u.ok)throw new Error(`signer: Bitcoin broadcast failed ${u.status}`)}catch(u){if(!/Bitcoin broadcast failed 404/.test(String(u?.message||u)))throw u;a=await _n(o,"sendrawtransaction",[s.hex])}if(a&&String(a).toLowerCase()!==s.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let u=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${u}/tx/${s.id}/status`);d.ok&&(c=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:s.id,status:c}}}}function na(e,t){let r=Jr(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"),a=Ln(s,new Uint8Array(64)),c=await sr(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[a,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Zs(c)},sign:n=>Ln(Buffer.from(n.messageBase64,"base64"),zs.sign(Buffer.from(n.messageBase64,"base64"),r)),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 sr(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await sr(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[s],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:s,status:0};let u=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:s,status:u?1:null}}}}function oa(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 Bn({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:s=12e4}={}){let{JsonRpcProvider:a,Wallet:c}=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 u=Vs(e),d=()=>Object.freeze(dn(u.policy,u.policyKey,{sequenceAnchorFile:u.policyAnchor})),l=d();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 f=["surfaces","actions","destinations","owners"];l.surfaces.some(y=>String(y).startsWith("evm"))&&f.push("chains","spenders");for(let y of f)if(!Array.isArray(l[y])||l[y].length===0)throw new Error(`signer: ${y} allowlist is empty`);if(l.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge"||y==="evm-nft")){for(let y of["providers"])if(!Array.isArray(l[y])||l[y].length===0)throw new Error(`signer: ${y} allowlist is empty`)}if(l.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(y=>String(y).startsWith("evm"))&&(!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(F(l,"poly")&&(Tr(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(F(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(F(l,"hl")){let y=Array.isArray(l.coins)?l.coins.map(String):[],A=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(y.filter(q=>q!=="*"&&q!=="#*").length&&!y.includes("*")&&A.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let m=r?xn(r):L(t),p=un(u.vault),g=cn(p,m),w;try{w=Tn(g,p.meta)}finally{g.fill(0)}(On(l)||F(l,"hl")||F(l,"poly"))&&zr("evm",w.evm,l.owners),F(l,"btc")&&zr("btc",w.btc,l.owners),F(l,"sol")&&zr("sol",w.sol,l.owners);let h=Array.isArray(l.chains)?l.chains.filter(y=>Number.isInteger(Number(y))&&String(y).trim()!==""):[],x=On(l);if(x&&(h.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(F(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(F(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=x?new a(l.rpcUrl,Number(h[0])):null,b=w.evm&&(x||F(l,"hl")||F(l,"poly"))?E?new c(w.evm.secret).connect(E):new c(w.evm.secret):null,T=E?{simulate:async y=>{if((await E.getNetwork()).chainId!==BigInt(y.chainId))throw new Error("signer: RPC chain mismatch");return await E.call(y),!0},sign:y=>b.signTransaction(y),broadcast:async(y,A)=>{if((await E.getNetwork()).chainId!==BigInt(A.chainId))throw new Error("signer: RPC chain mismatch");let q={native:(await E.getBalance(A.from)).toString()},ke=await E.broadcastTransaction(y),ne=await ke.wait(),qe={native:(await E.getBalance(A.from)).toString()};return{hash:ne?.hash??ke.hash,status:ne?.status??null,verifiedBefore:q,verifiedAfter:qe}}}:null,O=E?async y=>ia(E,y):void 0,v={...T?{evm:T,"evm-swap":T,"evm-bridge":T,"evm-nft":T}:{},...w.btc?{btc:ta(d,w.btc)}:{},...w.sol?{sol:na(d,w.sol)}:{},...b&&F(l,"hl")?{hl:Qs(d,b)}:{},...b&&F(l,"poly")?{poly:ra(d,b)}:{},...F(l,"lighter")?{lighter:ea(d)}:{}};oa(v,n);let Te=qt({...v,...n}),Pn=new Set(Object.keys(v)),$n=new Set(Object.keys(n||{})),Vr=l.surfaces.filter(y=>!Pn.has(y)&&!$n.has(y));if(Vr.length)throw new Error(`signer: ${Vr.join(",")} require local keys or injected surface transports`);let Mn=Date.now(),Kr=Mn+s,ur=!1,Rn=()=>ur?!1:kn.existsSync(u.lock)?(ur=!0,!1):kn.existsSync(u.vault)&&Date.now()<Kr,Fn=()=>(ur=!0,ce(u.lock,`disarmed ${new Date().toISOString()}
13
+ `),!0),Fe=an({host:o,port:i,token:Ks(u.token),policy:l,readPolicy:d,isArmed:Rn,disarm:Fn,sessionExpiresAtMs:Kr,nowMs:Date.now,simulate:(y,A)=>Ye(A,Te).simulate(y,A),estimateNetworkFees:O,sign:(y,A)=>Ye(A,Te).sign(y,A),verifySigned:(y,A,N)=>Zt(N?.surface||"evm",y,A,N),broadcast:(y,A,N)=>Ye(N,Te).broadcast(y,A,N),confirmArtifact:aa,decodeEconomics:(y,A)=>Br(y,A),reserveLedger:(y,A)=>{let N=y?.version===1&&y?.surface?y:null,q=N?.artifact||y,ke=N?.tradeId||q?.tradeId;if(!ke)throw new Error("ledger: executable artifact requires a tradeId");let ne;if(N)ne=Br(N,A);else{if(q?.value===void 0)throw new Error("ledger: executable artifact value required");let qe=BigInt(q.value),Xr=BigInt(q.gasLimit??0),Zr=BigInt(q.maxFeePerGas??q.gasPrice??0);if(Xr<=0n||Zr<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let Qr=Xr*Zr+BigInt(q.l1FeeWei??0)+BigInt(q.operatorFeeWei??0);ne={unit:"wei",value:qe.toString(),notional:(qe+Qr).toString(),fee:Qr.toString()}}if(ne.value===void 0||ne.notional===void 0)throw new Error("ledger: decoded value and notional required");return pn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:ke,...ne,policy:A})},commitLedger:y=>hn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:y.tradeId}),releaseLedger:y=>wn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:y.tradeId}),settleFailedLedger:y=>gn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:y.tradeId}),validateReservation:(y,A,N)=>mn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,reservation:y,policy:A,economics:N}),verifyFeeWaiver:(y,A)=>En(y,A,u.policyKey),verifyTriggerAttestation:(y,A,N)=>yn(y,A,u.policyKey,N),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),Yr=setTimeout(()=>Fe.close(),s);return Yr.unref(),Fe.on("close",()=>{clearTimeout(Yr)}),Fe.listen(i,o),Fe}var ar="0x420000000000000000000000000000000000000F";function Nn(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 ia(e,t){if(!K(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 a=await e.call({to:ar,data:o.encodeFunctionData("getL1Fee",[i])});s=o.decodeFunctionResult("getL1Fee",a)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:s,operatorFeeWei:await sa(e,o,t.gasLimit)}}async function sa(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:ar,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Nn(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:ar,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:ar,data:t.encodeFunctionData("operatorFeeConstant")}),s=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),a=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*s/1000000n+a).toString()}catch(o){if(!Nn(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function aa(e,t,r){return process.stdin.isTTY?(process.stderr.write(Ys(e,t,r)),process.stdin.resume(),new Promise(n=>{let o=i=>{process.stdin.off("data",o),process.stdin.pause(),n(String(i).trim()===t)};process.stdin.once("data",o)})):!1}var Cn=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
14
+ Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,cr=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function ua(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(Cn+`
15
+ `),0;let r=cr(e,"--passphrase-file"),n=await Bn({configDir:ca.join(t.configDir||Ue(),"signer"),passphraseFile:r,credentialService:cr(e,"--credential-service"),port:Number(cr(e,"--port",9462)),sessionMs:Number(cr(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
16
+ `),await new Promise(o=>n.on("close",o)),0}var Bl={name:"signer",summary:"run the short-lived loopback signer",usage:Cn,run:e=>ua(e.argv||[])};export{Bl as default,ua as run};