@oracle-agent/oracle 0.28.13 → 0.28.15

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,13 +1,13 @@
1
- import Mn from"node:fs";import ee from"node:path";import Ka from"node:os";import{createHash as Ya,randomBytes as Xa}from"node:crypto";import{execFileSync as Qa}from"node:child_process";import{fileURLToPath as Za}from"node:url";import{Interface as lr,keccak256 as es}from"ethers";import{Transaction as sr}from"@scure/btc-signer";import{ed25519 as ts}from"@noble/curves/ed25519.js";import ya from"node:http";import{timingSafeEqual as Ea}from"node:crypto";import{createHash as aa,randomBytes as sa,timingSafeEqual as ca}from"node:crypto";import{base58 as wn}from"@scure/base";import{Interface as Jr}from"ethers";import{Interface as co,MaxUint256 as uo,isAddress as lo,keccak256 as rc,toUtf8Bytes as nc}from"ethers";import{Interface as ao,isAddress as _s}from"ethers";import{isAddress as Cs}from"ethers";import{createHash as Xn,createHmac as Qn,timingSafeEqual as Zn}from"node:crypto";import{readFileSync as Vn}from"node:fs";import{homedir as Gn}from"node:os";import{join as rt}from"node:path";function Kn(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let t=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return t?[t]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),r=Gn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||rt(r,".config","oracle")).trim();return[e,rt(t,"exec.env")].filter(Boolean)}return[e,rt(r,".config","oracle","exec.env"),rt(r,".config","mad-desk","exec.env")].filter(Boolean)}function Je(e,r,t){let n=e??process.env[r]??process.env[t];if(!String(n||"").trim())for(let o of Kn())try{let i=Vn(o,"utf8"),a=i.match(new RegExp(`^${r}=(.*)$`,"m"))||i.match(new RegExp(`^${t}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${r} required for attestation. Set it in the environment, or place ${r}=<value> in ~/.config/oracle/exec.env`);return n}function Oe(e,r,t="guard"){let n=Number(r);if(r==null||!Number.isFinite(n))throw new Error(`${t}: current time must be a finite number (got ${Yn(r)})`);let o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${t}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${t} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${t}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${t}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function Yn(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var fr=100;function vt(e){return Array.isArray(e)?`[${e.map(vt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${vt(e[r])}`).join(",")}}`:JSON.stringify(e??null)}function eo(e,{required:r=!1}={}){try{return Je(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(t){if(r)throw t;return null}}function to(e){let{signature:r,...t}=e;return t}function ro(e){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<10||r.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return Xn("sha256").update(Buffer.from(r.slice(2),"hex")).digest("hex")}function no(e,r){let t=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(r??""),"utf8");return t.length!==n.length||t.length===0?!1:Zn(t,n)}function oo(e){let r=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(r)||r.length<10||r.length%2!==0)return null;let t=r.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=r.length;i+=64)n.push(r.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(t){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 It(e,{nowMs:r=Date.now(),chainId:t,venue:n,secret:o,tx:i,requireSigned:a=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let c=eo(o,{required:a});if(a&&!c)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(c){let p=Qn("sha256",c).update(vt(to(e))).digest("hex");if(!no(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 u=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(u)||u<0||u>fr)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(s)||s<0||s>fr||u>s)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{Oe({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},r,"auto-slippage quote")}catch(p){throw new Error(`${p.message}; re-quote before signing`)}if(t!=null&&Number(e.chainId)!==Number(t))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-u),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=oo(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==ro(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 Us=new ao(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as so,isAddress as Hs}from"ethers";var Gs=new so(["function approve(address spender,uint256 amount) returns (bool)"]),Ks=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function P(e,r="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${r} 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(`${r} 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(`${r} must be a number or decimal string`);return e}throw new Error(`${r} must be a number or decimal string`)}function W(e,r="value"){if(typeof e!="string"||e==="")throw new Error(`${r} must be a string`);return e}function ue(e,r="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${r} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${r} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let t=P(e,r);if(t==="")throw new Error(`${r} is required`);if(!/^-?\d+$/.test(t)&&!/^0x[0-9a-fA-F]+$/.test(t))throw new Error(`${r} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(t)}`);try{return BigInt(t)}catch{throw new Error(`${r} must be an integer, got ${JSON.stringify(t)}`)}}function Tt(e,r="amount"){let t=ue(e,r);if(t<=0n)throw new Error(`${r} must be positive`);return t}function q(e,r,t="amount"){let n=P(e,t);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${t} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[a="0",c=""]=i.split(".");if(c.length>r)throw new Error(`${t} has more than ${r} decimal places, which would lose precision`);let u=BigInt((a||"0")+c.padEnd(r,"0"));return o?-u:u}var uc=new co(["function approve(address spender,uint256 amount) returns (bool)"]);function pr(e,r){let t=String(e||"").trim();if(!lo(t))throw new Error(`${r} must be an address`);return t.toLowerCase()}function fo(e,r="approval amount",{allowZero:t=!1}={}){let n=ue(e,r);if(t?n<0n:n<=0n)throw new Error(`${r} must be positive`);if(n>=uo)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var mr=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),po=new Set(["0x39509351","0xf9255c1f"]);function te(e){let r=String(e||"").toLowerCase();return r.length<10?!1:mr.has(r.slice(0,10))}function ze(e){if(!te(e))throw new Error("approval calldata required");let r=String(e||"").toLowerCase(),t=r.slice(0,10),n=r.slice(10).match(/.{1,64}/g)||[],o=s=>n[s]?"0x"+n[s].slice(24):null,i=s=>n[s]?BigInt("0x"+n[s]):null,a=null,c=null,u=null;switch(t){case"0x095ea7b3":case"0x39509351":a=o(0),c=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":u=o(0),a=o(1),c=i(2);break;case"0xd505accf":a=o(1),c=i(2);break;case"0x8fcbaf0c":{a=o(1),c=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":u=o(0),a=o(1),c=i(2);break;default:throw new Error(`approval selector ${t} is recognised but not decodable; refusing to bound it`)}if(a==null||c==null)throw new Error("invalid approve calldata");return{spender:pr(a,"approval spender"),token:u==null?null:pr(u,"approval token"),amount:fo(c,"approval amount",{allowZero:!0}),selector:t,additive:po.has(t)}}import{createHash as mo,createHmac as fc,timingSafeEqual as pc}from"node:crypto";var wo=2,kt=300*1e3,wr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function ho(e){let r=e==null||e===""?kt:Number(e);return!Number.isFinite(r)||r<0?kt:Math.min(r,wr)}function Nt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Nt).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Nt(e[t])}`).join(",")}}`}function go(e){let{prepareHash:r,prepareMac:t,note:n,...o}=e||{};return o}function yo(e){let r=go(e);return mo("sha256").update(Nt(r)).digest("hex")}function hr(e,{maxAgeMs:r=kt,nowMs:t=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)!==wo)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let a=yo(e);if(String(e.prepareHash||"")!==a)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let c=Number(e.preparedAt),u=Number(e.expiresAt),s=ho(r),d=t-c,l=u-c;if(!Number.isFinite(d)||!Number.isFinite(u)||!Number.isFinite(l)||d<0||l<=0||l>wr||d>s||t>=u)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${s})`);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 nt=e=>String(e||"").toLowerCase(),Eo=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),bo=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function re(e){try{return bo.has(BigInt(e))}catch{return!1}}var X=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},gr=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},Ve=(e,r,t,n=String)=>{if(!Array.isArray(r)||r.length===0)throw new Error(`policy: ${t} allowlist is empty`);if(!r.map(n).includes(n(e)))throw new Error(`policy: ${t} not allowed`)};function ot(e,r,{nowMs:t=Date.now(),networkFees:n,requireNetworkFees:o=!1}={}){if(!e||!r)throw new Error("policy: artifact and policy required");if(Object.keys(e).some(m=>!Eo.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(r.chains)||r.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!r.chains.some(m=>i(m,e.chainId)))throw new Error("policy: chain not allowed");if(Ve(e.to,r.destinations,"destination",nt),Ve(String(e.data||"0x").slice(0,10),r.selectors,"selector",m=>String(m).toLowerCase()),Ve(e.from,r.owners,"owner",nt),te(e.data)){let m;try{m=ze(e.data)}catch(g){throw new Error(`policy: malformed approval calldata: ${g?.message||g}`)}Ve(m.spender,r.spenders,"spender",nt),Ve(m.token||e.to,r.erc20Tokens,"ERC-20 token",nt);let p=X(r.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(X(e.value,"value")>X(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=X(e.gasLimit,"gasLimit");if(a>X(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let c=e.maxFeePerGas??e.gasPrice,u=X(c,"feePerGas")*a,s=0n;try{if(re(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&&(s+=X(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(s+=X(e.operatorFeeWei,"operatorFeeWei")),re(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=X(n.l1FeeWei,"estimated l1FeeWei")+X(n.operatorFeeWei,"estimated operatorFeeWei");if(s<m)throw new Error("policy: rollup fee attestation understates estimate")}if(u+s>X(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=gr(r.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<=t)throw new Error("policy: artifact expired");let f=gr(r.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-t>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as yr}from"node:crypto";import{Address as xo,NETWORK as So,OutScript as Er,RawTx as Ao,SigHash as br,TEST_NETWORK as vo,Transaction as Io}from"@scure/btc-signer";var xr=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},To=(e,r)=>{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 ${r}`);let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error(`envelope: invalid ${r}`);return t},ko=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,No=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),Ae=e=>No(e)?String(e).toLowerCase():String(e),Ot=(e,r)=>Array.isArray(r)&&r.some(t=>Ae(t)===Ae(e)),Oo=(e,r)=>Buffer.from(e||[]).equals(Buffer.from(r||[]));function Lo(e){let r=Buffer.from(Ao.encode(e)),t=yr("sha256").update(r).digest();return Buffer.from(yr("sha256").update(t).digest()).reverse().toString("hex")}function Co(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(Lo(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))throw new Error("envelope: Bitcoin prevout txid mismatch");let r=e.nonWitnessUtxo.outputs?.[e.index];if(!r)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(r.amount)||!Oo(e.witnessUtxo.script,r.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return r}function Lt(e,r){if(e.action!=="transfer")throw new Error("envelope: BTC decoder requires transfer action");let t=e?.artifact;if(Object.keys(t).some(l=>!["network","psbt"].includes(l)))throw new Error("envelope: unexpected BTC artifact field");if(!Ot(t.network,r.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(t.network).toLowerCase())?So:["testnet","signet","regtest"].includes(String(t.network).toLowerCase())?vo:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Io.fromPSBT(To(t.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=xo(n);for(let l=0;l<o.inputsLength;l++){let f=o.getInput(l);for(let g of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(ko(f[g]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==br.DEFAULT&&f.sighashType!==br.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let m=Co(f),p;try{let g=Er.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(!Ot(p,r.owners)||Ae(p)!==Ae(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...r.changeAddresses||[]].map(l=>Ae(l))),c=0n,u=!1,s=[];for(let l=0;l<o.outputsLength;l++){let f=o.getOutput(l),m;try{m=i.encode(Er.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let p=Ae(m);if(s.push(`${m}:${f.amount}`),p===Ae(e.destination)){u=!0,c+=f.amount;continue}if(Ot(m,r.destinations)){c+=f.amount;continue}if(!a.has(p))throw new Error("policy: Bitcoin output destination not allowed")}if(!u)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>xr(r.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(c>xr(r.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:c.toString(),notional:(c+d).toString(),fee:d.toString(),outputs:Object.freeze(s)})}function Ct(e,r){let{unit:t,value:n,notional:o,fee:i}=Lt(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}import{createHash as Pt}from"node:crypto";import{base58 as kr}from"@scure/base";import{getCompiledTransactionMessageDecoder as Bo}from"@solana/transaction-messages";var Rt="11111111111111111111111111111111",Po="ComputeBudget111111111111111111111111111111",Ro="So11111111111111111111111111111111111111112",Nr="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var Or="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Fo=5000n,$o=2039280n,_o=37095705934669439343138083508754565189542113879843219016388785533085940283555n,M=57896044618658097711785492504343953926634992332820282019728792003956564819949n,Sr=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Ar=e=>Pt("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),qo=new Map([[Ar("route"),{name:"route",prefixBytes:0}],[Ar("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),G=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},Mo=(e,r)=>{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 ${r}`);let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error(`envelope: invalid ${r}`);return t},le=(e,r)=>Array.isArray(r)&&r.some(t=>String(t)===String(e)),Q=e=>String(e||""),Do=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,at=e=>Pt("sha256").update(e).digest("hex");function it(e,r){try{let t=Buffer.from(kr.decode(String(e||"")));if(t.length!==32)throw new Error("wrong length");return t}catch{throw new Error(`envelope: invalid Solana ${r}`)}}function V(e){let r=e%M;return r>=0n?r:M+r}function ne(e,r){let t=e;for(;r-- >0n;)t=t*t%M;return t}function Uo(e){let t=e*e%M*e%M,n=ne(t,2n)*t%M,o=ne(n,1n)*e%M,i=ne(o,5n)*o%M,a=ne(i,10n)*i%M,c=ne(a,20n)*a%M,u=ne(c,40n)*c%M,s=ne(u,80n)*u%M,d=ne(s,80n)*u%M,l=ne(d,10n)*i%M;return ne(l,2n)*e%M}function jo(e,r){let t=V(r*r*r),n=V(t*t*r),o=Uo(e*n),i=V(e*t*o),a=V(r*i*i),c=i,u=V(i*Sr),s=a===e,d=a===V(-e),l=a===V(-e*Sr);return s&&(i=c),(d||l)&&(i=u),(V(i)&1n)===1n&&(i=V(-i)),!s&&!d?null:i}function Wo(e){if(!e||e.length!==32)return!1;let r=0n;for(let o=31;o>=0;o--)r=(r<<8n)+BigInt(o===31?e[o]&127:e[o]);let t=V(r*r),n=jo(V(t-1n),V(_o*t+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function Ho(e,r){let t=Buffer.concat([...e,it(r,"program id"),Buffer.from("ProgramDerivedAddress")]),n=Pt("sha256").update(t).digest();if(Wo(n))throw new Error("envelope: derived Solana program address is on curve");return kr.encode(n)}function Ft(e,r,t=Nr){let n=[it(e,"owner"),it(t,"token program"),it(r,"mint")];for(let o=255;o>=0;o--)try{return Ho([...n,Buffer.from([o])],Or)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function Jo(e,r){return(r.accountIndices||[]).map(t=>Q(e.staticAccounts[t]))}function Ge(e){return Buffer.from(e.data||[])}function zo(e,r){return Q(e.staticAccounts[r.programAddressIndex])}function Lr(e,r){return Number(r)<e.header.numSignerAccounts}function Vo(e,r){let t=e.header.numSignerAccounts,n=e.header.numReadonlySignerAccounts,o=e.header.numReadonlyNonSignerAccounts,i=e.staticAccounts.length;return Number(r)<t?Number(r)<t-n:Number(r)<i-o}function Ke(e){return e.accountIndices||[]}function Bt(e,r){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${r} allowlist required`);return e.map(String)}function vr(e,r){let t=Ke(r).map(n=>{let o=Lr(e,n)?"s":"n",i=Vo(e,n)?"w":"r";return`${n}:${Q(e.staticAccounts[n])}:${o}:${i}`});return at(Buffer.from(t.join(`
2
- `)))}function Ir(e,r,t){if(r+8>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readBigUInt64LE(r)}function Go(e,r,t){if(r+2>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readUInt16LE(r)}function Ko(e,r,t){if(r+4>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readUInt32LE(r)}function Yo(e,r,t){let n=t.maxJupiterRoutePlanSteps===void 0?1:Number(t.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(r<1||r>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(t.jupiterRouteVariants)?t.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=t.jupiterRouteVariantPayloadBytes||{},a=0,c=0,u=[];for(let s=0;s<r;s++){if(a>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e[a++];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(a+l+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e.subarray(a,a+l);a+=l;let m=f.toString("hex"),p=t.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[a++],h=e[a++],w=e[a++];if(g<1||g>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(h!==s||w!==s+1)throw new Error("envelope: unsupported Jupiter route-plan token index");c+=g,u.push(Object.freeze({swapVariant:d,variantPayloadHex:m,percent:g,inputIndex:h,outputIndex:w}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(c!==100*r)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(u)}function Xo(e,r){let t=Ge({data:e}),n=t.subarray(0,8).toString("hex"),o=qo.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,a=o.prefixBytes===1?t[8]:null;if(o.prefixBytes===1&&t.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let c=8+o.prefixBytes,u=c+4,s=t.length-i;if(s<=u)throw new Error("envelope: malformed Jupiter route payload");let d=Ko(t,c,"route plan length"),l=t.subarray(u,s),f=Yo(l,d,r);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:d,routePlan:f,routePlanHash:at(l),inAmount:Ir(t,s,"in_amount"),quotedOutAmount:Ir(t,s+8,"quoted_out_amount"),slippageBps:Go(t,s+16,"slippage_bps"),platformFeeBps:t[s+18],instructionHash:at(t)})}function Qo(e,r,t){let n=Jo(e,r),o=(i,a)=>{let c=n[i];if(!c)throw new Error(`envelope: Jupiter ${a} account missing`);return c};if(t.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(t.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 Tr(e,r){return e&&e!==r?e:null}function K(e,r,t){let n=Q(e.staticAccounts[r]);if(!n)throw new Error(`envelope: Jupiter ${t} missing`);return n}function Zo(e,r){let t=Ge(e);if(t.length===5&&t[0]===2){let n=t.readUInt32LE(1),o=r.maxComputeUnits===void 0?14e5:Number(r.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 t.length===9&&t[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function ei(e,r,t,n,o,i){let a=Ge(r);if(a.length!==1||a[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let c=Ke(r);if(c.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let u=K(e,c[0],"ATA payer"),s=K(e,c[1],"ATA account"),d=K(e,c[2],"ATA owner"),l=K(e,c[3],"ATA mint"),f=K(e,c[4],"ATA system program"),m=K(e,c[5],"ATA token program");if(u!==t.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(d!==t.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(f!==Rt)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(s!==Ft(t.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:s,debit:i}}function ti(e,r,t,n,o){let i=Ke(r),a=Ge(r);if(i.length!==2||a.length!==12||a.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let c=K(e,i[0],"wrap payer"),u=K(e,i[1],"wrap target"),s=a.readBigUInt64LE(4);if(c!==t.owner||u!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(s!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return s}function ri(e,r,t,n){let o=Ke(r),i=Ge(r);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||K(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=K(e,o[0],"closeAccount source"),c=K(e,o[1],"closeAccount destination"),u=K(e,o[2],"closeAccount authority");if(a!==n||c!==t.owner||u!==t.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function ni(e,r,t,n,o,i,a){let c=Ft(r.owner,r.artifact.inputMint,a);if(o.userSourceTokenAccount!==c)throw new Error("envelope: Jupiter source token account is not owner ATA");let u=G(t.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(u<$o)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let s=new Map,d=0n,l=!1,f=!1;for(let m of e.instructions){if(m===n)continue;let p=zo(e,m);if(p===Po)Zo(m,t);else if(p===Or){let{ata:g,debit:h}=ei(e,m,r,r.artifact,a,u);s.set(g,h)}else if(p===Rt)d+=ti(e,m,r,c,i);else if(p===a){let g=ri(e,m,r,c);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[...s.values()].reduce((m,p)=>m+p,0n)}function oi(e){let r;try{r=Bo().decode(Mo(e.messageBase64,"Solana message"))}catch(t){throw new Error(`envelope: invalid Solana message: ${t?.message||t}`)}if(r.version!=="legacy"&&Array.isArray(r.addressTableLookups)&&r.addressTableLookups.length)throw new Error("envelope: unresolved Solana address tables refused");return r}function ii(e,r,t){if(e.header.numSignerAccounts!==1||Q(e.staticAccounts[0])!==r.owner||!le(r.owner,t.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=Q(e.staticAccounts[o.programAddressIndex]);if(!i||!le(i,t.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function ai(e,r,t){let n=G(t.lamportsPerSignature,"lamportsPerSignature");if(n<Fo)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=t.maxLamportsPerSignature===void 0?n:G(t.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),a=i*n,c=i*o;if(r.exactFeeLamports!==void 0){let s=G(r.exactFeeLamports,"exactFeeLamports");if(s<a)throw new Error("policy: Solana exact fee below the base signature fee");if(s>c)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let u=c;if(u>G(t.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return u}function si(e,r,t,n){let o=0n,i=!1;for(let a of e.instructions){if(Q(e.staticAccounts[a.programAddressIndex])!==Rt)throw new Error("envelope: unsupported Solana program decoder");let u=a.accountIndices||[];if(u.length!==2||Q(e.staticAccounts[u[0]])!==r.owner)throw new Error("envelope: Solana transfer owner mismatch");let s=Q(e.staticAccounts[u[1]]);if(s!==r.destination||!le(s,t.destinations))throw new Error("envelope: Solana destination mismatch");let d=Buffer.from(a.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>G(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function ci(e,r,t,n){let o=r.artifact;if(o.provider!=="jupiter")throw new Error("envelope: Solana swap provider must be jupiter");if(o.inputMint!==Ro)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==r.destination||!le(o.outputMint,t.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Do(t);if(!le(o.inputMint,i)||!le(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=G(o.inAmount,"inAmount"),c=G(o.outAmount,"outAmount"),u=G(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>G(t.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>G(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(c<=0n||u<=0n||u>c)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(r.slippageBps))throw new Error("policy: Solana slippage mismatch");let s=Q(o.jupiterProgram);if(!s||!le(s,t.programs)||!n.includes(s))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(v=>Q(e.staticAccounts[v.programAddressIndex])===s);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=d[0],f=Xo(l.data,t);if(f.instruction==="shared_accounts_route"){let v=Array.isArray(t.jupiterSharedRouteIds)?t.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(!Bt(t.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(f.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(f.inAmount!==a)throw new Error("envelope: Jupiter route in_amount mismatch");if(f.quotedOutAmount!==c)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(u!==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=Qo(e,l,f),g=Ke(l),h=f.instruction==="shared_accounts_route"?2:1;if(!Lr(e,g[h]))throw new Error("envelope: Jupiter transfer authority must be signer");if(p.program!==s)throw new Error("envelope: Jupiter program account mismatch");if(p.userTransferAuthority!==r.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 w=Array.isArray(t.tokenPrograms)&&t.tokenPrograms.length?t.tokenPrograms:[Nr];if(!le(p.tokenProgram,w))throw new Error("policy: Solana token program not allowed");let b=Ft(r.owner,o.outputMint,p.tokenProgram);if(p.userDestinationTokenAccount!==b)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=Tr(p.destinationTokenAccount,s);if(E&&E!==b)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(Tr(p.platformFeeAccount,s))throw new Error("policy: Jupiter platform fee account not allowed");if(!Bt(t.jupiterRouteAccountHashes,"Jupiter route account hash").includes(vr(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let S=at(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,vr(e,l)].join(`
3
- `)));if(!Bt(t.jupiterRouteReviewHashes,"Jupiter route review hash").includes(S))throw new Error("policy: Jupiter route review hash not allowed");let I=ni(e,r,t,l,p,a,p.tokenProgram),T=a+I;if(T>G(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:T,programs:n}}function $t(e,r){if(e.action!=="transfer"&&e.action!=="swap")throw new Error("envelope: Solana decoder requires transfer or swap action");let t=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(t||{}).some(u=>!n.includes(u)))throw new Error("envelope: unexpected Solana artifact field");if(!le(t.cluster,r.chains))throw new Error("policy: chain not allowed");let o=oi(t),i=ii(o,e,r),a=e.action==="transfer"?si(o,e,r,i):ci(o,e,r,i),c=ai(o,t,r);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+c).toString(),fee:c.toString(),programs:Object.freeze(a.programs)})}function _t(e,r){let{unit:t,value:n,notional:o,fee:i}=$t(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}var Lc=64*1024;var ui=1e8;function qt(e){if(typeof e!="string"||!/^#(?:0|[1-9]\d*)$/.test(e))return null;let r=Number(e.slice(1));if(!Number.isSafeInteger(r)||r<0)return null;let t=r%10;if(t!==0&&t!==1)return null;let n=Math.floor(r/10),o=ui+r;return Number.isSafeInteger(o)?{encoding:r,outcome:n,side:t,coin:`#${r}`,assetId:o}:null}var li=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),di=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),fi=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"}),pi=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"}),me=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`hl: bounded ${r} required`);return e};function mi(e,r){let t=e.toString().padStart(r+1,"0");if(r===0)return t;let n=t.slice(0,-r),o=t.slice(-r).replace(/0+$/,"");return o?`${n}.${o}`:n}function Cr(e,r){let t=P(e,`hl: ${r}`);if(!/^\d+(?:\.\d+)?$/.test(t))throw new Error(`hl: ${r} must be a positive decimal`);let[n,o=""]=t.split("."),i=BigInt(n+o);if(i<=0n)throw new Error(`hl: ${r} must be positive`);return{raw:i,decimals:o.length}}function oe(e,r){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: ${r} must be finite JSON`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(n=>oe(n,r)).join(",")}]`;if(!e||typeof e!="object")throw new Error(`hl: ${r} must be structured JSON`);return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${oe(e[n],r)}`).join(",")}}`}function wi(e){if(typeof e.orderType!="string"||!e.orderType)throw new Error("hl: order type must be a string");let r=e.orderType,t=e.orderWire;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("hl: declared order wire required");if(r==="limit"){let i=t.limit?.tif;if(!["Gtc","Ioc","Alo"].includes(i)||oe(t,"declared order type")!==oe({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(r==="market"){if(oe(t,"declared order type")!==oe({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"}}[r];if(!n)throw new Error("hl: unsupported declared order type");let o=t.trigger?.triggerPx;if(o==null||oe(t,"declared order type")!==oe({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 hi(e,r,t){let n=Cr(e.s,"signed size"),o=Cr(e.p,"signed price"),i=n.decimals+o.decimals,a=n.raw*o.raw,c=q(r.notionalUsd,i,"hl: notionalUsd");if(c<=0n||a!==c)throw new Error("hl: signed notional must match");let u=q(t.maxNotionalUsd,i,"hl: maxNotionalUsd");if(a>u)throw new Error("hl: notional exceeds cap")}function gi(e,r){let t=e.action.builder;if(t==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("hl: signed order builder must be structured");let n=me(t.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(W(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(r.hlBuilders)?r.hlBuilders.map(c=>String(c).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=ue(t.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let a=q(r.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>a)throw new Error("hl: order builder fee exceeds cap")}function Br(e,r,t){if(!Number.isSafeInteger(e.a)||e.a!==t)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(r.side==="buy"))throw new Error("hl: signed side must match exactly");if(P(e.s,"hl: signed size")!==P(r.size,"hl: size"))throw new Error("hl: signed size must match");if(P(e.p,"hl: signed price")!==P(r.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof r.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==r.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(oe(e.t,"signed order type")!==oe(r.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(r.clientOrderId==null){if(n)throw new Error("hl: undeclared signed client order id")}else if(!n||typeof e.c!="string"||e.c!==r.clientOrderId)throw new Error("hl: signed client order id must match")}function Pr(e,r,t,n,o){if(!Number.isSafeInteger(e.a)||e.a!==t)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(r.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(P(e.s,"hl: bracket protection size")!==P(r.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(P(e.p,"hl: bracket protection price")!==P(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(P(i.triggerPx,"hl: triggerPx")!==P(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function yi(e){let r=String(e||"").replace(/\/$/,"");if(!li.has(r))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return r}function Mt(e){return qt(e)!=null}function Ei(e,r){let t=String(e||""),n=Array.isArray(r.coins)?r.coins.map(String):[];if(Mt(t)){if(r.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(n.includes(t)||n.includes("#*")||n.includes("*")||n.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(n.length&&!n.includes(t)&&!n.includes("*"))throw new Error("hl: coin not allowed");return!0}function bi(e,r,t){let n=Array.isArray(t.hlMarkets)?t.hlMarkets:[];if(n.length){if(!n.some(a=>{if(typeof a=="string"){let[c,u]=String(a).split(":");return c===e&&Number(u)===r}return String(a?.coin)===e&&Number(a?.assetId)===r}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(Mt(e)){let i=Array.isArray(t.coins)?t.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(t.coins)?t.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function we(e,r){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let t=e.artifact;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("hl: structured artifact required");let n=me(t.kind,"kind",48),o=fi[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=yi(t.submitTo);if(Object.prototype.hasOwnProperty.call(t,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(t,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let a=Number(t.nonce);if(!Number.isSafeInteger(a)||a<=0)throw new Error("hl: nonce must be a positive integer");if(!t.action||typeof t.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(t.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(t.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(t.action.type!==pi[n])throw new Error("hl: action type must match kind");let c=t.notionalUsd??0;if(di.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let u=me(t.coin,"coin",64),s=t.assetId??t.assetIndex;if(!Number.isSafeInteger(s)||s<0)throw new Error("hl: assetId required");if(n==="hip4-order"||s>=1e8){let d=qt(u);if(!d||d.coin!==u)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==s)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(Ei(u,r),bi(u,s,r),n==="hip4-order"&&!Mt(u))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(t.side!=="buy"&&t.side!=="sell")throw new Error("hl: side must be buy or sell");if(t.action.type!=="order"||!Array.isArray(t.action.orders))throw new Error("hl: signed orders are required");wi(t);let d=t.action.orders;if(n==="perp-bracket"){let l=t.takeProfitPx,f=t.stopLossPx,m=1+(l==null?0:1)+(f==null?0:1);if(m<2||d.length!==m||t.grouping!=="normalTpsl"||t.action.grouping!==t.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");Br(d[0],t,s);let p=1;l!=null&&Pr(d[p++],t,s,l,"tp"),f!=null&&Pr(d[p],t,s,f,"sl")}else{if(d.length!==1)throw new Error("hl: exactly one signed order is required");if(t.grouping!=="na"||t.action.grouping!==t.grouping)throw new Error("hl: signed grouping must match declared grouping");Br(d[0],t,s)}hi(d[0],t,r),gi(t,r),c=P(t.notionalUsd,"hl: notionalUsd")}if(n==="perp-leverage"){let d=t.leverage;if(!Number.isSafeInteger(d)||d<1)throw new Error("hl: leverage must be a positive integer");let l=r.maxLeverage==null?50:r.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=t.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!==s)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(t.orderId)||t.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(d[0].o)||d[0].o!==t.orderId)throw new Error("hl: signed cancel order id must match")}if(n==="perp-leverage"){if(!Number.isSafeInteger(t.action.asset)||t.action.asset!==s)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(t.action.leverage)||t.action.leverage!==t.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(t.marginMode))throw new Error("hl: declared margin mode required");let d=t.marginMode==="cross";if(typeof t.action.isCross!="boolean"||t.action.isCross!==d)throw new Error("hl: signed isCross must match declared margin mode")}if(n==="perp-isolated-margin"){if(!Number.isSafeInteger(t.action.asset)||t.action.asset!==s)throw new Error("hl: signed margin asset must match assetId");let d=me(t.usd,"margin usd",64),l=q(d,6,"hl: margin usd");if(ue(t.action.ntli,"hl: signed margin ntli")!==l)throw new Error("hl: signed margin amount must match usd");if(typeof t.isBuy!="boolean"||t.action.isBuy!==t.isBuy)throw new Error("hl: signed margin isBuy must match");let m=q(r.maxNotionalUsd,6,"hl: maxNotionalUsd"),p=l<0n?-l:l;if(p>m)throw new Error("hl: margin notional exceeds cap");c=mi(p,6)}}if(n==="builder-fee-approval"){let u=me(t.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(u))throw new Error("hl: builder address required");if(me(t.action.builder,"signed builder",42).toLowerCase()!==u)throw new Error("hl: signed builder must match");if(!(Array.isArray(r.hlBuilders)?r.hlBuilders.map(p=>String(p).toLowerCase()):[]).includes(u))throw new Error("hl: builder not allowed");let d=me(t.maxFeeRate,"maxFeeRate",32);if(me(t.action.maxFeeRate,"signed maxFeeRate",32)!==d)throw new Error("hl: signed builder fee must match");if(!/^\d+(?:\.\d+)?%$/.test(d))throw new Error("hl: builder fee rate must be a percent");let l=q(d.slice(0,-1),12,"hl: builder fee percent"),f=q(r.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(f<0n||l*100n>f)throw new Error("hl: builder fee exceeds cap");if(Number(t.action.nonce)!==a)throw new Error("hl: signed builder nonce must match");let m=i.includes("testnet")?"Testnet":"Mainnet";if(t.hyperliquidChain!==m||t.action.hyperliquidChain!==t.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(t.signatureChainId!=="0x66eee"||t.action.signatureChainId!==t.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 u=n==="hype-undelegate";if(typeof t.action.isUndelegate!="boolean"||t.action.isUndelegate!==u)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(r.maxHypeWei!=null&&BigInt(String(t.action.wei??t.caps?.amountHype??"0"))>BigInt(r.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(c??t.action.wei??0),notional:String(c??0),fee:"0",kind:n,actionType:t.action.type,amount:String(t.action.wei??c??0),coin:t.coin||null,submitTo:i})}import{createHmac as xi}from"node:crypto";var Le="0x"+"00".repeat(32);function Dt(e={}){let r=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,t=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(!r||!t||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(r),secret:String(t),passphrase:String(n)}}function Rr({creds:e,address:r,method:t,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(r||"")))throw new Error("poly: L2 address required");let a=String(i??Math.floor(Date.now()/1e3)),c=String(t||"").toUpperCase(),u=String(n||"");if(c!=="POST"||u!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let s=a+c+u+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),f=xi("sha256",l).update(s).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:r,POLY_SIGNATURE:f,POLY_TIMESTAMP:a,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function Si(e,r){if(e.side!==0&&e.side!==1)throw new Error("poly: side must be BUY or SELL");let t=e.side===0?"BUY":"SELL";if(r&&r!==t)throw new Error("poly: side mismatch");return t}function Fr(e,r){let t=BigInt(P(e.makerAmount,"poly: makerAmount")),n=BigInt(P(e.takerAmount,"poly: takerAmount"));if(t<=0n||n<=0n)throw new Error("poly: order amounts must be positive integer micro-units");return Number(r==="BUY"?t:n)/1e6}function Ai(e){let r=typeof e=="bigint"?e.toString(10):P(e,"poly: salt");if(!/^[1-9][0-9]*$/.test(r))throw new Error("poly: salt must be a positive integer");let t=BigInt(r);if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("poly: salt exceeds safe integer");return Number(t)}function $r({message:e,side:r,signature:t,orderType:n="GTC",apiKey:o}={}){if(!e||typeof e!="object")throw new Error("poly: CLOB v2 message required");if(!String(t||"").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=Si(e,r);if(W(e.metadata||Le,"poly: metadata").toLowerCase()!==Le)throw new Error("poly: metadata must be zero");if(W(e.builder||Le,"poly: builder").toLowerCase()!==Le)throw new Error("poly: builder must be zero");let a=Ai(e.salt);return{deferExec:!1,order:{builder:Le,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:Le,salt:String(a),side:i,signature:t,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var vi=new Set(["https://clob.polymarket.com/order"]),Ye=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Vc=Object.freeze(Ye.map(e=>e[0])),Ii=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),Ti="0xe111180000d2663c0091e4f400237545b87b996b",ki="0xe2222d279d744050d28e00520010520000310f59",_r=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`poly: bounded ${r} required`);return e};function qr(e){let r=String(e||"").replace(/\/$/,"");if(!vi.has(r))throw new Error("poly: submitTo must be the official Polymarket CLOB");return r}function Mr(e){let r=W(e,"poly: exchange").toLowerCase();if(!Ii.has(r))throw new Error("poly: verifyingContract must be an official CTF Exchange");return r}function he(e,r){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let t=e.artifact;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("poly: structured artifact required");let n=_r(t.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(W(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(qr(t.submitTo),t.chainId!==137)throw new Error("poly: chainId must be Polygon 137");let o=t.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(Mr(o.verifyingContract),Mr(t.exchange),W(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==W(t.exchange,"poly: exchange").toLowerCase())throw new Error("poly: exchange/domain mismatch");if(typeof t.negRisk!="boolean")throw new Error("poly: negRisk must be a boolean");let i=t.negRisk?ki:Ti;if(W(t.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let a=t.message||t.value;if(!a||typeof a!="object")throw new Error("poly: signed order message required");let c=t.types?.Order;if(!Array.isArray(c)||c.length!==Ye.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let h=0;h<Ye.length;h+=1)if(c[h]?.name!==Ye[h][0]||c[h]?.type!==Ye[h][1])throw new Error("poly: EIP-712 Order type must be official CLOB v2");if((t.orderType||"GTC")!=="GTC")throw new Error("poly: only GTC is public");let u=String(e.owner||"").toLowerCase();if(W(a.maker,"poly: maker").toLowerCase()!==u)throw new Error("poly: maker must equal owner");if(W(a.signer,"poly: signer").toLowerCase()!==u)throw new Error("poly: signer must equal owner");if(a.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof a.builder!="string"||a.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(a.side!==0&&a.side!==1)throw new Error("poly: side must be BUY or SELL");let s=_r(t.tokenId,"tokenId",80);if(W(a.tokenId,"poly: tokenId")!==s)throw new Error("poly: tokenId mismatch");let d=Array.isArray(r.polyTokens)?r.polyTokens.map(String):[];if(d.length&&!d.includes(s)&&!d.includes("*"))throw new Error("poly: tokenId not allowed");let l=Number(a.side)===0?"BUY":"SELL";if(t.side&&t.side!==l)throw new Error("poly: side mismatch");let f=Fr(a,l),m=q(t.notionalUsdc,6,"poly: notionalUsdc"),p=q(f,6,"poly: computed notional");if(m!==p)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let g=r.maxNotionalUsd??r.maxNotionalUsdc;if(g!=null){let h=q(g,6,"poly: maxNotionalUsd");if(p>h)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:String(f),notional:String(f),fee:"0",kind:n,tokenId:s,side:l,submitTo:qr(t.submitTo)})}var Ni=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),Ut=14,Dr=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`lighter: bounded ${r} required`);return e};function Ce(e,r,t){if(!Number.isSafeInteger(e)||e!==r)throw new Error(`lighter: ${t} must be exact numeric ${r}`)}function jt(e){let r=String(e||"").replace(/\/$/,"");if(!Ni.has(r))throw new Error("lighter: submitTo must be the official Lighter sendTx");return r}function ge(e,r={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let t=e.artifact;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("lighter: structured artifact required");let n=Dr(t.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=jt(t.submitTo),i=t.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=Number(ue(t.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: accountIndex required");let c=Number(ue(t.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(c)||c<0)throw new Error("lighter: clientOrderIndex required");Ce(t.orderType,0,"orderType"),Ce(t.timeInForce,1,"timeInForce"),Ce(t.reduceOnly,0,"reduceOnly"),Ce(t.triggerPrice,0,"triggerPrice"),Ce(t.orderExpiry,-1,"orderExpiry");let u=Dr(t.symbol||t.coin,"symbol",32),s=Array.isArray(r.lighterMarkets)?r.lighterMarkets.map(String):[];if(s.length&&!s.includes(u)&&!s.includes(String(i))&&!s.includes("*"))throw new Error("lighter: market not allowed");if(t.side!=="buy"&&t.side!=="sell")throw new Error("lighter: side must be buy or sell");let d=Tt(t.baseAmount,"lighter: baseAmount"),l=Tt(t.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(t.sizeDecimals??0),g=Number(t.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 h=p+g,w=d*l,b=q(t.notionalUsd,h,"lighter: notionalUsd");if(b<=0n)throw new Error("lighter: notionalUsd required");if(w!==b)throw new Error("lighter: notionalUsd must match size and price");let E=q(r.maxNotionalUsd??Number.MAX_SAFE_INTEGER,h,"lighter: maxNotionalUsd");if(w>E)throw new Error("lighter: notional exceeds cap");let S=P(t.notionalUsd,"lighter: notionalUsd");return Ce(t.txType,Ut,"txType"),Object.freeze({unit:"usd",value:String(S),notional:String(S),fee:"0",kind:n,symbol:u,marketIndex:i,side:t.side,baseAmount:f,price:m,submitTo:o,actionType:"create-order",amount:String(S)})}var zr=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var Wt=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}),Oi=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Vr=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"}}),Li=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),st=new Jr(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Ur=new Jr(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),Ci=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 Qe=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`envelope: bounded ${r} required`);return e},A=(e,r)=>{try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`envelope: ${r} must be a non-negative integer`)}},jr=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},Bi=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${r} allowlist is empty`);return e},_=(e,r,t)=>{if(!Bi(r,t).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${t} not allowed`)},Xe=(e,r,t)=>{Array.isArray(r)&&r.length&&_(e,r,t)},O=(e,r)=>{let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(t))throw new Error(`envelope: ${r} must be a 20-byte address`);return t},ve=e=>String(e||"0x").slice(0,10).toLowerCase(),Gr=e=>A(e.gasLimit,"gasLimit")*A(e.maxFeePerGas??e.gasPrice,"feePerGas")+A(e.l1FeeWei??0,"l1FeeWei")+A(e.operatorFeeWei??0,"operatorFeeWei");function Be(e,r,t,{dynamicTail:n=!1}={}){let o=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(o)||o.length<10+r*64)throw new Error(`envelope: malformed ${t} calldata`);if(!n&&o.length!==10+r*64)throw new Error(`envelope: malformed ${t} calldata`);return{hex:o,word:i=>o.slice(10+i*64,10+(i+1)*64)}}function D(e,r){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${r} address`);return`0x${e.slice(24)}`}function Z(e,r){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${r} integer`)}}function Pi(e){if(ve(e)!=="0x095ea7b3")return null;let r=Be(e,2,"approval");return{kind:"approval",spender:D(r.word(0),"approval spender"),amount:Z(r.word(1),"approval amount")}}function Kr(e,r){let t=r==="router02-exact-input-single"?7:8,n=Be(e,t,"Uniswap v3 exactInputSingle"),o=t===7?4:5;return{kind:"action",action:"swap",inputToken:D(n.word(0),"input token"),outputToken:D(n.word(1),"output token"),recipient:D(n.word(3),"recipient"),amountIn:Z(n.word(o),"amountIn"),minimumOut:Z(n.word(o+1),"amountOutMinimum")}}function Ri(e){let r=Be(e,12,"Across depositV3",{dynamicTail:!0}),t=Z(r.word(11),"message offset");if(t!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let n=10+Number(t)*2;if(r.hex.length<n+64)throw new Error("envelope: malformed Across depositV3 message");let o=Number(BigInt(`0x${r.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(r.hex.length!==n+64+i)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:D(r.word(0),"depositor"),recipient:D(r.word(1),"recipient"),inputToken:D(r.word(2),"input token"),outputToken:D(r.word(3),"output token"),amountIn:Z(r.word(4),"inputAmount"),minimumOut:Z(r.word(5),"outputAmount"),destinationChainId:Z(r.word(6),"destinationChainId")}}function Fi(e){let r=String(e||"").replace(/^0x/i,"").toLowerCase();if(r.length<86||r.length%2!==0)throw new Error("envelope: malformed Uniswap path");let t=`0x${r.slice(0,40)}`,n=`0x${r.slice(r.length-40)}`;if(!/^0x[0-9a-f]{40}$/.test(t)||!/^0x[0-9a-f]{40}$/.test(n))throw new Error("envelope: malformed Uniswap path tokens");return{inputToken:t,outputToken:n}}function Wr(e,{hasDeadline:r}){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<74)throw new Error("envelope: malformed exactInput calldata");let n=[];for(let h=10;h+64<=t.length;h+=64)n.push(t.slice(h,h+64));let o=(h,w)=>{if(!n[h])throw new Error(`envelope: malformed ${w}`);return BigInt(`0x${n[h]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let a=i/32,c=Number(o(a,"path offset")),u=n[a+1],s=o(a+(r?3:2),"amountIn"),d=o(a+(r?4:3),"amountOutMinimum"),l=a+c/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let f=Number(o(l,"path length")),m=t.slice(10+(l+1)*64,10+(l+1)*64+f*2),{inputToken:p,outputToken:g}=Fi(`0x${m}`);return{kind:"action",action:"swap",inputToken:p,outputToken:g,recipient:D(u,"recipient"),amountIn:s,minimumOut:d}}function $i(e){let r=Be(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:D(r.word(0),"input token"),outputToken:D(r.word(1),"output token"),recipient:D(r.word(3),"recipient"),amountIn:Z(r.word(5),"amountIn"),minimumOut:Z(r.word(6),"amountOutMinimum")}}function _i(e){let r=String(e||"").toLowerCase();if(!r.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let t=[];for(let f=10;f+64<=r.length;f+=64)t.push(r.slice(f,f+64));let n=Number(BigInt(`0x${t[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${t[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let a=Number(BigInt(`0x${t[o+1]}`)),c=o+1+a/32,u=Number(BigInt(`0x${t[c]}`)),d=`0x${r.slice(10+(c+1)*64,10+(c+1)*64+u*2)}`,l=ve(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Kr(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function qi(e,r){let t=ve(e),n=Vr[t];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(r).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{...Kr(e,n.layout),selector:t,provider:n.provider};if(n.layout==="exact-input-deadline")return{...Wr(e,{hasDeadline:!0}),selector:t,provider:n.provider};if(n.layout==="exact-input")return{...Wr(e,{hasDeadline:!1}),selector:t,provider:n.provider};if(n.layout==="multicall-deadline")return{..._i(e),selector:t,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...$i(e),selector:t,provider:n.provider};if(n.action==="bridge")return{...Ri(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Mi(e){let r=Be(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:D(r.word(0),"mint NFT contract"),feeRecipient:D(r.word(1),"mint fee recipient"),recipient:D(r.word(2),"mint recipient"),quantity:Z(r.word(3),"mint quantity")}}function Di(e){let r;try{r=Ur.decodeFunctionData("mintAllowList",e)}catch{throw new Error("envelope: malformed SeaDrop mintAllowList calldata")}let t=r[4],n=[...r[5]].map(String);if(n.length<1||n.length>64||n.some(u=>!/^0x[0-9a-fA-F]{64}$/.test(u)))throw new Error("envelope: bounded canonical SeaDrop allowlist proof required");if(Ur.encodeFunctionData("mintAllowList",[r[0],r[1],r[2],r[3],t,n]).toLowerCase()!==String(e).toLowerCase())throw new Error("envelope: SeaDrop allowlist calldata must be canonical");let i=BigInt(t.startTime),a=BigInt(t.endTime);if(a<=i)throw new Error("envelope: SeaDrop allowlist stage time range is invalid");let c=BigInt(r[3]);if(BigInt(t.maxTotalMintableByWallet)<c)throw new Error("envelope: SeaDrop allowlist wallet cap is below quantity");return{kind:"mint",action:"mint",mintType:"allowlist",contract:O(r[0],"mint NFT contract"),feeRecipient:O(r[1],"mint fee recipient"),recipient:O(r[2],"mint recipient"),quantity:c,mintPrice:BigInt(t.mintPrice),startTime:i,endTime:a,dropStageIndex:BigInt(t.dropStageIndex),proof:n}}function Ui(e,r){let t=ve(e);if(String(r).toLowerCase()==="nft-mint")return ji(e);let n=Li[t];if(!n)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(String(r).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed NFT selector");if(n.layout==="seadrop-mint-public")return{...Mi(e),selector:t,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...Di(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function ji(e){let r=ve(e);if(r==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let t=Ci[r];if(!t)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(t.layout==="mint-no-args")return{kind:"mint",action:"mint",selector:r,provider:"nft-mint",quantity:1n};if(t.layout==="mint-quantity"){let n=Be(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:r,provider:"nft-mint",quantity:Z(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function ct(e){let r=e?.artifact;if(Array.isArray(r?.transactions))return r.transactions;if(r?.transaction&&typeof r.transaction=="object")return[r.transaction];if(r?.data)return[r];throw new Error("envelope: ordered EVM transaction batch required")}function Yr(e,r,t,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=O(e.owner,"owner"),c=e.artifact,u=Number(c?.chainId??ct(e)[0]?.chainId);if(!Number.isSafeInteger(u)||u<=0)throw new Error("envelope: explicit batch chainId required");if(_(u,r.chains,"chain"),c?.owner!==void 0&&O(c.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let s=ct(e);if(!s.length||s.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,l=0n,f=0n;for(let m of s){if(!m||typeof m!="object"||Array.isArray(m))throw new Error("envelope: structured EVM transaction required");if(Number(m.chainId)!==u)throw new Error("envelope: every batch leg must use the same chain");if(O(m.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(_(ve(m.data),r.selectors,"selector"),d+=A(m.value??0,"value"),l+=A(m.gasLimit,"gasLimit"),f+=Gr(m),re(u)&&(m.l1FeeWei===void 0||m.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>A(r.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>A(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(f>A(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:s,chainId:u,owner:a,totalValue:d,totalGas:l,totalFee:f}}function Xr(e,r,{nowMs:t=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=Qe(e.provider,"provider",64).toLowerCase();_(i,r.providers,"provider");let a=Yr(e,r,o,{nowMs:t}),c=[],u=-1;for(let p=0;p<a.transactions.length;p++){let g=a.transactions[p],h=Pi(g.data),w;if(h){if(u!==-1)throw new Error("envelope: approval must be before action");if(A(g.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let S=O(g.to,"approval token");if(_(S,r.tokens,"token"),_(h.spender,r.spenders,"spender"),h.amount>A(r.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");w={...h,token:S,index:p}}else{if(u!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");_(g.to,r.destinations,"destination"),w={...qi(g.data,i),target:O(g.to,"action target"),index:p},u=p}let b=A(g.value??0,"value"),E=A(g.gasLimit,"gasLimit");c.push({...w,value:b,gas:E,fee:Gr(g)})}if(u<0)throw new Error("envelope: reviewed swap/bridge action required");let s=c[u],d=o==="evm-swap"?"swap":"bridge";if(s.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if(O(e.destination,"destination")!==s.target)throw new Error("envelope: destination must equal decoded action target");if(s.recipient!==a.owner)throw new Error("envelope: decoded recipient must equal owner");if(s.depositor&&s.depositor!==a.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(_(s.inputToken,r.tokens,"input token"),_(s.outputToken,r.tokens,"output token"),s.amountIn<=0n||s.amountIn>A(r.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(s.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(It(e.autoSlippage,{nowMs:t,chainId:a.chainId,venue:i,tx:a.transactions[u],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(s.minimumOut!==A(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(s.action==="bridge"&&A(e.toChainId,"toChainId")!==s.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=c.filter(p=>p.kind==="approval");if(!new Set([...Oi,...Array.isArray(r.nativeInputTokens)?r.nativeInputTokens.map(p=>String(p).toLowerCase()):[]]).has(s.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(s.value!==s.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let m=Object.freeze({quoteAmountOut:A(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:A(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...a,decoded:c,action:s,provider:i,authenticatedQuote:m}}function Wi(e,r,{nowMs:t}){let n=e.anvilAttestation,o=e.artifact?.anvilAttestation;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("envelope: Anvil attestation is required");if(!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: Anvil attestation artifact mismatch");if(Number(n.version)!==1||n.source!=="anvil-snapshot-rpc-reviewed-runtime")throw new Error("envelope: unsupported Anvil attestation");if(Number(n.chainId)!==4663)throw new Error("envelope: Anvil attestation chain mismatch");let i=O(e.destination,"Anvil market"),a=O(e.contract,"NFT contract"),c=O(e.paymentToken,"payment token");if(O(n.market,"attested Anvil market")!==i)throw new Error("envelope: Anvil attestation market mismatch");if(O(n.collection,"attested NFT collection")!==a)throw new Error("envelope: Anvil attestation collection mismatch");if(O(n.paymentToken,"attested payment token")!==c)throw new Error("envelope: Anvil attestation payment token mismatch");let u=Number(e.paymentTokenDecimals??e.artifact?.paymentTokenDecimals);if(!Number.isSafeInteger(u)||u<0||u>255||Number(n.paymentTokenDecimals)!==u)throw new Error("envelope: Anvil payment token decimals mismatch");let s=A(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei").toString();if(A(n.nativeSwapFeeWei,"attested nativeSwapFeeWei").toString()!==s)throw new Error("envelope: Anvil attestation native swap fee mismatch");let d=Number(n.snapshotFetchedAtMs),l=Number(n.snapshotExpiresAtMs);if(!Number.isFinite(d)||!Number.isFinite(l)||d>t||l<=t||l<=d)throw new Error("envelope: Anvil snapshot attestation is stale");let f=A(n.blockNumber,"attested blockNumber");if(f<=0n||!/^0x[0-9a-f]{64}$/.test(String(n.blockHash||"").toLowerCase()))throw new Error("envelope: Anvil block attestation is invalid");let m=String(n.runtimeCodeHash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(m))throw new Error("envelope: Anvil runtime code hash is invalid");let p=Object.entries(r.anvilRuntimeCodeHashes||{}).find(([h])=>h.toLowerCase()===i)?.[1];if(!p||String(p).toLowerCase()!==m)throw new Error("policy: Anvil runtime code hash is not reviewed");let g=Object.entries(r.nftPaymentTokenCaps||{}).find(([h])=>h.toLowerCase()===c)?.[1];if(!g||Number(g.decimals)!==u)throw new Error("policy: Anvil payment token decimals are not reviewed");return Object.freeze({...n,market:i,collection:a,paymentToken:c,paymentTokenDecimals:u,runtimeCodeHash:m,blockNumber:f})}function Hr(e,r){let t=e.artifact,n=e.anvilQuote,o=t?.anvilQuote;if(!n||typeof n!="object"||Array.isArray(n)||!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: exact Anvil quote artifact mismatch");if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("envelope: exact Anvil quote confirmation required");let i=r==="buy"?[[n.totalCostRaw,"anvilQuote.totalCostRaw"],[e.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw"],[t?.maxPaymentTokenAmountRaw,"artifact maxPaymentTokenAmountRaw"],[e.exactQuoteTotalCostRaw,"exactQuoteTotalCostRaw"],[t?.exactQuoteTotalCostRaw,"artifact exactQuoteTotalCostRaw"],[e.preconditions?.confirmedTotalCostRaw,"confirmedTotalCostRaw"]]:[[n.netPayoutRaw,"anvilQuote.netPayoutRaw"],[e.minPayoutRaw,"minPayoutRaw"],[t?.minPayoutRaw,"artifact minPayoutRaw"],[e.exactQuoteNetPayoutRaw,"exactQuoteNetPayoutRaw"],[t?.exactQuoteNetPayoutRaw,"artifact exactQuoteNetPayoutRaw"],[e.preconditions?.confirmedNetPayoutRaw,"confirmedNetPayoutRaw"]],a=A(i[0][0],i[0][1]);for(let[c,u]of i.slice(1))if(A(c,u)!==a)throw new Error(`envelope: Anvil ${r} exact settlement limit mismatch`);return a}function Qr(e,r,{nowMs:t=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint or NFT action");let n=Qe(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Xe(n,r.providers,"provider");let o=Yr(e,r,"evm-nft",{nowMs:t});if(n==="anvil-nft"){if(e.action!=="nft")throw new Error("envelope: Anvil requires NFT action");if(o.chainId!==4663)throw new Error("envelope: Anvil requires chain 4663");if(r.confirmationMode!=="exact-human")throw new Error("policy: Anvil requires exact-human confirmation");if(o.transactions.length!==1)throw new Error("envelope: Anvil requires one atomic action with pre-existing approval");if(Number(e.slippageBps)!==0)throw new Error("envelope: Anvil exact limit requires zero slippageBps");let[m]=o.transactions,p=O(e.destination,"Anvil market");if(O(m.to,"Anvil action target")!==p)throw new Error("envelope: Anvil action target mismatch");_(p,r.destinations,"destination");let g=O(e.contract??e.artifact?.contract,"NFT contract");if(Xe(g,r.nftContracts,"NFT contract"),O(e.marketCollection??e.artifact?.marketCollection,"Anvil market collection")!==g)throw new Error("envelope: Anvil market collection mismatch");let w=O(e.paymentToken??e.artifact?.paymentToken,"payment token");Xe(w,r.erc20Tokens,"ERC20 token");let b=Wi(e,r,{nowMs:t}),E=A(e.tokenId??e.artifact?.tokenId,"tokenId"),S=A(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei");if(o.totalValue!==S||A(m.value??0,"Anvil action value")!==S)throw new Error("envelope: Anvil native swap fee mismatch");if(S>A(r.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"))throw new Error("policy: Anvil native swap fee exceeds cap");let I=Qe(e.nftAction,"nftAction",8).toLowerCase(),T;if(I==="buy"){let v=Hr(e,I),C=Object.entries(r.nftPaymentTokenCaps||{}).find(([fe])=>fe.toLowerCase()===w)?.[1];if(!C)throw new Error("policy: Anvil payment-token cap required");if(v>A(C.maxPerTradeRaw,"maxPerTradeRaw"))throw new Error("policy: Anvil payment amount exceeds cap");if(e.preconditions?.allowanceVerified!==!0||A(e.preconditions?.allowanceRaw,"allowanceRaw")<v)throw new Error("envelope: Anvil pre-existing allowance proof required");let F=st.decodeFunctionData("buySpecificNFT",m.data);if(st.encodeFunctionData("buySpecificNFT",[F[0],F[1]]).toLowerCase()!==String(m.data).toLowerCase())throw new Error("envelope: non-canonical Anvil buy calldata");if(BigInt(F[0])!==E)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(F[1])!==v)throw new Error("envelope: Anvil maxCost mismatch");T={kind:"nft",action:"buy",tokenId:E,maxPaymentTokenAmountRaw:v,target:p}}else if(I==="sell"){let v=e.preconditions||{},C=O(v.approvedAddress,"NFT approval address");if(v.nftApprovalVerified!==!0||C!==p&&v.approvedForAll!==!0)throw new Error("envelope: Anvil pre-existing NFT approval proof required");let F=Hr(e,I),z=st.decodeFunctionData("sellNFT",m.data);if(st.encodeFunctionData("sellNFT",[z[0],z[1]]).toLowerCase()!==String(m.data).toLowerCase())throw new Error("envelope: non-canonical Anvil sell calldata");if(BigInt(z[0])!==E)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(z[1])!==F)throw new Error("envelope: Anvil minPayout mismatch");T={kind:"nft",action:"sell",tokenId:E,minPayoutRaw:F,target:p}}else throw new Error("envelope: unsupported Anvil NFT action");return{...o,provider:n,nftAction:I,tokenId:E,paymentToken:w,paymentTokenDecimals:b.paymentTokenDecimals,anvilAttestation:b,decoded:[T]}}let i=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;if(i?.oraclePrepared===!0&&hr(i,{nowMs:t,providers:Array.isArray(r.providers)&&r.providers.length?r.providers:null,kinds:["nft-mint"],label:"local-signer"}),o.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let a=o.transactions[0],c=ve(a.data);_(c,r.selectors,"selector"),_(a.to,r.destinations,"destination");let u=Ui(a.data,n),s=O(e.contract??e.artifact?.contract,"NFT contract");if(Xe(s,r.nftContracts,"NFT contract"),(u.contract||O(a.to,"NFT contract"))!==s)throw new Error("envelope: mint calldata NFT contract mismatch");if(u.recipient&&u.recipient!==o.owner)throw new Error("envelope: mint calldata recipient mismatch");u.feeRecipient&&Xe(u.feeRecipient,r.nftFeeRecipients,"mint fee recipient");let l=A(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>A(r.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(u.quantity!==l)throw new Error("envelope: mint calldata quantity mismatch");let f=A(e.totalWei??e.artifact?.totalWei,"totalWei");if(o.totalValue!==f)throw new Error("envelope: mint value does not match declared totalWei");if(u.mintType==="allowlist"){let m=BigInt(Math.floor(t/1e3));if(u.startTime>m||u.endTime<=m)throw new Error("policy: SeaDrop allowlist stage is not open");if(u.mintPrice*l!==f)throw new Error("envelope: SeaDrop allowlist price does not match declared totalWei")}if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&A(e.priceWei??e.artifact.priceWei,"priceWei")*l!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>A(r.maxMintTotalWei??r.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...o,provider:n,decoded:[{...u,target:O(a.to,"mint target"),value:o.totalValue,gas:o.totalGas,fee:o.totalFee}]}}function Hi(e,{localsWaiver:r=!1}={}){if(!(e in Wt))throw new Error("fee: unknown action");return r?0:Wt[e]}function ut(e,r,{nowMs:t=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:a=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let c=Qe(e.surface,"surface",16);if(!zr.has(c))throw new Error("envelope: unsupported public surface");let u=Qe(e.action,"action",32);_(c,r.surfaces,"surface"),_(u,r.actions,"action"),_(e.owner,r.owners,"owner"),_(e.destination,r.destinations,"destination");let s=jr(r.maxTtlMs,"maxTtlMs"),d=jr(r.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=t||e.expiresAtMs-t>s)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(c==="evm-swap"||c==="evm-bridge")Xr(e,r,{nowMs:t,routeAttestationSecret:o});else if(c==="evm-nft")Qr(e,r,{nowMs:t});else if(c==="evm"){if(!["transfer","approve"].includes(u))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(u==="swap"||u==="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");ot({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},r,{nowMs:t,networkFees:i,requireNetworkFees:a});let p=String(l.data||"0x").toLowerCase(),g=A(l.value,"EVM value");if(p==="0x"){if(g===0n)throw new Error("envelope: native EVM transfer value required")}else if(te(p)){if(g!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else c==="btc"?Ct(e,r):c==="sol"?_t(e,r):c==="hl"?we(e,r):c==="poly"?he(e,r):c==="lighter"&&ge(e,r);let f=Number(e.fee?.oracleFeeBps)===0&&Wt[u]!==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=Hi(u,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==m)throw new Error("fee: final artifact fee mismatch");return!0}var Ht=Object.freeze([...zr]),su=Object.freeze({...Vr});function Jt(e,r){if(e.surface==="hl")return we(e,r);if(e.surface==="poly")return he(e,r);if(e.surface==="lighter")return ge(e,r);if(e.surface==="btc")return Ct(e,r);if(e.surface==="sol")return _t(e,r);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let t=Xr(e,r,{nowMs:Math.max(0,Number(e.expiresAtMs)-1),routeAttestationSecret:r.routeAttestationSecret}),n=t.totalValue.toString(),o=t.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(t.totalValue+t.totalFee).toString(),fee:o})}if(e.surface==="evm-nft"){let t=Qr(e,r,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=t.totalFee.toString();if(t.provider==="anvil-nft"&&t.nftAction==="buy"){let i=A(e.maxPaymentTokenAmountRaw??e.artifact?.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw").toString(),a=t.totalValue.toString(),c=t.totalFee,u=[{unit:`erc20:${t.paymentToken}`,value:i,notional:i,fee:"0"},{unit:"wei",value:a,notional:(t.totalValue+c).toString(),fee:c.toString()}].sort((s,d)=>s.unit<d.unit?-1:s.unit>d.unit?1:0);return Object.freeze({units:u})}let o=t.totalValue.toString();return Object.freeze({unit:"wei",value:o,notional:(t.totalValue+t.totalFee).toString(),fee:n})}if(String(e.surface).startsWith("evm")){let t=A(e.artifact?.value,"EVM value"),n=A(e.artifact?.gasLimit,"EVM gasLimit"),o=A(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+A(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+A(e.artifact?.operatorFeeWei??0,"EVM operatorFeeWei");return Object.freeze({unit:"wei",value:t.toString(),notional:(t+i).toString(),fee:i.toString()})}throw new Error("envelope: unsupported public surface")}function Zr(e={}){let r={};for(let t of Ht){let n=e[t];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${t} requires simulate, sign, and broadcast functions`);r[t]=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(r)}function lt(e,r){let t=e?.surface||"evm",n=r?.[t];if(!n)throw new Error(`adapter: ${t} is not configured on this self-host`);return n}import{createHash as sn}from"node:crypto";import{ed25519 as ta}from"@noble/curves/ed25519.js";import{base58 as dn}from"@scure/base";import{RawTx as Kt,SigHash as Ie,Transaction as Yt}from"@scure/btc-signer";import{Transaction as Xt,keccak256 as cn,verifyTypedData as un}from"ethers";import{encode as Ji}from"@msgpack/msgpack";import{keccak256 as zi,verifyTypedData as Vi}from"ethers";var Pe=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),zt=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function en(e){let r=BigInt(e);if(r<0n||r>=2n**64n)throw new Error("hl-l1: nonce must fit uint64");let t=Buffer.alloc(8);return t.writeBigUInt64BE(r),t}function Gi(e,r,{vaultAddress:t=null,expiresAfter:n=null}={}){let i=[Buffer.from(Ji(e)),en(r)];if(t){let a=String(t).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]),en(n)),zi(Buffer.concat(i))}function Vt(e,r,{isMainnet:t=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:t?"a":"b",connectionId:Gi(e,r,{vaultAddress:n,expiresAfter:o})}}function tn(e){let r=e?.typedData;if(r==null)return null;if(typeof r!="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 t=Vt(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(r.domain?.name!==Pe.name||String(r.domain?.version)!==Pe.version||Number(r.domain?.chainId)!==Pe.chainId||String(r.domain?.verifyingContract||"").toLowerCase()!==String(Pe.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(r.types?.Agent||[])!==JSON.stringify(zt.Agent))throw new Error("hl-l1: typedData types must be Hyperliquid Agent");if(r.message?.source!==t.source||String(r.message?.connectionId||"").toLowerCase()!==String(t.connectionId).toLowerCase())throw new Error("hl-l1: typedData message must hash the validated action");return t}async function rn({wallet:e,action:r,nonce:t,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let a=Vt(r,t,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(Pe,zt,a)}function nn({signature:e,action:r,nonce:t,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:a=null}){try{let c=Vt(r,t,{isMainnet:n,vaultAddress:i,expiresAfter:a}),u=Vi(Pe,zt,c,e);return String(u).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var Ki=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function Gt(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 r of e)Gt(r);return}for(let r of Object.values(e))Gt(r)}}}function Yi(e){if(typeof e=="string"){if(!e.startsWith("{"))throw new Error("lighter: official signed tx_info JSON required");let r=JSON.parse(e);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("lighter: official signed tx_info JSON required");return r}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("lighter: official signed tx_info JSON required");return Gt(e),JSON.parse(JSON.stringify(e))}function dt(e,r){let t=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^(0|[1-9][0-9]*)$/.test(t))throw new Error(`lighter: ${r} must be an integer`);let n=BigInt(t);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`lighter: ${r} exceeds safe integer`);return n}function Xi(e,r){let t=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^-?(0|[1-9][0-9]*)$/.test(t))throw new Error(`lighter: ${r} must be an integer`);let n=BigInt(t);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`lighter: ${r} exceeds safe integer`);return n}function on(e,r,{signed:t=!1}={}){if(typeof e!="number"||!Number.isSafeInteger(e)||!t&&e<0)throw new Error(`lighter: signed ${r} must be an exact numeric integer`);return e}function Fe(e,r,t,n={}){let o=r.filter(a=>e[a]!==void 0&&e[a]!==null);if(o.length===0)throw new Error(`lighter: ${t} required`);let i=o.map(a=>on(e[a],t,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${t}`);return i[0]}function Qi(e,r,t){let n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length===0)throw new Error(`lighter: ${t} required`);let o=n.map(i=>String(e[i]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${t}`);return e[n[0]]}function Re(e,r,t,n){let o=Fe(e,r,n);if(BigInt(o)!==dt(t,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Zi(e,r,t,n){let o=Fe(e,r,n,{signed:!0});if(BigInt(o)!==Xi(t,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function ea(e){let r={};for(let[t,n]of Ki.entries()){let o=n.filter(a=>e[a]!==void 0&&e[a]!==null);if(!o.length)continue;let i=o.map(a=>{let c=e[a];if(t<3)return on(c,n[0]);if(typeof c!="string"||c.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return c});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);r[n[0]]=i[0]}return r}function Ze(e,r){let t=Yi(r),n=Re(t,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=Re(t,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=Re(t,["Type","type"],e.orderType,"Type"),a=Re(t,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),c=Re(t,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),u=Re(t,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),s=Zi(t,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=Fe(t,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=Fe(t,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),f=Fe(t,["Price","price"],"Price");if(BigInt(d)!==dt(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==dt(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==dt(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let m=Qi(t,["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 h=Fe(t,["txType","tx_type","TxType"],"txType");if(h!==Ut)throw new Error("lighter: signed txType must be official create-order");let w={...ea(t),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:a,ReduceOnly:c,TriggerPrice:u,OrderExpiry:s,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(f),IsAsk:p?1:0,txType:h},b=JSON.stringify(w),E=JSON.parse(b);if(E.MarketIndex!==Number(d)||E.BaseAmount!==Number(l)||E.Price!==Number(f)||E.IsAsk!==(p?1:0)||E.txType!==h)throw new Error("lighter: canonical tx_info mutated");return{txType:h,txInfo:b,submitTo:jt(e.submitTo)}}function an(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var $e=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 r=Buffer.from(e,"base64");return r.toString("base64")===e?r:null},ft=e=>String(e||"").toLowerCase();function ra(e,r){if(typeof e!="string")return!1;let t,n;try{t=Xt.from(e),n=Xt.from({chainId:r.chainId,to:r.to,data:r.data,value:r.value,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce,type:r.type,accessList:r.accessList})}catch{return!1}return ft(t.from)!==ft(r.from)||ft(t.to)!==ft(r.to)?!1:t.unsignedHash===n.unsignedHash}function na(e){let r=Buffer.from(Kt.encode(e)),t=sn("sha256").update(r).digest();return Buffer.from(sn("sha256").update(t).digest()).reverse().toString("hex")}function ln(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||na(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))return!1;let r=e.nonWitnessUtxo.outputs?.[e.index];return r?BigInt(e.witnessUtxo.amount)===BigInt(r.amount)&&Buffer.from(e.witnessUtxo.script||[]).equals(Buffer.from(r.script||[])):!1}function oa(e,r){let t=$e(e),n=$e(r.psbt);if(!t||!n)return!1;try{let o=Yt.fromPSBT(n),i=Yt.fromPSBT(t);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 c=i.getInput(a),u=o.getInput(a);if(!ln(u)||!ln(c))return!1;let s=(w,b)=>{if(w==null&&b==null)return!0;if(w==null||b==null)return!1;try{return Buffer.from(w).equals(Buffer.from(b))}catch{return!1}},d=(w,b)=>{if(w==null&&b==null)return!0;if(w==null||b==null)return!1;try{return Buffer.from(Kt.encode(w)).equals(Buffer.from(Kt.encode(b)))}catch{return s(w,b)}};if(!!c.witnessUtxo!=!!u.witnessUtxo||c.witnessUtxo&&(BigInt(c.witnessUtxo.amount)!==BigInt(u.witnessUtxo.amount)||!s(c.witnessUtxo.script,u.witnessUtxo.script))||!d(c.nonWitnessUtxo,u.nonWitnessUtxo)||!s(c.redeemScript,u.redeemScript)||!s(c.witnessScript,u.witnessScript)||c.sighashType!==void 0&&c.sighashType!==Ie.DEFAULT&&c.sighashType!==Ie.ALL)return!1;let l=w=>!(w instanceof Uint8Array)||w.length<9?!1:w[w.length-1]===Ie.ALL,f=w=>w instanceof Uint8Array?w.length===64?!0:w.length===65&&w[64]===Ie.ALL:!1;for(let w of c.partialSig||[]){let b=Array.isArray(w)?w[1]:w;if(!l(b))return!1}if(c.tapKeySig&&!f(c.tapKeySig))return!1;for(let w of c.tapScriptSig||[]){let b=Array.isArray(w)?w[1]:w;if(!f(b))return!1}let m=w=>w[w.length-1]===Ie.ALL,p=w=>w.length>=9&&w.length<=73&&w[1]===w.length-3&&w[2]===2,g=w=>{let b=!1;for(let E of w)if(E instanceof Uint8Array){if(E[0]===48){if(!p(E)||!m(E))return!1;b=!0;continue}if(E.length===64){b=!0;continue}if(E.length===65){if(E[64]!==Ie.ALL&&E[64]!==Ie.DEFAULT)return!1;b=!0}}return b};if(c.finalScriptWitness){let w;if(Array.isArray(c.finalScriptWitness))w=c.finalScriptWitness;else if(c.finalScriptWitness instanceof Uint8Array){let b=c.finalScriptWitness,E=T=>{let v=b[T];return v===void 0?null:v<253?{value:v,next:T+1}:v===253?{value:b[T+1]|b[T+2]<<8,next:T+3}:null},S=E(0);if(!S)return!1;w=[];let I=S.next;for(let T=0;T<S.value;T++){let v=E(I);if(!v||I+v.value>b.length)return!1;w.push(b.slice(v.next,v.next+v.value)),I=v.next+v.value}if(I!==b.length)return!1}else return!1;if(!w.length||!g(w))return!1}if(c.finalScriptSig instanceof Uint8Array&&c.finalScriptSig.length){let w=c.finalScriptSig,b=[],E=0;for(;E<w.length;){let S=w[E];if(S>=1&&S<=75){if(E+1+S>w.length)return!1;b.push(w.slice(E+1,E+1+S)),E+=1+S;continue}if(S===76){let I=w[E+1];if(I===void 0||E+2+I>w.length)return!1;b.push(w.slice(E+2,E+2+I)),E+=2+I;continue}return!1}if(!b.length||!g(b))return!1}if(![c.partialSig,c.tapKeySig,c.tapScriptSig,c.finalScriptSig,c.finalScriptWitness].some(w=>Array.isArray(w)||w instanceof Uint8Array?w.length>0:w!=null))return!1}return!0}catch{return!1}}function fn(e){let r=0,t=0,n=0;for(;n<e.length&&n<3;){let o=e[n++];if(r|=(o&127)<<t,(o&128)===0)return{value:r,offset:n};t+=7}return null}function ia(e,r,t){let n=$e(e),o=$e(r.messageBase64);if(!n||!o)return!1;let i=fn(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let c=n.subarray(i.offset,a),u=n.subarray(a);if(!u.equals(o))return!1;try{let s=dn.decode(String(t));return s.length===32&&ta.verify(c,u,s)}catch{return!1}}function pn(e,r,t,n){if(String(e).startsWith("evm"))return ra(r,t);if(e==="btc")return oa(r,t);if(e==="sol")return ia(r,t,n?.owner);if(e==="hl"){if(t?.typedData?.domain&&t.typedData.types&&t.typedData.message)try{return String(un(t.typedData.domain,t.typedData.types,t.typedData.message,r)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return nn({signature:r,action:t?.action,nonce:t?.nonce,isMainnet:!String(t?.submitTo||"").includes("testnet"),owner:n?.owner})}if(e==="poly"&&t?.domain&&t.types&&t.message)try{return String(un(t.domain,t.types,t.message,r)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Ze(t,r),!0}catch{return!1}return!1}function mn(e,r){try{if(String(e).startsWith("evm"))return Xt.from(r).hash;if(e==="btc"){let t=$e(r);if(!t)return null;let n=Yt.fromPSBT(t);return n.finalize(),n.extract(),n.id}if(e==="sol"){let t=$e(r);if(!t)return null;let n=fn(t);if(!n||n.value!==1)return null;let o=t.subarray(n.offset,n.offset+64);return o.length===64?dn.encode(o):null}if(e==="hl"&&typeof r=="string"&&r.startsWith("0x"))return cn(r);if(e==="poly"&&typeof r=="string"&&r.startsWith("0x"))return cn(r)}catch{}return null}var ua=e=>String(e||"").toLowerCase();function Y(e){return aa("sha256").update(JSON.stringify(e)).digest("hex")}function Zt(e,r,t={}){return ot(e,r,t)}async function la(e,r={}){if(!re(e?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(typeof r.estimateNetworkFees!="function")throw new Error("policy: rollup fee estimate required");let t=await r.estimateNetworkFees(e);if(!t||t.l1FeeWei===void 0||t.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");return{l1FeeWei:String(t.l1FeeWei),operatorFeeWei:String(t.operatorFeeWei)}}function hn(e,r,t=!1){if(!re(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(t||r!=null){if(!r||r.l1FeeWei===void 0||r.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let n=BigInt(e.l1FeeWei)+BigInt(e.operatorFeeWei),o=BigInt(r.l1FeeWei)+BigInt(r.operatorFeeWei);if(n<o)throw new Error("policy: rollup fee attestation understates estimate")}return!0}var pt=class{#e=new Map;constructor({now:r=Date.now}={}){this.now=r}issue({artifact:r,owner:t,ttlMs:n=6e4}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=sa(32).toString("hex");return this.#e.set(o,{digest:Y(r),owner:ua(t),expiresAtMs:this.now()+n}),o}consume(r,t){let n=this.#e.get(String(r));if(!n)throw new Error("confirmation: used or unknown nonce");if(n.expiresAtMs<=this.now())throw this.#e.delete(String(r)),new Error("confirmation: expired nonce");let o=Buffer.from(n.digest,"hex"),i=Buffer.from(Y(t),"hex");if(!ca(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(r)),n}clear(){this.#e.clear()}};function da(e){let r=String(e?.data||"0x").toLowerCase(),t=BigInt(e?.value??0);if(r==="0x"){if(t<=0n)throw new Error("signer: native EVM transfer value required");return!0}if(te(r)){if(t!==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 fa(e={},r={}){let t={};for(let n of new Set([...Object.keys(e||{}),...Object.keys(r||{})]))t[n]=(BigInt(r?.[n]??0)-BigInt(e?.[n]??0)).toString();return t}function mt(e,r){let t=String(r||"");if(String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(t);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(t);if(e==="sol")try{let n=wn.decode(t);return n.length===64&&wn.encode(n)===t}catch{return!1}return e==="hl"?/^0x[0-9a-fA-F]{64}$/.test(t):e==="poly"?/^0x[0-9a-fA-F]{64}$/.test(t):!1}function gn(e,r,t){return!mt(e,r)||!mt(e,t)?!1:e==="sol"?String(r)===String(t):String(r).toLowerCase()===String(t).toLowerCase()}function pa(e){let r=e?.confirmationMode;if(r!=="exact-human"&&r!=="auto-within-rails")throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");return r}async function Qt({artifact:e,envelope:r,nonce:t,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:c}){let u=pa(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(u!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(r?.triggerAttestation,e,c())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(u!=="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(t,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=c())throw new Error("confirmation: expired nonce");return i}function ma(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function wa(e,r){return e&&ma(e.surface)?ct(e):[r]}function ha(e,r){let t=e?.hash??null,n=e?.transactionHash??null;if(t!=null&&n!=null&&!gn(r,t,n))throw new Error("signer: receipt reports conflicting transaction hashes");return t||n||null}function ga(e,r){let t=e?.verifiedBefore??e?.before,n=e?.verifiedAfter??e?.after;return{transactionHash:r,status:e?.status,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:fa(t,n)}}async function yn(e,r,t){if(!t.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:h,...w}=e||{};return w})(),i=wa(n,o),a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=()=>typeof t.nowMs=="function"?t.nowMs():t.nowMs??Date.now(),u=await Qt({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:null,consumeNonce:!0,nowMs:c}),s=Y(e),d=(h={})=>{n?ut(n,a,h):(Zt(o,a,{nowMs:h.nowMs,networkFees:h.networkFees,requireNetworkFees:h.requireNetworkFees}),da(o))},l=async h=>{let w=n&&!String(n.surface||"").startsWith("evm")?void 0:await la(h,t);return{nowMs:c(),verifyFeeWaiver:t.verifyFeeWaiver,routeAttestationSecret:t.routeAttestationSecret,networkFees:w,requireNetworkFees:re(h?.chainId)}};d({nowMs:c(),verifyFeeWaiver:t.verifyFeeWaiver,routeAttestationSecret:t.routeAttestationSecret});for(let h of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof t[h]!="function")throw new Error(`signer: ${h} is required`);let f=t.reserveLedger(n||e,a);if(!f)throw new Error("signer: ledger reservation required");let m=!1,p=[];try{for(let h of i){if(typeof t.simulate!="function"||await t.simulate(h,n)!==!0)throw new Error("signer: strict affirmative simulation required");let w=await l(h);if(hn(h,w.networkFees,w.requireNetworkFees),!t.isArmed())throw new Error("signer: disarmed before signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,u=await Qt({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:u,consumeNonce:!1,nowMs:c}),d(w),t.validateReservation(f,a,n&&typeof t.decodeEconomics=="function"?t.decodeEconomics(n,a):void 0),m=!0;let b=await t.sign(h,n);if(typeof t.verifySigned!="function"||await t.verifySigned(b,h,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!t.isArmed())throw new Error("signer: disarmed before broadcast");if(Y(e)!==s)throw new Error("signer: artifact mutated after signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,u=await Qt({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:u,consumeNonce:!1,nowMs:c});let E=await l(h);hn(h,E.networkFees,E.requireNetworkFees),d(E),t.validateReservation(f,a,n&&typeof t.decodeEconomics=="function"?t.decodeEconomics(n,a):void 0);let S=await t.broadcast(b,h,n),I=S?.status,T=n?.surface||"evm",v=ha(S,T),C=mn(T,b);if(!gn(T,v,C))throw new Error("signer: receipt transaction hash does not match signed bytes");if(I===0||I==="0x0")throw mt(T,v)?(t.settleFailedLedger(f),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(!mt(T,v))throw new Error("signer: successful broadcast requires a valid transaction hash");p.push(ga(S,v))}}catch(h){throw m||t.releaseLedger(f),h}if(t.commitLedger(f),p.length===1){let h={receipt:p[0]};return n?.surface==="evm-bridge"&&(h.originStatus="success",h.destinationStatus="unverified",h.destinationSuccess=!1,h.note="Origin-chain receipts do not prove destination-chain settlement."),h}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 En=new Set(["127.0.0.1","::1","localhost"]),ba=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&Ea(t,n)},U=(e,r,t)=>{let n=JSON.stringify(t);e.writeHead(r,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function xa(e){let r=String(e||"");if(r.startsWith("[")){let t=r.indexOf("]");if(t>1)return r.slice(1,t)}return r.split(":")[0]}var bn=e=>new Promise((r,t)=>{let n=0,o=[],i=!1;e.on("data",a=>{n+=a.length,n>64*1024&&!i?(i=!0,t(new Error("request refused")),e.resume()):i||o.push(a)}),e.on("end",()=>{if(!i)try{r(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{t(new Error("request refused"))}}),e.on("error",t)});function xn(e={}){let r=e.host||"127.0.0.1";if(!En.has(r))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 t=e.confirmations||new pt,n=e.origin||`http://${r}`;return ya.createServer(async(i,a)=>{try{let c=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!ba(c,e.token))return U(a,401,{error:"unauthorized"});let u=xa(i.headers.host);if(!En.has(u))return U(a,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return U(a,403,{error:"origin refused"});if(i.method==="GET"&&i.url==="/status"){let s=typeof e.readPolicy=="function"?e.readPolicy():e.policy,d=new Set(Ht),l=Array.isArray(s?.surfaces)?s.surfaces.filter(f=>typeof f=="string"&&d.has(f)):[];return U(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(),t.clear(),U(a,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return U(a,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return U(a,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return U(a,403,{error:"autonomous signer does not issue human confirmation nonces"});let s=await bn(i),d=Y(s.artifact),l=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(l?.confirmationMode!=="exact-human")return U(a,403,{error:"exact-human policy required"});let f=typeof e.nowMs=="function"?e.nowMs():Date.now();if(s.artifact?.version===1&&s.artifact?.surface)ut(s.artifact,l,{nowMs:f,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:m,...p}=s.artifact||{};Zt(p,l,{nowMs:f})}return typeof e.confirmArtifact!="function"?U(a,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(s.artifact,d,l)!==!0?U(a,400,{error:"exact human confirmation refused"}):U(a,200,{confirmationNonce:t.issue({artifact:s.artifact,owner:s.artifact?.owner??s.artifact?.from,ttlMs:s.ttlMs})})}if(i.method==="POST"&&i.url==="/execute"){let s=await bn(i),d=await yn(s.artifact,s.confirmationNonce,{...e,confirmations:t});return U(a,200,d)}return U(a,404,{error:"not found"})}catch(c){return e.onError?.(String(c?.message||c)),U(a,400,{error:"request refused"})}})}import{createCipheriv as Fu,createDecipheriv as Sa,randomBytes as Aa,scryptSync as va}from"node:crypto";import L from"node:fs";import _e from"node:path";var Ia="ORACLE-LOCAL-VAULT",Ta=1,ht=Object.freeze({N:1<<17,r:8,p:1}),ka=256*1024*1024,Na=16*1024;function wt(e,r,t,{max:n=r}={}){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 ${t} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<r||o.length>n)throw new Error(`local-vault: invalid ${t} length`);return o}function Oa(e,r,t=ht){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return va(n,r,32,{...t,maxmem:ka})}function Sn(e,r){if(e?.magic!==Ia||e?.version!==Ta)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!==ht.N||e.kdf.r!==ht.r||e.kdf.p!==ht.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 t=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(l=>!t.includes(l)))throw new Error("local-vault: unexpected vault field");let n=wt(e.kdf.salt,32,"salt"),o=wt(e.cipher.iv,12,"iv"),i=wt(e.tag,16,"tag"),a=wt(e.ciphertext,1,"ciphertext",{max:Na}),{ciphertext:c,tag:u,...s}=e,d=Oa(r,n);try{let l=Sa("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(s))),l.setAuthTag(i),Buffer.concat([l.update(a),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function La(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 Ca(e){let r=_e.dirname(e),t=L.lstatSync(r);if(!t.isDirectory()||t.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(t.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((t.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=L.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!==t.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function R(e){let r;try{r=L.openSync(e,L.constants.O_RDONLY|L.constants.O_NOFOLLOW)}catch(t){throw t.code==="ELOOP"?new Error("local-vault: refusing symlink"):t}try{let t=L.fstatSync(r);if(La(t),t.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=L.lstatSync(e);if(n.isSymbolicLink()||n.dev!==t.dev||n.ino!==t.ino)throw new Error("local-vault: secret source changed or is too large");return L.readFileSync(r,"utf8").replace(/[\r\n]+$/,"")}finally{L.closeSync(r)}}function An(e){return JSON.parse(R(e))}function ye(e,r){L.mkdirSync(_e.dirname(e),{recursive:!0,mode:448}),Ca(e);let t=_e.join(_e.dirname(e),`.${_e.basename(e)}.${process.pid}.${Aa(6).toString("hex")}.tmp`);try{let n=L.openSync(t,L.constants.O_CREAT|L.constants.O_EXCL|L.constants.O_WRONLY|L.constants.O_NOFOLLOW,384);try{L.writeFileSync(n,String(r)),L.fsyncSync(n)}finally{L.closeSync(n)}L.renameSync(t,e),L.chmodSync(e,384);let o=L.openSync(_e.dirname(e),"r");try{L.fsyncSync(o)}finally{L.closeSync(o)}}catch(n){try{L.unlinkSync(t)}catch{}throw n}}import{createHmac as Pa,randomBytes as Ra,timingSafeEqual as Fa}from"node:crypto";import j from"node:fs";import Te from"node:path";import{homedir as er}from"node:os";import{join as tr}from"node:path";var vn=process.env.ORACLE_PUBLIC_DESKTOP==="1",Ba=vn?process.env.ORACLE_CONFIG_DIR||tr(er(),".config","oracle"):tr(er(),".config","oracle"),Uu=vn?Ba:tr(er(),".config","mad-desk");var zu="0".repeat(64),Vu=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 gt(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(gt).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+gt(e[t])).join(",")+"}"}var Gu=Promise.resolve();function Me(e,r){if(!e)throw new Error("ledger: separate freshness anchor required");let t=a=>{try{return j.realpathSync(a)}catch{return Te.resolve(a)}},n=t(Te.dirname(Te.resolve(e))),o=t(Te.dirname(Te.resolve(r))),i=(a,c)=>c===a||c.startsWith(a+Te.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var $a=864e5,J=(e,r)=>Pa("sha256",r).update(gt(e)).digest("hex"),ie=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&Fa(t,n)},_a=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:r,...t}=e;return t};function qa(e,r){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!ie(e.integrity.mac,J(e.policy,r)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Et(e,r){if(!e)throw new Error("policy: sequence anchor required");let t;try{t=R(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(t)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!ie(n?.integrity?.mac,J(n?.marker,r)))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 Ma(e,r,t,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 c=Et(e,t);i=c.present&&c.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(r),policyMac:String(n)};i&&(a.ledgerInitialized=!0),ye(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:J(a,t)}})+`
4
- `)}function Da(e,r){let t=Et(e,r);if(!t.present)throw new Error("policy: sequence anchor required");if(t.ledgerInitialized)return!0;if(t.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");return Ma(e,t.sequence,r,t.policyMac,{ledgerInitialized:!0}),!0}function In(e,r,{sequenceAnchorFile:t}={}){if(!t)throw new Error("policy: sequence anchor required");let n=R(r),o;try{o=JSON.parse(R(e))}catch(u){throw new Error(`policy: cannot read sealed policy: ${u?.message||u}`)}let i=qa(o,n);Me(t,e);let a=Et(t,n),c=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(c!==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(!ie(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function et(e,r,t,n,o){let i=`${e}.continuity`,a;try{let c=JSON.parse(R(e));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!ie(c?.integrity?.mac,J(c.ledger,r)))throw new Error("integrity verification failed");if(a=c.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(c){if(c?.code==="ENOENT"){if(j.existsSync(i)||j.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let u=Et(o,r);if(u.present&&u.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:t,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${c?.message||c}`)}try{let c=JSON.parse(R(i));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!ie(c?.integrity?.mac,J(c.marker,r)))throw new Error("continuity verification failed");if(c.marker?.version===2&&(c.marker.sequence!==a.sequence||!ie(c.marker.ledgerMac,J(a,r))))throw new Error("continuity rollback detected");if(c.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(j.existsSync(n)&&(c.marker?.version!==2||a.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(c.marker?.version===2){let u=JSON.parse(R(n));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!ie(u?.integrity?.mac,J(u.marker,r))||u.marker?.version!==1||u.marker.sequence!==a.sequence||!ie(u.marker.ledgerMac,J(a,r)))throw new Error("checkpoint rollback detected")}}catch(c){throw new Error(`ledger: corrupt or unreadable: ${c?.message||c}`)}if(t-a.windowStartMs>=$a){let c=a.entries.map(u=>u.state==="reserved"?u:Array.isArray(u.units)?{...u,state:"consumed",units:u.units.map(s=>({...s,value:"0",notional:"0"}))}:{...u,state:"consumed",value:"0",notional:"0"});return{windowStartMs:t,entries:c,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function Ua(e){return Array.isArray(e.units)?e.units:[{unit:e.unit||"wei",value:e.value,notional:e.notional,fee:e.fee}]}function Ee(e,r,t){return e.reduce((n,o)=>{let i=Ua(o).find(a=>a.unit===t);return i?n+BigInt(i[r]??0):n},0n)}function rr(e){if(!Array.isArray(e)||e.length===0)throw new Error("ledger: units array required");let r=new Set,t=e.map(n=>{let o=String(n?.unit||"");if(!o)throw new Error("ledger: unit required");if(r.has(o))throw new Error("ledger: duplicate unit in units array");r.add(o);let i=BigInt(n.value??0),a=BigInt(n.notional??0);if(i<0n||a<0n)throw new Error("ledger: unit value/notional must be non-negative");let c=n.fee===void 0?0n:BigInt(n.fee);if(c<0n)throw new Error("ledger: unit fee must be non-negative");return{unit:o,value:i.toString(),notional:a.toString(),fee:c.toString()}});return t.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),t}function yt(e,r){if(String(r).startsWith("erc20:")){let n=String(r).slice(6).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("ledger: invalid ERC20 accounting unit");let o=Object.entries(e.nftPaymentTokenCaps||{}).find(([a])=>String(a).toLowerCase()===n)?.[1];if(!o)throw new Error("ledger: NFT payment-token caps required");let i=["maxDailyValueRaw","maxDailyNotionalRaw","maxPerTradeRaw"];for(let a of i)if(o[a]===void 0||o[a]===null||o[a]==="")throw new Error(`ledger: ${a} required`);return i.map(a=>BigInt(o[a]))}let t=r==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:r==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:r==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:null;if(!t)throw new Error("ledger: unsupported accounting unit");for(let n of t)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return t.map(n=>BigInt(e[n]))}function tt(e,r){let t=`${e}.lock`,n=Ra(16).toString("hex"),o;try{o=j.openSync(t,j.constants.O_CREAT|j.constants.O_EXCL|j.constants.O_WRONLY|(j.constants.O_NOFOLLOW||0),384),j.writeFileSync(o,n),j.fsyncSync(o)}catch(i){throw o!==void 0&&j.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return r()}finally{j.closeSync(o);try{R(t)===n&&j.unlinkSync(t)}catch{}}}function qe(e,r,t,n,o){let i=`${e}.continuity`,a={...r,sequence:(r.sequence??0)+1},c=J(a,t);ye(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:c}})+`
5
- `);let u={version:2,sequence:a.sequence,ledgerMac:c};ye(i,JSON.stringify({marker:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:J(u,t)}})+`
6
- `);let s={version:1,sequence:a.sequence,ledgerMac:c};j.mkdirSync(Te.dirname(n),{recursive:!0,mode:448}),ye(n,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:J(s,t)}})+`
7
- `),o&&Da(o,t)}function nr({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:c=0,fee:u,units:s,policy:d,nowMs:l=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");Me(t,e);let m=R(r);return tt(e,()=>{let p=et(e,m,l,t,n);if(p.entries.some(h=>String(h.tradeId)===f))throw new Error("ledger: replayed tradeId");let g;if(s!==void 0){let h=rr(s);for(let w of h){let[b,E,S]=yt(d,w.unit),I=BigInt(w.value),T=BigInt(w.notional);if(T>S)throw new Error("ledger: per-trade cap exceeded");if(Ee(p.entries,"value",w.unit)+I>b||Ee(p.entries,"notional",w.unit)+T>E)throw new Error("ledger: daily cap exceeded")}g={tradeId:f,units:h,state:"reserved",atMs:l}}else{let h=BigInt(a),w=BigInt(c),[b,E,S]=yt(d,i);if(h<0n||w<0n||w>S)throw new Error("ledger: per-trade cap exceeded");if(Ee(p.entries,"value",i)+h>b||Ee(p.entries,"notional",i)+w>E)throw new Error("ledger: daily cap exceeded");g={tradeId:f,unit:i,value:h.toString(),notional:w.toString(),fee:u===void 0?"0":BigInt(u).toString(),state:"reserved",atMs:l}}return p.entries.push(g),qe(e,p,m,t,n),structuredClone(g)})}function Tn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:c=Date.now()}){Me(t,e);let u=R(r);return tt(e,()=>{let s=et(e,u,c,t,n),d=s.entries.find(g=>String(g.tradeId)===String(o?.tradeId??"")&&g.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let g=rr(o.units);if(JSON.stringify(g)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(a){if(!Array.isArray(a.units))throw new Error("ledger: reserved units no longer match decoded economics");let h=rr(a.units);if(h.length!==d.units.length||h.some((w,b)=>w.unit!==d.units[b].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let w=0;w<h.length;w++)if(BigInt(h[w].value)>BigInt(d.units[w].value)||BigInt(h[w].notional)>BigInt(d.units[w].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let h of d.units){let[w,b,E]=yt(i,h.unit);if(BigInt(h.notional)>E)throw new Error("ledger: per-trade cap exceeded");if(Ee(s.entries,"value",h.unit)>w||Ee(s.entries,"notional",h.unit)>b)throw new Error("ledger: daily cap exceeded")}return structuredClone(d)}if(d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(d.value)||BigInt(a.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[f,m,p]=yt(i,l);if(BigInt(d.notional)>p)throw new Error("ledger: per-trade cap exceeded");if(Ee(s.entries,"value",l)>f||Ee(s.entries,"notional",l)>m)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function kn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(t,e);let a=R(r);return tt(e,()=>{let c=et(e,a,i,t,n),u=c.entries.find(s=>String(s.tradeId)===String(o??"")&&s.state==="reserved");if(!u||u.state!=="reserved")throw new Error("ledger: reservation unavailable");return u.state="committed",u.committedAtMs=i,qe(e,c,a,t,n),structuredClone(u)})}function Nn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(t,e);let a=R(r);return tt(e,()=>{let c=et(e,a,i,t,n),u=c.entries.findIndex(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(u<0)throw new Error("ledger: reservation unavailable");let[s]=c.entries.splice(u,1);return qe(e,c,a,t,n),structuredClone(s)})}function On({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(t,e);let a=R(r);return tt(e,()=>{let c=et(e,a,i,t,n),u=c.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!u)throw new Error("ledger: reservation unavailable");if(Array.isArray(u.units))return u.state="committed",u.committedAtMs=i,u.units=u.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),u.settledAs=u.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",qe(e,c,a,t,n),structuredClone(u);let s=BigInt(u.fee??0);return s<=0n?(u.state="committed",u.committedAtMs=i,u.value="0",u.notional="0",u.settledAs="no-fee",qe(e,c,a,t,n),structuredClone(u)):(u.state="committed",u.committedAtMs=i,u.value="0",u.notional=s.toString(),u.settledAs="fee-only",qe(e,c,a,t,n),structuredClone(u))})}function Ln(e,r,t,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:Y(_a(r))};return ie(e.mac,J(o,R(t)))}function ja(e){let r={...e?.fee||{}};return delete r.waiverAttestation,{...e,fee:r}}function Cn(e,r,t,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(r.owner).toLowerCase(),action:String(r.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:Y(ja(r))};return ie(e.mac,J(o,R(t)))}import{spawnSync as Wa}from"node:child_process";function Bn(e="oracle-local-signer",r=process.env.USER||process.env.USERNAME||"oracle"){let t,n;if(process.platform==="darwin")t="/usr/bin/security",n=["find-generic-password","-s",e,"-a",r,"-w"];else if(process.platform==="linux")t="secret-tool",n=["lookup","service",e,"account",r];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let o=Wa(t,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 or}from"ethers";import{base58 as Fn}from"@scure/base";import{ed25519 as Ha}from"@noble/curves/ed25519.js";import{NETWORK as $n,TEST_NETWORK as _n,WIF as Ja,p2wpkh as Pn}from"@scure/btc-signer";import{pubECDSA as za}from"@scure/btc-signer/utils.js";var Va=e=>{let r=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(r)||r.length%2?null:Buffer.from(r,"hex")},Ga=e=>{let r=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r))return null;let t=Buffer.from(r,"base64");return t.toString("base64")===r?t:null},De=(e,r)=>{if(!(e instanceof Uint8Array))throw new Error(`${r}: 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(`${r}: expected 32-byte private key material`)};function ir(e,r){let t=String(r||"").trim();if(e==="evm")return new or(t).privateKey;if(e==="btc")for(let i of[$n,_n])try{return Buffer.from(Ja(i).decode(t))}catch{}if(e==="sol")try{return De(Fn.decode(t),"sol")}catch{}let n=Va(t);if(n)return e==="evm"?new or(`0x${n.toString("hex")}`).privateKey:De(n,e);let o=Ga(t);if(o)return De(o,e);if(t.startsWith("[")||t.startsWith("{")){let i=JSON.parse(t);if(Array.isArray(i))return De(Uint8Array.from(i),e);let a=i.privateKey??i.secretKey??i.key;if(a)return ir(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function Rn(e,r){if(e==="evm"){let t=new or(String(r));return{kind:e,secret:t.privateKey,addresses:[t.address.toLowerCase()]}}if(e==="btc"){let t=De(r,"btc"),n=za(t);return{kind:e,secret:t.toString("hex"),addresses:[Pn(n,$n).address,Pn(n,_n).address]}}if(e==="sol"){let t=De(r,"sol");return{kind:e,secret:t.toString("hex"),addresses:[Fn.encode(Ha.getPublicKey(t))]}}throw new Error(`unsupported signer kind ${e}`)}function qn(e,r={}){let t=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(r.kind||"")!=="multichain")return{[r.kind||"evm"]:Rn(r.kind||"evm",ir(r.kind||"evm",t))};let n=JSON.parse(t),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Rn(i,ir(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function ar(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var se=new lr(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Dn=new lr(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),cr=new lr(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function rs(e){let r=process.env.ORACLE_SIGNER_STATE_DIR||ee.join(process.env.XDG_STATE_HOME||ee.join(Ka.homedir(),".local","state"),"oracle"),t=Ya("sha256").update(ee.resolve(e)).digest("hex").slice(0,16);return{vault:ee.join(e,"vault.json"),policy:ee.join(e,"signer-policy.json"),policyKey:ee.join(e,"policy-integrity-key"),policyAnchor:ee.join(r,`signer-policy-${t}.high-water`),ledger:ee.join(e,"signer-ledger.json"),ledgerAnchor:ee.join(r,`signer-ledger-${t}.high-water`),token:ee.join(e,"signer-token"),lock:ee.join(r,`signer-${t}.lock`)}}function ns(e){try{return R(e)}catch(t){if(t.code!=="ENOENT")throw t}let r=Xa(32).toString("hex");return ye(e,r+`
8
- `),r}function Dl(e,r,t){let n=String(e||"").toLowerCase();if(n!==String(r||"").toLowerCase())throw new Error("signer: wallet does not match vault metadata");if(!Array.isArray(t)||!t.some(o=>String(o).toLowerCase()===n))throw new Error("signer: wallet is not an allowed policy owner");return!0}function ur(e,r,t){if(!r)throw new Error(`signer: ${e} key is required by policy`);let n=new Set((t||[]).map(o=>String(o).toLowerCase()));if(!r.addresses.some(o=>n.has(String(o).toLowerCase())))throw new Error(`signer: ${e} vault address is not an allowed policy owner`);return!0}function Un(e){return e.surfaces.some(r=>String(r).startsWith("evm"))}function H(e,r){return e.surfaces.includes(r)}function ae(e,r){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(t))throw new Error(`signer: invalid ${r}`);return t}function jn(e,r){return Object.entries(e||{}).find(([t])=>t.toLowerCase()===r)?.[1]}function os(e,r){let t=e?.anvilQuote;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("signer: exact prepared Anvil quote is required");if(!e?.artifact?.anvilQuote||JSON.stringify(e.artifact.anvilQuote)!==JSON.stringify(t))throw new Error("signer: exact prepared Anvil quote artifact mismatch");return Object.freeze(r==="buy"?{totalCostRaw:BigInt(t.totalCostRaw).toString(),baseCostRaw:BigInt(t.baseCostRaw).toString(),feeRaw:BigInt(t.feeRaw).toString(),protocolFeeRaw:BigInt(t.protocolFeeRaw).toString(),available:t.available===!0}:{netPayoutRaw:BigInt(t.netPayoutRaw).toString(),grossPayoutRaw:BigInt(t.grossPayoutRaw).toString(),feeRaw:BigInt(t.feeRaw).toString(),protocolFeeRaw:BigInt(t.protocolFeeRaw).toString()})}function is(e,r,t){if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("signer: exact prepared Anvil quote confirmation required");let n=e.artifact,o=r==="buy"?[t.totalCostRaw,e.maxPaymentTokenAmountRaw,n?.maxPaymentTokenAmountRaw,e.exactQuoteTotalCostRaw,n?.exactQuoteTotalCostRaw,e.preconditions?.confirmedTotalCostRaw]:[t.netPayoutRaw,e.minPayoutRaw,n?.minPayoutRaw,e.exactQuoteNetPayoutRaw,n?.exactQuoteNetPayoutRaw,e.preconditions?.confirmedNetPayoutRaw],i;try{i=BigInt(o[0]);for(let s of o.slice(1))if(BigInt(s)!==i)throw new Error("mismatch")}catch{throw new Error(`signer: exact Anvil ${r} settlement limit mismatch`)}let a=n?.transactions;if(!Array.isArray(a)||a.length!==1)throw new Error("signer: exact Anvil action transaction required");let c=r==="buy"?"buySpecificNFT":"sellNFT",u;try{if(u=se.decodeFunctionData(c,a[0].data),se.encodeFunctionData(c,[u[0],u[1]]).toLowerCase()!==String(a[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${r} calldata required`)}if(BigInt(u[0])!==BigInt(e.tokenId)||BigInt(u[1])!==i)throw new Error(`signer: exact Anvil ${r} calldata limit mismatch`);return i}async function de(e,r,t,n,o,i=[]){let a=await e.send("eth_call",[{to:r,data:t.encodeFunctionData(n,i)},o]);return t.decodeFunctionResult(n,a)[0]}async function as(e,r,t,{nowMs:n=Date.now(),signerAddress:o}={}){if(r?.surface!=="evm-nft"||String(r?.provider).toLowerCase()!=="anvil-nft")return null;if(!e||typeof e.send!="function")throw new Error("signer: trusted RPC cannot attest Anvil market");let i=ae(r.destination,"Anvil market"),a=ae(r.contract,"Anvil collection"),c=ae(r.paymentToken,"Anvil payment token"),u=BigInt(r.nativeSwapFeeWei),s=Number(r.paymentTokenDecimals),d=ae(o,"Anvil signer identity"),l=ae(r.owner,"Anvil envelope owner");if(d!==l)throw new Error("signer: Anvil signer identity mismatch");let f=BigInt(r.tokenId);if(f<0n)throw new Error("signer: invalid Anvil tokenId");let m=String(r.nftAction||"").toLowerCase();if(m!=="buy"&&m!=="sell")throw new Error("signer: unsupported Anvil NFT action");let p=os(r,m),g=is(r,m,p),h=r.anvilAttestation;if(!h||typeof h!="object"||Number(h.snapshotExpiresAtMs)<=Number(n))throw new Error("signer: fresh provider Anvil attestation required");let w=String(jn(t.anvilRuntimeCodeHashes,i)||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(w)||w!==String(h.runtimeCodeHash||"").toLowerCase())throw new Error("signer: Anvil runtime is not reviewed by policy");let b=jn(t.nftPaymentTokenCaps,c);if(!b||Number(b.decimals)!==s)throw new Error("signer: Anvil payment token decimals are not reviewed by policy");let E=String(await e.send("eth_chainId",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(E)||BigInt(E)!==4663n)throw new Error("signer: trusted RPC Anvil chain mismatch");let S=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(S))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let I=BigInt(S),T=await e.send("eth_getBlockByNumber",[S,!1]),v=String(T?.hash||"").toLowerCase();if(String(T?.number||"").toLowerCase()!==S||!/^0x[0-9a-f]{64}$/.test(v))throw new Error("signer: trusted RPC returned an invalid Anvil block attestation");let C=Object.freeze({blockHash:v,requireCanonical:!0}),F=String(await e.send("eth_getCode",[i,C])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(F)||F==="0x")throw new Error("signer: Anvil market runtime is empty");let z=es(F).toLowerCase();if(z!==w)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[fe,St,At]=await Promise.all([de(e,i,se,"collection",C),de(e,i,se,"token",C),de(e,i,se,"robinhoodSwapFeeWei",C)]),pe=ae(fe,"live Anvil collection"),ke=ae(St,"live Anvil payment token"),Ue=BigInt(At).toString();if(pe!==a)throw new Error("signer: live Anvil collection mismatch");if(ke!==c)throw new Error("signer: live Anvil payment token mismatch");if(Ue!==u.toString())throw new Error("signer: live Anvil native swap fee mismatch");let be=Number(await de(e,ke,Dn,"decimals",C));if(!Number.isSafeInteger(be)||be!==s)throw new Error("signer: live Anvil payment token decimals mismatch");let je=ae(await de(e,pe,cr,"ownerOf",C,[f]),"live Anvil token owner"),We=null,ce=null,xe=null,y=null,x;if(m==="buy"){let[k,N,$]=await Promise.all([de(e,i,se,"inventory",C,[f]),de(e,ke,Dn,"allowance",C,[d,i]),e.send("eth_call",[{to:i,data:se.encodeFunctionData("quoteSpecificBuy",[f])},C])]);We=!!k,ce=BigInt(N).toString();let B=se.decodeFunctionResult("quoteSpecificBuy",$);if(x=Object.freeze({totalCostRaw:BigInt(B[0]).toString(),baseCostRaw:BigInt(B[1]).toString(),feeRaw:BigInt(B[2]).toString(),protocolFeeRaw:BigInt(B[3]).toString(),available:!!B[4]}),JSON.stringify(x)!==JSON.stringify(p))throw new Error("signer: exact Anvil buy quote changed after preparation");if(je!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!We)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt(ce)!==BigInt(r.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(ce)<g)throw new Error("signer: live Anvil ERC20 allowance is insufficient");if(!x.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(x.totalCostRaw)!==g)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(x.totalCostRaw)!==BigInt(x.baseCostRaw)+BigInt(x.feeRaw)+BigInt(x.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[k,N,$]=await Promise.all([de(e,pe,cr,"getApproved",C,[f]),de(e,pe,cr,"isApprovedForAll",C,[d,i]),e.send("eth_call",[{to:i,data:se.encodeFunctionData("quoteSellNFT")},C])]);xe=ae(k,"live Anvil token approval"),y=!!N;let B=se.decodeFunctionResult("quoteSellNFT",$);if(x=Object.freeze({netPayoutRaw:BigInt(B[0]).toString(),grossPayoutRaw:BigInt(B[1]).toString(),feeRaw:BigInt(B[2]).toString(),protocolFeeRaw:BigInt(B[3]).toString()}),JSON.stringify(x)!==JSON.stringify(p))throw new Error("signer: exact Anvil sell quote changed after preparation");if(je!==d)throw new Error("signer: exact Anvil token owner does not match signer");if(xe!==i&&!y)throw new Error("signer: live Anvil NFT approval is insufficient");if(xe!==ae(r.preconditions?.approvedAddress,"prepared Anvil token approval")||y!==!!r.preconditions?.approvedForAll)throw new Error("signer: live Anvil NFT approval changed after preparation");if(BigInt(x.netPayoutRaw)!==g)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(x.netPayoutRaw)+BigInt(x.feeRaw)+BigInt(x.protocolFeeRaw)!==BigInt(x.grossPayoutRaw))throw new Error("signer: exact Anvil sell quote fee arithmetic mismatch")}return Object.freeze({source:"local-signer-trusted-rpc",chainId:4663,market:i,collection:pe,paymentToken:ke,paymentTokenDecimals:be,nativeSwapFeeWei:Ue,signerAddress:d,nftAction:m,tokenId:f.toString(),tokenOwner:je,inventoryMember:We,allowanceRaw:ce,approvedAddress:xe,approvedForAll:y,quote:x,blockNumber:I.toString(),blockHash:v,runtimeCodeHash:z,verifiedAtMs:Number(n)})}function Wn(e,r,t="execution"){if(!e||!r)throw new Error("signer: complete Anvil revalidation evidence required");for(let n of["runtimeCodeHash","market","collection","paymentToken","paymentTokenDecimals","nativeSwapFeeWei","signerAddress","nftAction","tokenId","tokenOwner","inventoryMember","allowanceRaw","approvedAddress","approvedForAll"])if(String(r[n]).toLowerCase()!==String(e[n]).toLowerCase())throw new Error(`signer: Anvil ${n} changed after simulation at ${t}`);if(JSON.stringify(r.quote)!==JSON.stringify(e.quote))throw new Error(`signer: Anvil quote changed after simulation at ${t}`);return!0}function ss(e,r,t,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:a}={}){let c=Za(new URL("./anvil-attestation-worker.mjs",import.meta.url)),u={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},s;try{s=Qa(process.execPath,[c],{input:JSON.stringify({rpcUrl:e,chainId:r,envelope:t,policy:u,nowMs:Number(o),signerAddress:a}),encoding:"utf8",timeout:i,maxBuffer:64e3,env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_OPTIONS:""},stdio:["pipe","pipe","pipe"]})}catch{throw new Error("signer: fresh independent Anvil attestation failed before reservation")}let d;try{d=JSON.parse(s)}catch{throw new Error("signer: invalid Anvil reservation attestation result")}if(!d||d.source!=="local-signer-trusted-rpc"||!/^0x[0-9a-f]{64}$/.test(String(d.blockHash||"")))throw new Error("signer: invalid Anvil reservation attestation result");return Object.freeze(d)}function cs(e,r,t,n=null){let o=e?.version===1&&e?.surface?e:null,i=o?.artifact||e||{},a=[`surface=${o?.surface||"evm"} action=${o?.action||"evm"}`,`chain=${i.chainId??i.network??i.cluster??"n/a"} owner=${o?.owner||i.from||"n/a"}`,`to=${i.to||o?.destination||"n/a"} calldata=${String(i.data||"0x")} value=${i.value??"n/a"}`,`gas=${i.gasLimit??"n/a"} maxFeePerGas=${i.maxFeePerGas??i.gasPrice??"n/a"} maxPriorityFeePerGas=${i.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${i.l1FeeWei??"n/a"} operatorFeeWei=${i.operatorFeeWei??"n/a"}`,`nonce=${i.nonce??"n/a"} type=${i.type??"n/a"} accessList=${Array.isArray(i.accessList)?i.accessList.length:0}`,`slippageBps=${o?.slippageBps??i.slippageBps??"n/a"} expiresAtMs=${o?.expiresAtMs??i.expiresAtMs??"n/a"}`],c=(s,d)=>{if(a.push(`LEG ${d} chain=${s.chainId??"n/a"} from=${s.from??"n/a"} to=${s.to??"n/a"}`),a.push(`LEG ${d} calldata=${String(s.data||"0x")} value=${s.value??"n/a"}`),a.push(`LEG ${d} gas=${s.gasLimit??"n/a"} maxFeePerGas=${s.maxFeePerGas??s.gasPrice??"n/a"} maxPriorityFeePerGas=${s.maxPriorityFeePerGas??"n/a"}`),a.push(`LEG ${d} l1FeeWei=${s.l1FeeWei??"n/a"} operatorFeeWei=${s.operatorFeeWei??"n/a"} nonce=${s.nonce??"n/a"} type=${s.type??"n/a"}`),te(String(s.data||"0x")))try{let l=ze(String(s.data||"0x"));a.push(`LEG ${d} APPROVAL token=${l.token||s.to||"n/a"} spender=${l.spender} amount=${l.amount}`)}catch{a.push(`LEG ${d} APPROVAL spender=undecodable amount=undecodable`)}},u=String(i.data||"0x");if(te(u))try{let s=ze(u);a.push(`APPROVAL token=${s.token||i.to||"n/a"} spender=${s.spender} amount=${s.amount}`)}catch{a.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(i.transactions)&&(a.push(`batchLegs=${i.transactions.length}`),i.transactions.forEach((s,d)=>c(s,d))),o?.surface==="btc"){let s=Lt(o,t);a.push(`amount=${s.value} sats fee=${s.fee} sats outputs=${s.outputs.join(",")}`)}if(o?.surface==="sol"){let s=$t(o,t);a.push(`amount=${s.value} lamports fee=${s.fee} lamports programs=${s.programs.join(",")}`)}if(o?.surface==="hl"){let s=we(o,t);a.push(`hlKind=${s.kind} actionType=${s.actionType} coin=${s.coin||"n/a"} amount=${s.amount} notionalUsd=${s.notional} submitTo=${s.submitTo}`)}if(o?.surface==="poly"){let s=he(o,t);a.push(`polyKind=${s.kind} tokenId=${s.tokenId} notionalUsdc=${s.notional} submitTo=${s.submitTo}`)}if(o?.surface==="evm-nft"&&o?.provider==="anvil-nft"&&(a.push(`anvilAction=${o.nftAction} collection=${o.contract} tokenId=${o.tokenId} market=${o.destination}`),a.push(`paymentToken=${o.paymentToken} paymentTokenDecimals=${o.paymentTokenDecimals} maxPaymentTokenAmountRaw=${o.maxPaymentTokenAmountRaw??"n/a"} minPayoutRaw=${o.minPayoutRaw??"n/a"} nativeSwapFeeWei=${o.nativeSwapFeeWei}`),n&&(a.push(`SIGNER VERIFIED block=${n.blockNumber} blockHash=${n.blockHash} runtimeCodeHash=${n.runtimeCodeHash} signer=${n.signerAddress} collection=${n.collection} paymentToken=${n.paymentToken} paymentTokenDecimals=${n.paymentTokenDecimals} nativeSwapFeeWei=${n.nativeSwapFeeWei}`),a.push(`SIGNER DYNAMIC tokenId=${n.tokenId} owner=${n.tokenOwner} inventory=${n.inventoryMember} allowanceRaw=${n.allowanceRaw} approved=${n.approvedAddress} approvedForAll=${n.approvedForAll} quote=${JSON.stringify(n.quote)}`))),o?.surface==="lighter"){let s=ge(o,t);a.push(`lighterKind=${s.kind} actionType=${s.actionType} market=${s.symbol} amount=${s.amount} submitTo=${s.submitTo}`)}return`
1
+ import Hn from"node:fs";import re from"node:path";import ts from"node:os";import{createHash as rs,randomBytes as ns}from"node:crypto";import{execFileSync as os}from"node:child_process";import{fileURLToPath as is}from"node:url";import{Interface as pr,keccak256 as as}from"ethers";import{Transaction as lr}from"@scure/btc-signer";import{ed25519 as ss}from"@noble/curves/ed25519.js";import va from"node:http";import{timingSafeEqual as Ia}from"node:crypto";import{createHash as fa,randomBytes as pa,timingSafeEqual as ma}from"node:crypto";import{base58 as yn}from"@scure/base";import{Interface as Gr}from"ethers";import{Interface as mo,MaxUint256 as wo,isAddress as ho,keccak256 as cc,toUtf8Bytes as uc}from"ethers";import{Interface as fo,isAddress as Ws}from"ethers";import{isAddress as _s}from"ethers";import{createHash as ro,createHmac as no,timingSafeEqual as oo}from"node:crypto";import{readFileSync as Qn}from"node:fs";import{homedir as Zn}from"node:os";import{join as nt}from"node:path";function eo(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let t=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return t?[t]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),r=Zn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||nt(r,".config","oracle")).trim();return[e,nt(t,"exec.env")].filter(Boolean)}return[e,nt(r,".config","oracle","exec.env"),nt(r,".config","mad-desk","exec.env")].filter(Boolean)}function ze(e,r,t){let n=e??process.env[r]??process.env[t];if(!String(n||"").trim())for(let o of eo())try{let i=Qn(o,"utf8"),a=i.match(new RegExp(`^${r}=(.*)$`,"m"))||i.match(new RegExp(`^${t}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${r} required for attestation. Set it in the environment, or place ${r}=<value> in ~/.config/oracle/exec.env`);return n}function Be(e,r,t="guard"){if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t}: current time must be a finite number (got ${to(r)})`);let n=r,o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${t}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${t} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${t}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${t}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function to(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var wr=100;function kt(e){return Array.isArray(e)?`[${e.map(kt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${kt(e[r])}`).join(",")}}`:JSON.stringify(e??null)}function io(e,{required:r=!1}={}){try{return ze(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(t){if(r)throw t;return null}}function ao(e){let{signature:r,...t}=e;return t}function so(e){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<10||r.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return ro("sha256").update(Buffer.from(r.slice(2),"hex")).digest("hex")}function co(e,r){let t=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(r??""),"utf8");return t.length!==n.length||t.length===0?!1:oo(t,n)}function uo(e){let r=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(r)||r.length<10||r.length%2!==0)return null;let t=r.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=r.length;i+=64)n.push(r.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(t){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 Tt(e,{nowMs:r=Date.now(),chainId:t,venue:n,secret:o,tx:i,requireSigned:a=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let c=io(o,{required:a});if(a&&!c)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(c){let w=no("sha256",c).update(kt(ao(e))).digest("hex");if(!co(e.signature,w))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 u=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(u)||u<0||u>wr)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(s)||s<0||s>wr||u>s)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{Be({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},r,"auto-slippage quote")}catch(w){throw new Error(`${w.message}; re-quote before signing`)}if(t!=null&&Number(e.chainId)!==Number(t))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-u),p=f/10000n;if(f%10000n!==0n&&(p+=1n),l<p)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let w=uo(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==so(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(w!=null&&w!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is hash-bound but the calldata encodes ${w}, not the guard floor ${e.minAmountOut}`)}else{if(w==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(w!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${w}`)}}return!0}var Vs=new fo(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as po,isAddress as Ys}from"ethers";var ec=new po(["function approve(address spender,uint256 amount) returns (bool)"]),tc=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function R(e,r="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${r} 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(`${r} 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(`${r} must be a number or decimal string`);return e}throw new Error(`${r} must be a number or decimal string`)}function W(e,r="value"){if(typeof e!="string"||e==="")throw new Error(`${r} must be a string`);return e}function Q(e,r="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${r} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${r} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let t=R(e,r);if(t==="")throw new Error(`${r} is required`);if(!/^-?\d+$/.test(t)&&!/^0x[0-9a-fA-F]+$/.test(t))throw new Error(`${r} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(t)}`);try{return BigInt(t)}catch{throw new Error(`${r} must be an integer, got ${JSON.stringify(t)}`)}}function V(e,r="amount"){let t=Q(e,r);if(t<=0n)throw new Error(`${r} must be positive`);return t}function P(e,r,t="amount"){let n=R(e,t);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${t} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[a="0",c=""]=i.split(".");if(c.length>r)throw new Error(`${t} has more than ${r} decimal places, which would lose precision`);let u=BigInt((a||"0")+c.padEnd(r,"0"));return o?-u:u}var wc=new mo(["function approve(address spender,uint256 amount) returns (bool)"]);function hr(e,r){let t=String(e||"").trim();if(!ho(t))throw new Error(`${r} must be an address`);return t.toLowerCase()}function go(e,r="approval amount",{allowZero:t=!1}={}){let n=Q(e,r);if(t?n<0n:n<=0n)throw new Error(`${r} must be positive`);if(n>=wo)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var gr=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),yo=new Set(["0x39509351","0xf9255c1f"]);function ne(e){let r=String(e||"").toLowerCase();return r.length<10?!1:gr.has(r.slice(0,10))}function Ve(e){if(!ne(e))throw new Error("approval calldata required");let r=String(e||"").toLowerCase(),t=r.slice(0,10),n=r.slice(10).match(/.{1,64}/g)||[],o=s=>n[s]?"0x"+n[s].slice(24):null,i=s=>n[s]?BigInt("0x"+n[s]):null,a=null,c=null,u=null;switch(t){case"0x095ea7b3":case"0x39509351":a=o(0),c=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":u=o(0),a=o(1),c=i(2);break;case"0xd505accf":a=o(1),c=i(2);break;case"0x8fcbaf0c":{a=o(1),c=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":u=o(0),a=o(1),c=i(2);break;default:throw new Error(`approval selector ${t} is recognised but not decodable; refusing to bound it`)}if(a==null||c==null)throw new Error("invalid approve calldata");return{spender:hr(a,"approval spender"),token:u==null?null:hr(u,"approval token"),amount:go(c,"approval amount",{allowZero:!0}),selector:t,additive:yo.has(t)}}import{createHash as Eo,createHmac as yc,timingSafeEqual as Ec}from"node:crypto";var bo=2,Nt=300*1e3,yr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function xo(e){let r=e==null||e===""?Nt:Number(e);return!Number.isFinite(r)||r<0?Nt:Math.min(r,yr)}function Ot(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ot).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ot(e[t])}`).join(",")}}`}function So(e){let{prepareHash:r,prepareMac:t,note:n,...o}=e||{};return o}function Ao(e){let r=So(e);return Eo("sha256").update(Ot(r)).digest("hex")}function Er(e,{maxAgeMs:r=Nt,nowMs:t=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)!==bo)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let a=Ao(e);if(String(e.prepareHash||"")!==a)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let c=Number(e.preparedAt),u=Number(e.expiresAt),s=xo(r),d=t-c,l=u-c;if(!Number.isFinite(d)||!Number.isFinite(u)||!Number.isFinite(l)||d<0||l<=0||l>yr||d>s||t>=u)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${s})`);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 ot=e=>String(e||"").toLowerCase(),vo=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),Io=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function oe(e){try{return Io.has(BigInt(e))}catch{return!1}}var Z=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},br=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},Ge=(e,r,t,n=String)=>{if(!Array.isArray(r)||r.length===0)throw new Error(`policy: ${t} allowlist is empty`);if(!r.map(n).includes(n(e)))throw new Error(`policy: ${t} not allowed`)};function it(e,r,{nowMs:t=Date.now(),networkFees:n,requireNetworkFees:o=!1}={}){if(!e||!r)throw new Error("policy: artifact and policy required");if(Object.keys(e).some(p=>!vo.has(p)))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=(p,w)=>{try{return BigInt(p)===BigInt(w)}catch{return String(p)===String(w)}};if(!Array.isArray(r.chains)||r.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!r.chains.some(p=>i(p,e.chainId)))throw new Error("policy: chain not allowed");if(Ge(e.to,r.destinations,"destination",ot),Ge(String(e.data||"0x").slice(0,10),r.selectors,"selector",p=>String(p).toLowerCase()),Ge(e.from,r.owners,"owner",ot),ne(e.data)){let p;try{p=Ve(e.data)}catch(y){throw new Error(`policy: malformed approval calldata: ${y?.message||y}`)}Ge(p.spender,r.spenders,"spender",ot),Ge(p.token||e.to,r.erc20Tokens,"ERC-20 token",ot);let w=Z(r.maxApproval,"maxApproval");if(BigInt(p.amount)>w)throw new Error("policy: approval exceeds cap");if(p.additive)throw new Error("policy: additive approval cannot be bounded; use approve() with an absolute amount")}if(Z(e.value,"value")>Z(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=Z(e.gasLimit,"gasLimit");if(a>Z(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let c=e.maxFeePerGas??e.gasPrice,u=Z(c,"feePerGas")*a,s=0n;try{if(oe(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&&(s+=Z(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(s+=Z(e.operatorFeeWei,"operatorFeeWei")),oe(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let p=Z(n.l1FeeWei,"estimated l1FeeWei")+Z(n.operatorFeeWei,"estimated operatorFeeWei");if(s<p)throw new Error("policy: rollup fee attestation understates estimate")}if(u+s>Z(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=br(r.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<=t)throw new Error("policy: artifact expired");let f=br(r.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-t>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as xr}from"node:crypto";import{Address as ko,NETWORK as To,OutScript as Sr,RawTx as No,SigHash as Ar,TEST_NETWORK as Oo,Transaction as Lo}from"@scure/btc-signer";var vr=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},Bo=(e,r)=>{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 ${r}`);let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error(`envelope: invalid ${r}`);return t},Co=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,Po=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),Ie=e=>Po(e)?String(e).toLowerCase():String(e),Lt=(e,r)=>Array.isArray(r)&&r.some(t=>Ie(t)===Ie(e)),Ro=(e,r)=>Buffer.from(e||[]).equals(Buffer.from(r||[]));function $o(e){let r=Buffer.from(No.encode(e)),t=xr("sha256").update(r).digest();return Buffer.from(xr("sha256").update(t).digest()).reverse().toString("hex")}function Fo(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if($o(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))throw new Error("envelope: Bitcoin prevout txid mismatch");let r=e.nonWitnessUtxo.outputs?.[e.index];if(!r)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(r.amount)||!Ro(e.witnessUtxo.script,r.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return r}function Bt(e,r){if(e.action!=="transfer")throw new Error("envelope: BTC decoder requires transfer action");let t=e?.artifact;if(Object.keys(t).some(l=>!["network","psbt"].includes(l)))throw new Error("envelope: unexpected BTC artifact field");if(!Lt(t.network,r.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(t.network).toLowerCase())?To:["testnet","signet","regtest"].includes(String(t.network).toLowerCase())?Oo:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Lo.fromPSBT(Bo(t.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=ko(n);for(let l=0;l<o.inputsLength;l++){let f=o.getInput(l);for(let y of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(Co(f[y]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==Ar.DEFAULT&&f.sighashType!==Ar.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let p=Fo(f),w;try{let y=Sr.decode(p.script);if(!["wpkh"].includes(y.type))throw new Error("unsupported input");w=i.encode(y)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!Lt(w,r.owners)||Ie(w)!==Ie(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...r.changeAddresses||[]].map(l=>Ie(l))),c=0n,u=!1,s=[];for(let l=0;l<o.outputsLength;l++){let f=o.getOutput(l),p;try{p=i.encode(Sr.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let w=Ie(p);if(s.push(`${p}:${f.amount}`),w===Ie(e.destination)){u=!0,c+=f.amount;continue}if(Lt(p,r.destinations)){c+=f.amount;continue}if(!a.has(w))throw new Error("policy: Bitcoin output destination not allowed")}if(!u)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>vr(r.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(c>vr(r.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:c.toString(),notional:(c+d).toString(),fee:d.toString(),outputs:Object.freeze(s)})}function Ct(e,r){let{unit:t,value:n,notional:o,fee:i}=Bt(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}import{createHash as Rt}from"node:crypto";import{base58 as Lr}from"@scure/base";import{getCompiledTransactionMessageDecoder as _o}from"@solana/transaction-messages";var $t="11111111111111111111111111111111",qo="ComputeBudget111111111111111111111111111111",Mo="So11111111111111111111111111111111111111112",Br="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var Cr="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Do=5000n,Uo=2039280n,jo=37095705934669439343138083508754565189542113879843219016388785533085940283555n,M=57896044618658097711785492504343953926634992332820282019728792003956564819949n,Ir=19681161376707505956807079304988542015446066515923890162744021073123829784752n,kr=e=>Rt("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Wo=new Map([[kr("route"),{name:"route",prefixBytes:0}],[kr("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),K=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},Ho=(e,r)=>{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 ${r}`);let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error(`envelope: invalid ${r}`);return t},de=(e,r)=>Array.isArray(r)&&r.some(t=>String(t)===String(e)),ee=e=>String(e||""),Jo=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,st=e=>Rt("sha256").update(e).digest("hex");function at(e,r){try{let t=Buffer.from(Lr.decode(String(e||"")));if(t.length!==32)throw new Error("wrong length");return t}catch{throw new Error(`envelope: invalid Solana ${r}`)}}function G(e){let r=e%M;return r>=0n?r:M+r}function ie(e,r){let t=e;for(;r-- >0n;)t=t*t%M;return t}function zo(e){let t=e*e%M*e%M,n=ie(t,2n)*t%M,o=ie(n,1n)*e%M,i=ie(o,5n)*o%M,a=ie(i,10n)*i%M,c=ie(a,20n)*a%M,u=ie(c,40n)*c%M,s=ie(u,80n)*u%M,d=ie(s,80n)*u%M,l=ie(d,10n)*i%M;return ie(l,2n)*e%M}function Vo(e,r){let t=G(r*r*r),n=G(t*t*r),o=zo(e*n),i=G(e*t*o),a=G(r*i*i),c=i,u=G(i*Ir),s=a===e,d=a===G(-e),l=a===G(-e*Ir);return s&&(i=c),(d||l)&&(i=u),(G(i)&1n)===1n&&(i=G(-i)),!s&&!d?null:i}function Go(e){if(!e||e.length!==32)return!1;let r=0n;for(let o=31;o>=0;o--)r=(r<<8n)+BigInt(o===31?e[o]&127:e[o]);let t=G(r*r),n=Vo(G(t-1n),G(jo*t+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function Ko(e,r){let t=Buffer.concat([...e,at(r,"program id"),Buffer.from("ProgramDerivedAddress")]),n=Rt("sha256").update(t).digest();if(Go(n))throw new Error("envelope: derived Solana program address is on curve");return Lr.encode(n)}function Ft(e,r,t=Br){let n=[at(e,"owner"),at(t,"token program"),at(r,"mint")];for(let o=255;o>=0;o--)try{return Ko([...n,Buffer.from([o])],Cr)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function Yo(e,r){return(r.accountIndices||[]).map(t=>ee(e.staticAccounts[t]))}function Ke(e){return Buffer.from(e.data||[])}function Xo(e,r){return ee(e.staticAccounts[r.programAddressIndex])}function Pr(e,r){return Number(r)<e.header.numSignerAccounts}function Qo(e,r){let t=e.header.numSignerAccounts,n=e.header.numReadonlySignerAccounts,o=e.header.numReadonlyNonSignerAccounts,i=e.staticAccounts.length;return Number(r)<t?Number(r)<t-n:Number(r)<i-o}function Ye(e){return e.accountIndices||[]}function Pt(e,r){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${r} allowlist required`);return e.map(String)}function Tr(e,r){let t=Ye(r).map(n=>{let o=Pr(e,n)?"s":"n",i=Qo(e,n)?"w":"r";return`${n}:${ee(e.staticAccounts[n])}:${o}:${i}`});return st(Buffer.from(t.join(`
2
+ `)))}function Nr(e,r,t){if(r+8>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readBigUInt64LE(r)}function Zo(e,r,t){if(r+2>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readUInt16LE(r)}function ei(e,r,t){if(r+4>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readUInt32LE(r)}function ti(e,r,t){let n=t.maxJupiterRoutePlanSteps===void 0?1:Number(t.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(r<1||r>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(t.jupiterRouteVariants)?t.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=t.jupiterRouteVariantPayloadBytes||{},a=0,c=0,u=[];for(let s=0;s<r;s++){if(a>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e[a++];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(a+l+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e.subarray(a,a+l);a+=l;let p=f.toString("hex"),w=t.jupiterRouteVariantPayloads?.[String(d)];if(!Array.isArray(w)||!w.map(String).includes(p))throw new Error("policy: Jupiter route variant payload not allowed");let y=e[a++],h=e[a++],m=e[a++];if(y<1||y>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(h!==s||m!==s+1)throw new Error("envelope: unsupported Jupiter route-plan token index");c+=y,u.push(Object.freeze({swapVariant:d,variantPayloadHex:p,percent:y,inputIndex:h,outputIndex:m}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(c!==100*r)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(u)}function ri(e,r){let t=Ke({data:e}),n=t.subarray(0,8).toString("hex"),o=Wo.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,a=o.prefixBytes===1?t[8]:null;if(o.prefixBytes===1&&t.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let c=8+o.prefixBytes,u=c+4,s=t.length-i;if(s<=u)throw new Error("envelope: malformed Jupiter route payload");let d=ei(t,c,"route plan length"),l=t.subarray(u,s),f=ti(l,d,r);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:d,routePlan:f,routePlanHash:st(l),inAmount:Nr(t,s,"in_amount"),quotedOutAmount:Nr(t,s+8,"quoted_out_amount"),slippageBps:Zo(t,s+16,"slippage_bps"),platformFeeBps:t[s+18],instructionHash:st(t)})}function ni(e,r,t){let n=Yo(e,r),o=(i,a)=>{let c=n[i];if(!c)throw new Error(`envelope: Jupiter ${a} account missing`);return c};if(t.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(t.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 Or(e,r){return e&&e!==r?e:null}function Y(e,r,t){let n=ee(e.staticAccounts[r]);if(!n)throw new Error(`envelope: Jupiter ${t} missing`);return n}function oi(e,r){let t=Ke(e);if(t.length===5&&t[0]===2){let n=t.readUInt32LE(1),o=r.maxComputeUnits===void 0?14e5:Number(r.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 t.length===9&&t[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function ii(e,r,t,n,o,i){let a=Ke(r);if(a.length!==1||a[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let c=Ye(r);if(c.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let u=Y(e,c[0],"ATA payer"),s=Y(e,c[1],"ATA account"),d=Y(e,c[2],"ATA owner"),l=Y(e,c[3],"ATA mint"),f=Y(e,c[4],"ATA system program"),p=Y(e,c[5],"ATA token program");if(u!==t.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(d!==t.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(f!==$t)throw new Error("envelope: Jupiter ATA system program mismatch");if(p!==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(s!==Ft(t.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:s,debit:i}}function ai(e,r,t,n,o){let i=Ye(r),a=Ke(r);if(i.length!==2||a.length!==12||a.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let c=Y(e,i[0],"wrap payer"),u=Y(e,i[1],"wrap target"),s=a.readBigUInt64LE(4);if(c!==t.owner||u!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(s!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return s}function si(e,r,t,n){let o=Ye(r),i=Ke(r);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||Y(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=Y(e,o[0],"closeAccount source"),c=Y(e,o[1],"closeAccount destination"),u=Y(e,o[2],"closeAccount authority");if(a!==n||c!==t.owner||u!==t.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function ci(e,r,t,n,o,i,a){let c=Ft(r.owner,r.artifact.inputMint,a);if(o.userSourceTokenAccount!==c)throw new Error("envelope: Jupiter source token account is not owner ATA");let u=K(t.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(u<Uo)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let s=new Map,d=0n,l=!1,f=!1;for(let p of e.instructions){if(p===n)continue;let w=Xo(e,p);if(w===qo)oi(p,t);else if(w===Cr){let{ata:y,debit:h}=ii(e,p,r,r.artifact,a,u);s.set(y,h)}else if(w===$t)d+=ai(e,p,r,c,i);else if(w===a){let y=si(e,p,r,c);y.kind==="syncNative"&&(l=!0),y.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[...s.values()].reduce((p,w)=>p+w,0n)}function ui(e){let r;try{r=_o().decode(Ho(e.messageBase64,"Solana message"))}catch(t){throw new Error(`envelope: invalid Solana message: ${t?.message||t}`)}if(r.version!=="legacy"&&Array.isArray(r.addressTableLookups)&&r.addressTableLookups.length)throw new Error("envelope: unresolved Solana address tables refused");return r}function li(e,r,t){if(e.header.numSignerAccounts!==1||ee(e.staticAccounts[0])!==r.owner||!de(r.owner,t.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=ee(e.staticAccounts[o.programAddressIndex]);if(!i||!de(i,t.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function di(e,r,t){let n=K(t.lamportsPerSignature,"lamportsPerSignature");if(n<Do)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=t.maxLamportsPerSignature===void 0?n:K(t.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),a=i*n,c=i*o;if(r.exactFeeLamports!==void 0){let s=K(r.exactFeeLamports,"exactFeeLamports");if(s<a)throw new Error("policy: Solana exact fee below the base signature fee");if(s>c)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let u=c;if(u>K(t.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return u}function fi(e,r,t,n){let o=0n,i=!1;for(let a of e.instructions){if(ee(e.staticAccounts[a.programAddressIndex])!==$t)throw new Error("envelope: unsupported Solana program decoder");let u=a.accountIndices||[];if(u.length!==2||ee(e.staticAccounts[u[0]])!==r.owner)throw new Error("envelope: Solana transfer owner mismatch");let s=ee(e.staticAccounts[u[1]]);if(s!==r.destination||!de(s,t.destinations))throw new Error("envelope: Solana destination mismatch");let d=Buffer.from(a.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>K(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function pi(e,r,t,n){let o=r.artifact;if(o.provider!=="jupiter")throw new Error("envelope: Solana swap provider must be jupiter");if(o.inputMint!==Mo)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==r.destination||!de(o.outputMint,t.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Jo(t);if(!de(o.inputMint,i)||!de(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=K(o.inAmount,"inAmount"),c=K(o.outAmount,"outAmount"),u=K(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>K(t.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>K(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(c<=0n||u<=0n||u>c)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(r.slippageBps))throw new Error("policy: Solana slippage mismatch");let s=ee(o.jupiterProgram);if(!s||!de(s,t.programs)||!n.includes(s))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(S=>ee(e.staticAccounts[S.programAddressIndex])===s);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=d[0],f=ri(l.data,t);if(f.instruction==="shared_accounts_route"){let S=Array.isArray(t.jupiterSharedRouteIds)?t.jupiterSharedRouteIds.map(Number):[];if(!S.length)throw new Error("policy: Jupiter shared route id allowlist required");if(!S.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(!Pt(t.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(f.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(f.inAmount!==a)throw new Error("envelope: Jupiter route in_amount mismatch");if(f.quotedOutAmount!==c)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 p=f.quotedOutAmount-f.quotedOutAmount*BigInt(f.slippageBps)/10000n;if(u!==p)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 w=ni(e,l,f),y=Ye(l),h=f.instruction==="shared_accounts_route"?2:1;if(!Pr(e,y[h]))throw new Error("envelope: Jupiter transfer authority must be signer");if(w.program!==s)throw new Error("envelope: Jupiter program account mismatch");if(w.userTransferAuthority!==r.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(w.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(w.sourceMint!==void 0&&w.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let m=Array.isArray(t.tokenPrograms)&&t.tokenPrograms.length?t.tokenPrograms:[Br];if(!de(w.tokenProgram,m))throw new Error("policy: Solana token program not allowed");let b=Ft(r.owner,o.outputMint,w.tokenProgram);if(w.userDestinationTokenAccount!==b)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=Or(w.destinationTokenAccount,s);if(E&&E!==b)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(Or(w.platformFeeAccount,s))throw new Error("policy: Jupiter platform fee account not allowed");if(!Pt(t.jupiterRouteAccountHashes,"Jupiter route account hash").includes(Tr(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let A=st(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,Tr(e,l)].join(`
3
+ `)));if(!Pt(t.jupiterRouteReviewHashes,"Jupiter route review hash").includes(A))throw new Error("policy: Jupiter route review hash not allowed");let I=ci(e,r,t,l,w,a,w.tokenProgram),k=a+I;if(k>K(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:k,programs:n}}function _t(e,r){if(e.action!=="transfer"&&e.action!=="swap")throw new Error("envelope: Solana decoder requires transfer or swap action");let t=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(t||{}).some(u=>!n.includes(u)))throw new Error("envelope: unexpected Solana artifact field");if(!de(t.cluster,r.chains))throw new Error("policy: chain not allowed");let o=ui(t),i=li(o,e,r),a=e.action==="transfer"?fi(o,e,r,i):pi(o,e,r,i),c=di(o,t,r);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+c).toString(),fee:c.toString(),programs:Object.freeze(a.programs)})}function qt(e,r){let{unit:t,value:n,notional:o,fee:i}=_t(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}var Fc=64*1024;var mi=1e8;function Mt(e){if(typeof e!="string"||!/^#(?:0|[1-9]\d*)$/.test(e))return null;let r=Number(e.slice(1));if(!Number.isSafeInteger(r)||r<0)return null;let t=r%10;if(t!==0&&t!==1)return null;let n=Math.floor(r/10),o=mi+r;return Number.isSafeInteger(o)?{encoding:r,outcome:n,side:t,coin:`#${r}`,assetId:o}:null}var wi=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),hi=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),gi=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"}),yi=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"}),he=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`hl: bounded ${r} required`);return e};function Ei(e,r){let t=e.toString().padStart(r+1,"0");if(r===0)return t;let n=t.slice(0,-r),o=t.slice(-r).replace(/0+$/,"");return o?`${n}.${o}`:n}function Rr(e,r){let t=R(e,`hl: ${r}`);if(!/^\d+(?:\.\d+)?$/.test(t))throw new Error(`hl: ${r} must be a positive decimal`);let[n,o=""]=t.split("."),i=BigInt(n+o);if(i<=0n)throw new Error(`hl: ${r} must be positive`);return{raw:i,decimals:o.length}}function ae(e,r){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: ${r} must be finite JSON`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(n=>ae(n,r)).join(",")}]`;if(!e||typeof e!="object")throw new Error(`hl: ${r} must be structured JSON`);return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${ae(e[n],r)}`).join(",")}}`}function bi(e){if(typeof e.orderType!="string"||!e.orderType)throw new Error("hl: order type must be a string");let r=e.orderType,t=e.orderWire;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("hl: declared order wire required");if(r==="limit"){let i=t.limit?.tif;if(!["Gtc","Ioc","Alo"].includes(i)||ae(t,"declared order type")!==ae({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(r==="market"){if(ae(t,"declared order type")!==ae({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"}}[r];if(!n)throw new Error("hl: unsupported declared order type");let o=t.trigger?.triggerPx;if(o==null||ae(t,"declared order type")!==ae({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 xi(e,r,t){let n=Rr(e.s,"signed size"),o=Rr(e.p,"signed price"),i=n.decimals+o.decimals,a=n.raw*o.raw,c=P(r.notionalUsd,i,"hl: notionalUsd");if(c<=0n||a!==c)throw new Error("hl: signed notional must match");let u=P(t.maxNotionalUsd,i,"hl: maxNotionalUsd");if(a>u)throw new Error("hl: notional exceeds cap")}function Si(e,r){let t=e.action.builder;if(t==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("hl: signed order builder must be structured");let n=he(t.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(W(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(r.hlBuilders)?r.hlBuilders.map(c=>String(c).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=Q(t.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let a=P(r.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>a)throw new Error("hl: order builder fee exceeds cap")}function $r(e,r,t){if(!Number.isSafeInteger(e.a)||e.a!==t)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(r.side==="buy"))throw new Error("hl: signed side must match exactly");if(R(e.s,"hl: signed size")!==R(r.size,"hl: size"))throw new Error("hl: signed size must match");if(R(e.p,"hl: signed price")!==R(r.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof r.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==r.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(ae(e.t,"signed order type")!==ae(r.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(r.clientOrderId==null){if(n)throw new Error("hl: undeclared signed client order id")}else if(!n||typeof e.c!="string"||e.c!==r.clientOrderId)throw new Error("hl: signed client order id must match")}function Fr(e,r,t,n,o){if(!Number.isSafeInteger(e.a)||e.a!==t)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(r.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(R(e.s,"hl: bracket protection size")!==R(r.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(R(e.p,"hl: bracket protection price")!==R(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(R(i.triggerPx,"hl: triggerPx")!==R(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function Ai(e){let r=String(e||"").replace(/\/$/,"");if(!wi.has(r))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return r}function Dt(e){return Mt(e)!=null}function vi(e,r){let t=String(e||""),n=Array.isArray(r.coins)?r.coins.map(String):[];if(Dt(t)){if(r.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(n.includes(t)||n.includes("#*")||n.includes("*")||n.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(n.length&&!n.includes(t)&&!n.includes("*"))throw new Error("hl: coin not allowed");return!0}function Ii(e,r,t){let n=Array.isArray(t.hlMarkets)?t.hlMarkets:[];if(n.length){if(!n.some(a=>{if(typeof a=="string"){let[c,u]=String(a).split(":");return c===e&&Number(u)===r}return String(a?.coin)===e&&Number(a?.assetId)===r}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(Dt(e)){let i=Array.isArray(t.coins)?t.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(t.coins)?t.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function ge(e,r){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let t=e.artifact;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("hl: structured artifact required");let n=he(t.kind,"kind",48),o=gi[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=Ai(t.submitTo);if(Object.prototype.hasOwnProperty.call(t,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(t,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let a=Number(t.nonce);if(!Number.isSafeInteger(a)||a<=0)throw new Error("hl: nonce must be a positive integer");if(!t.action||typeof t.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(t.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(t.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(t.action.type!==yi[n])throw new Error("hl: action type must match kind");let c=t.notionalUsd??0;if(hi.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let u=he(t.coin,"coin",64),s=t.assetId??t.assetIndex;if(!Number.isSafeInteger(s)||s<0)throw new Error("hl: assetId required");if(n==="hip4-order"||s>=1e8){let d=Mt(u);if(!d||d.coin!==u)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==s)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(vi(u,r),Ii(u,s,r),n==="hip4-order"&&!Dt(u))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(t.side!=="buy"&&t.side!=="sell")throw new Error("hl: side must be buy or sell");if(t.action.type!=="order"||!Array.isArray(t.action.orders))throw new Error("hl: signed orders are required");bi(t);let d=t.action.orders;if(n==="perp-bracket"){let l=t.takeProfitPx,f=t.stopLossPx,p=1+(l==null?0:1)+(f==null?0:1);if(p<2||d.length!==p||t.grouping!=="normalTpsl"||t.action.grouping!==t.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");$r(d[0],t,s);let w=1;l!=null&&Fr(d[w++],t,s,l,"tp"),f!=null&&Fr(d[w],t,s,f,"sl")}else{if(d.length!==1)throw new Error("hl: exactly one signed order is required");if(t.grouping!=="na"||t.action.grouping!==t.grouping)throw new Error("hl: signed grouping must match declared grouping");$r(d[0],t,s)}xi(d[0],t,r),Si(t,r),c=R(t.notionalUsd,"hl: notionalUsd")}if(n==="perp-leverage"){let d=t.leverage;if(!Number.isSafeInteger(d)||d<1)throw new Error("hl: leverage must be a positive integer");let l=r.maxLeverage==null?50:r.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=t.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!==s)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(t.orderId)||t.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(d[0].o)||d[0].o!==t.orderId)throw new Error("hl: signed cancel order id must match")}if(n==="perp-leverage"){if(!Number.isSafeInteger(t.action.asset)||t.action.asset!==s)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(t.action.leverage)||t.action.leverage!==t.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(t.marginMode))throw new Error("hl: declared margin mode required");let d=t.marginMode==="cross";if(typeof t.action.isCross!="boolean"||t.action.isCross!==d)throw new Error("hl: signed isCross must match declared margin mode")}if(n==="perp-isolated-margin"){if(!Number.isSafeInteger(t.action.asset)||t.action.asset!==s)throw new Error("hl: signed margin asset must match assetId");let d=he(t.usd,"margin usd",64),l=P(d,6,"hl: margin usd");if(Q(t.action.ntli,"hl: signed margin ntli")!==l)throw new Error("hl: signed margin amount must match usd");if(typeof t.isBuy!="boolean"||t.action.isBuy!==t.isBuy)throw new Error("hl: signed margin isBuy must match");let p=P(r.maxNotionalUsd,6,"hl: maxNotionalUsd"),w=l<0n?-l:l;if(w>p)throw new Error("hl: margin notional exceeds cap");c=Ei(w,6)}}if(n==="builder-fee-approval"){let u=he(t.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(u))throw new Error("hl: builder address required");if(he(t.action.builder,"signed builder",42).toLowerCase()!==u)throw new Error("hl: signed builder must match");if(!(Array.isArray(r.hlBuilders)?r.hlBuilders.map(w=>String(w).toLowerCase()):[]).includes(u))throw new Error("hl: builder not allowed");let d=he(t.maxFeeRate,"maxFeeRate",32);if(he(t.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=P(d.slice(0,-1),12,"hl: builder fee percent"),f=P(r.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(f<0n||l*100n>f)throw new Error("hl: builder fee exceeds cap");if(Number(t.action.nonce)!==a)throw new Error("hl: signed builder nonce must match");let p=i.includes("testnet")?"Testnet":"Mainnet";if(t.hyperliquidChain!==p||t.action.hyperliquidChain!==t.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(t.signatureChainId!=="0x66eee"||t.action.signatureChainId!==t.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 u=n==="hype-undelegate";if(typeof t.action.isUndelegate!="boolean"||t.action.isUndelegate!==u)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(r.maxHypeWei!=null&&BigInt(String(t.action.wei??t.caps?.amountHype??"0"))>BigInt(r.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(c??t.action.wei??0),notional:String(c??0),fee:"0",kind:n,actionType:t.action.type,amount:String(t.action.wei??c??0),coin:t.coin||null,submitTo:i})}import{createHmac as ki}from"node:crypto";var Ce="0x"+"00".repeat(32);function Ut(e={}){let r=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,t=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(!r||!t||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(r),secret:String(t),passphrase:String(n)}}function _r({creds:e,address:r,method:t,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(r||"")))throw new Error("poly: L2 address required");let a=String(i??Math.floor(Date.now()/1e3)),c=String(t||"").toUpperCase(),u=String(n||"");if(c!=="POST"||u!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let s=a+c+u+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),f=ki("sha256",l).update(s).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:r,POLY_SIGNATURE:f,POLY_TIMESTAMP:a,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function Ti(e,r){if(e.side!==0&&e.side!==1)throw new Error("poly: side must be BUY or SELL");let t=e.side===0?"BUY":"SELL";if(r&&r!==t)throw new Error("poly: side mismatch");return t}function Ni(e){let r=typeof e=="bigint"?e:V(e,"poly: atomicUsdc");if(r<=0n)throw new Error("poly: order amounts must be positive integer micro-units");let t=r/1000000n,n=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return n?`${t.toString()}.${n}`:t.toString()}function qr(e,r){let t=V(e.makerAmount,"poly: makerAmount"),n=V(e.takerAmount,"poly: takerAmount");return Ni(r==="BUY"?t:n)}function Oi(e){let r=typeof e=="bigint"?e.toString(10):R(e,"poly: salt");if(!/^[1-9][0-9]*$/.test(r))throw new Error("poly: salt must be a positive integer");let t=BigInt(r);if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("poly: salt exceeds safe integer");return Number(t)}function Mr({message:e,side:r,signature:t,orderType:n="GTC",apiKey:o}={}){if(!e||typeof e!="object")throw new Error("poly: CLOB v2 message required");if(!String(t||"").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=Ti(e,r);if(W(e.metadata||Ce,"poly: metadata").toLowerCase()!==Ce)throw new Error("poly: metadata must be zero");if(W(e.builder||Ce,"poly: builder").toLowerCase()!==Ce)throw new Error("poly: builder must be zero");let a=Oi(e.salt);return{deferExec:!1,order:{builder:Ce,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:Ce,salt:String(a),side:i,signature:t,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var Li=new Set(["https://clob.polymarket.com/order"]),Xe=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Zc=Object.freeze(Xe.map(e=>e[0])),Bi=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),Ci="0xe111180000d2663c0091e4f400237545b87b996b",Pi="0xe2222d279d744050d28e00520010520000310f59",Dr=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`poly: bounded ${r} required`);return e};function Ur(e){let r=String(e||"").replace(/\/$/,"");if(!Li.has(r))throw new Error("poly: submitTo must be the official Polymarket CLOB");return r}function jr(e){let r=W(e,"poly: exchange").toLowerCase();if(!Bi.has(r))throw new Error("poly: verifyingContract must be an official CTF Exchange");return r}function ye(e,r){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let t=e.artifact;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("poly: structured artifact required");let n=Dr(t.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(W(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(Ur(t.submitTo),t.chainId!==137)throw new Error("poly: chainId must be Polygon 137");let o=t.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(jr(o.verifyingContract),jr(t.exchange),W(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==W(t.exchange,"poly: exchange").toLowerCase())throw new Error("poly: exchange/domain mismatch");if(typeof t.negRisk!="boolean")throw new Error("poly: negRisk must be a boolean");let i=t.negRisk?Pi:Ci;if(W(t.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let a=t.message||t.value;if(!a||typeof a!="object")throw new Error("poly: signed order message required");let c=t.types?.Order;if(!Array.isArray(c)||c.length!==Xe.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let S=0;S<Xe.length;S+=1)if(c[S]?.name!==Xe[S][0]||c[S]?.type!==Xe[S][1])throw new Error("poly: EIP-712 Order type must be official CLOB v2");if((t.orderType||"GTC")!=="GTC")throw new Error("poly: only GTC is public");let u=String(e.owner||"").toLowerCase();if(W(a.maker,"poly: maker").toLowerCase()!==u)throw new Error("poly: maker must equal owner");if(W(a.signer,"poly: signer").toLowerCase()!==u)throw new Error("poly: signer must equal owner");if(a.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof a.builder!="string"||a.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(a.side!==0&&a.side!==1)throw new Error("poly: side must be BUY or SELL");let s=Dr(t.tokenId,"tokenId",80);if(W(a.tokenId,"poly: tokenId")!==s)throw new Error("poly: tokenId mismatch");let d=Array.isArray(r.polyTokens)?r.polyTokens.map(String):[];if(d.length&&!d.includes(s)&&!d.includes("*"))throw new Error("poly: tokenId not allowed");let l=Number(a.side)===0?"BUY":"SELL";if(t.side&&t.side!==l)throw new Error("poly: side mismatch");let f=V(a.makerAmount,"poly: makerAmount"),p=V(a.takerAmount,"poly: takerAmount"),w=V(t.makerAmount,"poly: prepared makerAmount"),y=V(t.takerAmount,"poly: prepared takerAmount");if(f!==w)throw new Error("poly: signed makerAmount differs from prepared envelope");if(p!==y)throw new Error("poly: signed takerAmount differs from prepared envelope");let h=l==="BUY"?f:p,m=l==="BUY"?p:f,b=P(t.quantity,6,"poly: quantity");if(b<=0n||b!==m)throw new Error("poly: quantity must match CLOB v2 amounts");let E=P(t.price,6,"poly: price");if(E<=0n||E>=1000000n)throw new Error("poly: price must be within (0,1)");if(m*E!==h*1000000n)throw new Error("poly: price must match CLOB v2 amounts");if(P(t.notionalUsdc,6,"poly: notionalUsdc")!==h)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let I=qr(a,l);if(P(I,6,"poly: displayed notionalUsdc")!==h)throw new Error("poly: displayed notionalUsdc must match CLOB v2 amounts");let k=r.maxNotionalUsd??r.maxNotionalUsdc;if(k!=null){let S=P(k,6,"poly: maxNotionalUsd");if(h>S)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:h.toString(),notional:h.toString(),fee:"0",kind:n,tokenId:s,side:l,makerAmount:f.toString(),takerAmount:p.toString(),price:String(t.price),quantity:String(t.quantity),notionalUsdc:I,submitTo:Ur(t.submitTo)})}var Ri=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),jt=14,Wr=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`lighter: bounded ${r} required`);return e};function Pe(e,r,t){if(!Number.isSafeInteger(e)||e!==r)throw new Error(`lighter: ${t} must be exact numeric ${r}`)}function Wt(e){let r=String(e||"").replace(/\/$/,"");if(!Ri.has(r))throw new Error("lighter: submitTo must be the official Lighter sendTx");return r}function Ee(e,r={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let t=e.artifact;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("lighter: structured artifact required");let n=Wr(t.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=Wt(t.submitTo),i=t.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=Number(Q(t.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: accountIndex required");let c=Number(Q(t.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(c)||c<0)throw new Error("lighter: clientOrderIndex required");Pe(t.orderType,0,"orderType"),Pe(t.timeInForce,1,"timeInForce"),Pe(t.reduceOnly,0,"reduceOnly"),Pe(t.triggerPrice,0,"triggerPrice"),Pe(t.orderExpiry,-1,"orderExpiry");let u=Wr(t.symbol||t.coin,"symbol",32),s=Array.isArray(r.lighterMarkets)?r.lighterMarkets.map(String):[];if(s.length&&!s.includes(u)&&!s.includes(String(i))&&!s.includes("*"))throw new Error("lighter: market not allowed");if(t.side!=="buy"&&t.side!=="sell")throw new Error("lighter: side must be buy or sell");let d=V(t.baseAmount,"lighter: baseAmount"),l=V(t.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),p=Number(l),w=Number(t.sizeDecimals??0),y=Number(t.priceDecimals??0);if(!Number.isInteger(w)||w<0||w>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(y)||y<0||y>12)throw new Error("lighter: priceDecimals required");let h=w+y,m=d*l,b=P(t.notionalUsd,h,"lighter: notionalUsd");if(b<=0n)throw new Error("lighter: notionalUsd required");if(m!==b)throw new Error("lighter: notionalUsd must match size and price");let E=P(r.maxNotionalUsd??Number.MAX_SAFE_INTEGER,h,"lighter: maxNotionalUsd");if(m>E)throw new Error("lighter: notional exceeds cap");let A=R(t.notionalUsd,"lighter: notionalUsd");return Pe(t.txType,jt,"txType"),Object.freeze({unit:"usd",value:String(A),notional:String(A),fee:"0",kind:n,symbol:u,marketIndex:i,side:t.side,baseAmount:f,price:p,submitTo:o,actionType:"create-order",amount:String(A)})}var Kr=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var Ht=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}),$i=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Yr=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"}}),Fi=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),ct=new Gr(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Hr=new Gr(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),_i=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,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`envelope: bounded ${r} required`);return e},v=(e,r)=>{try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`envelope: ${r} must be a non-negative integer`)}},Jr=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},qi=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${r} allowlist is empty`);return e},q=(e,r,t)=>{if(!qi(r,t).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${t} not allowed`)},Qe=(e,r,t)=>{Array.isArray(r)&&r.length&&q(e,r,t)},O=(e,r)=>{let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(t))throw new Error(`envelope: ${r} must be a 20-byte address`);return t},ke=e=>String(e||"0x").slice(0,10).toLowerCase(),Xr=e=>v(e.gasLimit,"gasLimit")*v(e.maxFeePerGas??e.gasPrice,"feePerGas")+v(e.l1FeeWei??0,"l1FeeWei")+v(e.operatorFeeWei??0,"operatorFeeWei");function Re(e,r,t,{dynamicTail:n=!1}={}){let o=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(o)||o.length<10+r*64)throw new Error(`envelope: malformed ${t} calldata`);if(!n&&o.length!==10+r*64)throw new Error(`envelope: malformed ${t} calldata`);return{hex:o,word:i=>o.slice(10+i*64,10+(i+1)*64)}}function D(e,r){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${r} address`);return`0x${e.slice(24)}`}function te(e,r){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${r} integer`)}}function Mi(e){if(ke(e)!=="0x095ea7b3")return null;let r=Re(e,2,"approval");return{kind:"approval",spender:D(r.word(0),"approval spender"),amount:te(r.word(1),"approval amount")}}function Qr(e,r){let t=r==="router02-exact-input-single"?7:8,n=Re(e,t,"Uniswap v3 exactInputSingle"),o=t===7?4:5;return{kind:"action",action:"swap",inputToken:D(n.word(0),"input token"),outputToken:D(n.word(1),"output token"),recipient:D(n.word(3),"recipient"),amountIn:te(n.word(o),"amountIn"),minimumOut:te(n.word(o+1),"amountOutMinimum")}}function Di(e){let r=Re(e,12,"Across depositV3",{dynamicTail:!0}),t=te(r.word(11),"message offset");if(t!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let n=10+Number(t)*2;if(r.hex.length<n+64)throw new Error("envelope: malformed Across depositV3 message");let o=Number(BigInt(`0x${r.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(r.hex.length!==n+64+i)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:D(r.word(0),"depositor"),recipient:D(r.word(1),"recipient"),inputToken:D(r.word(2),"input token"),outputToken:D(r.word(3),"output token"),amountIn:te(r.word(4),"inputAmount"),minimumOut:te(r.word(5),"outputAmount"),destinationChainId:te(r.word(6),"destinationChainId")}}function Ui(e){let r=String(e||"").replace(/^0x/i,"").toLowerCase();if(r.length<86||r.length%2!==0)throw new Error("envelope: malformed Uniswap path");let t=`0x${r.slice(0,40)}`,n=`0x${r.slice(r.length-40)}`;if(!/^0x[0-9a-f]{40}$/.test(t)||!/^0x[0-9a-f]{40}$/.test(n))throw new Error("envelope: malformed Uniswap path tokens");return{inputToken:t,outputToken:n}}function zr(e,{hasDeadline:r}){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<74)throw new Error("envelope: malformed exactInput calldata");let n=[];for(let h=10;h+64<=t.length;h+=64)n.push(t.slice(h,h+64));let o=(h,m)=>{if(!n[h])throw new Error(`envelope: malformed ${m}`);return BigInt(`0x${n[h]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let a=i/32,c=Number(o(a,"path offset")),u=n[a+1],s=o(a+(r?3:2),"amountIn"),d=o(a+(r?4:3),"amountOutMinimum"),l=a+c/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let f=Number(o(l,"path length")),p=t.slice(10+(l+1)*64,10+(l+1)*64+f*2),{inputToken:w,outputToken:y}=Ui(`0x${p}`);return{kind:"action",action:"swap",inputToken:w,outputToken:y,recipient:D(u,"recipient"),amountIn:s,minimumOut:d}}function ji(e){let r=Re(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:D(r.word(0),"input token"),outputToken:D(r.word(1),"output token"),recipient:D(r.word(3),"recipient"),amountIn:te(r.word(5),"amountIn"),minimumOut:te(r.word(6),"amountOutMinimum")}}function Wi(e){let r=String(e||"").toLowerCase();if(!r.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let t=[];for(let f=10;f+64<=r.length;f+=64)t.push(r.slice(f,f+64));let n=Number(BigInt(`0x${t[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${t[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let a=Number(BigInt(`0x${t[o+1]}`)),c=o+1+a/32,u=Number(BigInt(`0x${t[c]}`)),d=`0x${r.slice(10+(c+1)*64,10+(c+1)*64+u*2)}`,l=ke(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Qr(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function Hi(e,r){let t=ke(e),n=Yr[t];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(r).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{...Qr(e,n.layout),selector:t,provider:n.provider};if(n.layout==="exact-input-deadline")return{...zr(e,{hasDeadline:!0}),selector:t,provider:n.provider};if(n.layout==="exact-input")return{...zr(e,{hasDeadline:!1}),selector:t,provider:n.provider};if(n.layout==="multicall-deadline")return{...Wi(e),selector:t,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...ji(e),selector:t,provider:n.provider};if(n.action==="bridge")return{...Di(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Ji(e){let r=Re(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:D(r.word(0),"mint NFT contract"),feeRecipient:D(r.word(1),"mint fee recipient"),recipient:D(r.word(2),"mint recipient"),quantity:te(r.word(3),"mint quantity")}}function zi(e){let r;try{r=Hr.decodeFunctionData("mintAllowList",e)}catch{throw new Error("envelope: malformed SeaDrop mintAllowList calldata")}let t=r[4],n=[...r[5]].map(String);if(n.length<1||n.length>64||n.some(u=>!/^0x[0-9a-fA-F]{64}$/.test(u)))throw new Error("envelope: bounded canonical SeaDrop allowlist proof required");if(Hr.encodeFunctionData("mintAllowList",[r[0],r[1],r[2],r[3],t,n]).toLowerCase()!==String(e).toLowerCase())throw new Error("envelope: SeaDrop allowlist calldata must be canonical");let i=BigInt(t.startTime),a=BigInt(t.endTime);if(a<=i)throw new Error("envelope: SeaDrop allowlist stage time range is invalid");let c=BigInt(r[3]);if(BigInt(t.maxTotalMintableByWallet)<c)throw new Error("envelope: SeaDrop allowlist wallet cap is below quantity");return{kind:"mint",action:"mint",mintType:"allowlist",contract:O(r[0],"mint NFT contract"),feeRecipient:O(r[1],"mint fee recipient"),recipient:O(r[2],"mint recipient"),quantity:c,mintPrice:BigInt(t.mintPrice),startTime:i,endTime:a,dropStageIndex:BigInt(t.dropStageIndex),proof:n}}function Vi(e,r){let t=ke(e);if(String(r).toLowerCase()==="nft-mint")return Gi(e);let n=Fi[t];if(!n)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(String(r).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed NFT selector");if(n.layout==="seadrop-mint-public")return{...Ji(e),selector:t,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...zi(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function Gi(e){let r=ke(e);if(r==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let t=_i[r];if(!t)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(t.layout==="mint-no-args")return{kind:"mint",action:"mint",selector:r,provider:"nft-mint",quantity:1n};if(t.layout==="mint-quantity"){let n=Re(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:r,provider:"nft-mint",quantity:te(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function ut(e){let r=e?.artifact;if(Array.isArray(r?.transactions))return r.transactions;if(r?.transaction&&typeof r.transaction=="object")return[r.transaction];if(r?.data)return[r];throw new Error("envelope: ordered EVM transaction batch required")}function Zr(e,r,t,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=O(e.owner,"owner"),c=e.artifact,u=Number(c?.chainId??ut(e)[0]?.chainId);if(!Number.isSafeInteger(u)||u<=0)throw new Error("envelope: explicit batch chainId required");if(q(u,r.chains,"chain"),c?.owner!==void 0&&O(c.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let s=ut(e);if(!s.length||s.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,l=0n,f=0n;for(let p of s){if(!p||typeof p!="object"||Array.isArray(p))throw new Error("envelope: structured EVM transaction required");if(Number(p.chainId)!==u)throw new Error("envelope: every batch leg must use the same chain");if(O(p.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(q(ke(p.data),r.selectors,"selector"),d+=v(p.value??0,"value"),l+=v(p.gasLimit,"gasLimit"),f+=Xr(p),oe(u)&&(p.l1FeeWei===void 0||p.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>v(r.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>v(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(f>v(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:s,chainId:u,owner:a,totalValue:d,totalGas:l,totalFee:f}}function en(e,r,{nowMs:t=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();q(i,r.providers,"provider");let a=Zr(e,r,o,{nowMs:t}),c=[],u=-1;for(let w=0;w<a.transactions.length;w++){let y=a.transactions[w],h=Mi(y.data),m;if(h){if(u!==-1)throw new Error("envelope: approval must be before action");if(v(y.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let A=O(y.to,"approval token");if(q(A,r.tokens,"token"),q(h.spender,r.spenders,"spender"),h.amount>v(r.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");m={...h,token:A,index:w}}else{if(u!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");q(y.to,r.destinations,"destination"),m={...Hi(y.data,i),target:O(y.to,"action target"),index:w},u=w}let b=v(y.value??0,"value"),E=v(y.gasLimit,"gasLimit");c.push({...m,value:b,gas:E,fee:Xr(y)})}if(u<0)throw new Error("envelope: reviewed swap/bridge action required");let s=c[u],d=o==="evm-swap"?"swap":"bridge";if(s.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if(O(e.destination,"destination")!==s.target)throw new Error("envelope: destination must equal decoded action target");if(s.recipient!==a.owner)throw new Error("envelope: decoded recipient must equal owner");if(s.depositor&&s.depositor!==a.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(q(s.inputToken,r.tokens,"input token"),q(s.outputToken,r.tokens,"output token"),s.amountIn<=0n||s.amountIn>v(r.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(s.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(Tt(e.autoSlippage,{nowMs:t,chainId:a.chainId,venue:i,tx:a.transactions[u],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(s.minimumOut!==v(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(s.action==="bridge"&&v(e.toChainId,"toChainId")!==s.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=c.filter(w=>w.kind==="approval");if(!new Set([...$i,...Array.isArray(r.nativeInputTokens)?r.nativeInputTokens.map(w=>String(w).toLowerCase()):[]]).has(s.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(s.value!==s.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let p=Object.freeze({quoteAmountOut:v(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:v(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...a,decoded:c,action:s,provider:i,authenticatedQuote:p}}function Ki(e,r,{nowMs:t}){let n=e.anvilAttestation,o=e.artifact?.anvilAttestation;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("envelope: Anvil attestation is required");if(!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: Anvil attestation artifact mismatch");if(Number(n.version)!==1||n.source!=="anvil-snapshot-rpc-reviewed-runtime")throw new Error("envelope: unsupported Anvil attestation");if(Number(n.chainId)!==4663)throw new Error("envelope: Anvil attestation chain mismatch");let i=O(e.destination,"Anvil market"),a=O(e.contract,"NFT contract"),c=O(e.paymentToken,"payment token");if(O(n.market,"attested Anvil market")!==i)throw new Error("envelope: Anvil attestation market mismatch");if(O(n.collection,"attested NFT collection")!==a)throw new Error("envelope: Anvil attestation collection mismatch");if(O(n.paymentToken,"attested payment token")!==c)throw new Error("envelope: Anvil attestation payment token mismatch");let u=Number(e.paymentTokenDecimals??e.artifact?.paymentTokenDecimals);if(!Number.isSafeInteger(u)||u<0||u>255||Number(n.paymentTokenDecimals)!==u)throw new Error("envelope: Anvil payment token decimals mismatch");let s=v(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei").toString();if(v(n.nativeSwapFeeWei,"attested nativeSwapFeeWei").toString()!==s)throw new Error("envelope: Anvil attestation native swap fee mismatch");let d=Number(n.snapshotFetchedAtMs),l=Number(n.snapshotExpiresAtMs);if(!Number.isFinite(d)||!Number.isFinite(l)||d>t||l<=t||l<=d)throw new Error("envelope: Anvil snapshot attestation is stale");let f=v(n.blockNumber,"attested blockNumber");if(f<=0n||!/^0x[0-9a-f]{64}$/.test(String(n.blockHash||"").toLowerCase()))throw new Error("envelope: Anvil block attestation is invalid");let p=String(n.runtimeCodeHash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(p))throw new Error("envelope: Anvil runtime code hash is invalid");let w=Object.entries(r.anvilRuntimeCodeHashes||{}).find(([h])=>h.toLowerCase()===i)?.[1];if(!w||String(w).toLowerCase()!==p)throw new Error("policy: Anvil runtime code hash is not reviewed");let y=Object.entries(r.nftPaymentTokenCaps||{}).find(([h])=>h.toLowerCase()===c)?.[1];if(!y||Number(y.decimals)!==u)throw new Error("policy: Anvil payment token decimals are not reviewed");return Object.freeze({...n,market:i,collection:a,paymentToken:c,paymentTokenDecimals:u,runtimeCodeHash:p,blockNumber:f})}function Vr(e,r){let t=e.artifact,n=e.anvilQuote,o=t?.anvilQuote;if(!n||typeof n!="object"||Array.isArray(n)||!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: exact Anvil quote artifact mismatch");if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("envelope: exact Anvil quote confirmation required");let i=r==="buy"?[[n.totalCostRaw,"anvilQuote.totalCostRaw"],[e.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw"],[t?.maxPaymentTokenAmountRaw,"artifact maxPaymentTokenAmountRaw"],[e.exactQuoteTotalCostRaw,"exactQuoteTotalCostRaw"],[t?.exactQuoteTotalCostRaw,"artifact exactQuoteTotalCostRaw"],[e.preconditions?.confirmedTotalCostRaw,"confirmedTotalCostRaw"]]:[[n.netPayoutRaw,"anvilQuote.netPayoutRaw"],[e.minPayoutRaw,"minPayoutRaw"],[t?.minPayoutRaw,"artifact minPayoutRaw"],[e.exactQuoteNetPayoutRaw,"exactQuoteNetPayoutRaw"],[t?.exactQuoteNetPayoutRaw,"artifact exactQuoteNetPayoutRaw"],[e.preconditions?.confirmedNetPayoutRaw,"confirmedNetPayoutRaw"]],a=v(i[0][0],i[0][1]);for(let[c,u]of i.slice(1))if(v(c,u)!==a)throw new Error(`envelope: Anvil ${r} exact settlement limit mismatch`);return a}function tn(e,r,{nowMs:t=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint or NFT action");let n=Ze(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Qe(n,r.providers,"provider");let o=Zr(e,r,"evm-nft",{nowMs:t});if(n==="anvil-nft"){if(e.action!=="nft")throw new Error("envelope: Anvil requires NFT action");if(o.chainId!==4663)throw new Error("envelope: Anvil requires chain 4663");if(r.confirmationMode!=="exact-human")throw new Error("policy: Anvil requires exact-human confirmation");if(o.transactions.length!==1)throw new Error("envelope: Anvil requires one atomic action with pre-existing approval");if(Number(e.slippageBps)!==0)throw new Error("envelope: Anvil exact limit requires zero slippageBps");let[p]=o.transactions,w=O(e.destination,"Anvil market");if(O(p.to,"Anvil action target")!==w)throw new Error("envelope: Anvil action target mismatch");q(w,r.destinations,"destination");let y=O(e.contract??e.artifact?.contract,"NFT contract");if(Qe(y,r.nftContracts,"NFT contract"),O(e.marketCollection??e.artifact?.marketCollection,"Anvil market collection")!==y)throw new Error("envelope: Anvil market collection mismatch");let m=O(e.paymentToken??e.artifact?.paymentToken,"payment token");Qe(m,r.erc20Tokens,"ERC20 token");let b=Ki(e,r,{nowMs:t}),E=v(e.tokenId??e.artifact?.tokenId,"tokenId"),A=v(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei");if(o.totalValue!==A||v(p.value??0,"Anvil action value")!==A)throw new Error("envelope: Anvil native swap fee mismatch");if(A>v(r.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"))throw new Error("policy: Anvil native swap fee exceeds cap");let I=Ze(e.nftAction,"nftAction",8).toLowerCase(),k;if(I==="buy"){let S=Vr(e,I),B=Object.entries(r.nftPaymentTokenCaps||{}).find(([me])=>me.toLowerCase()===m)?.[1];if(!B)throw new Error("policy: Anvil payment-token cap required");if(S>v(B.maxPerTradeRaw,"maxPerTradeRaw"))throw new Error("policy: Anvil payment amount exceeds cap");if(e.preconditions?.allowanceVerified!==!0||v(e.preconditions?.allowanceRaw,"allowanceRaw")<S)throw new Error("envelope: Anvil pre-existing allowance proof required");let F=ct.decodeFunctionData("buySpecificNFT",p.data);if(ct.encodeFunctionData("buySpecificNFT",[F[0],F[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil buy calldata");if(BigInt(F[0])!==E)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(F[1])!==S)throw new Error("envelope: Anvil maxCost mismatch");k={kind:"nft",action:"buy",tokenId:E,maxPaymentTokenAmountRaw:S,target:w}}else if(I==="sell"){let S=e.preconditions||{},B=O(S.approvedAddress,"NFT approval address");if(S.nftApprovalVerified!==!0||B!==w&&S.approvedForAll!==!0)throw new Error("envelope: Anvil pre-existing NFT approval proof required");let F=Vr(e,I),z=ct.decodeFunctionData("sellNFT",p.data);if(ct.encodeFunctionData("sellNFT",[z[0],z[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil sell calldata");if(BigInt(z[0])!==E)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(z[1])!==F)throw new Error("envelope: Anvil minPayout mismatch");k={kind:"nft",action:"sell",tokenId:E,minPayoutRaw:F,target:w}}else throw new Error("envelope: unsupported Anvil NFT action");return{...o,provider:n,nftAction:I,tokenId:E,paymentToken:m,paymentTokenDecimals:b.paymentTokenDecimals,anvilAttestation:b,decoded:[k]}}let i=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;if(i?.oraclePrepared===!0&&Er(i,{nowMs:t,providers:Array.isArray(r.providers)&&r.providers.length?r.providers:null,kinds:["nft-mint"],label:"local-signer"}),o.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let a=o.transactions[0],c=ke(a.data);q(c,r.selectors,"selector"),q(a.to,r.destinations,"destination");let u=Vi(a.data,n),s=O(e.contract??e.artifact?.contract,"NFT contract");if(Qe(s,r.nftContracts,"NFT contract"),(u.contract||O(a.to,"NFT contract"))!==s)throw new Error("envelope: mint calldata NFT contract mismatch");if(u.recipient&&u.recipient!==o.owner)throw new Error("envelope: mint calldata recipient mismatch");u.feeRecipient&&Qe(u.feeRecipient,r.nftFeeRecipients,"mint fee recipient");let l=v(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>v(r.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(u.quantity!==l)throw new Error("envelope: mint calldata quantity mismatch");let f=v(e.totalWei??e.artifact?.totalWei,"totalWei");if(o.totalValue!==f)throw new Error("envelope: mint value does not match declared totalWei");if(u.mintType==="allowlist"){let p=BigInt(Math.floor(t/1e3));if(u.startTime>p||u.endTime<=p)throw new Error("policy: SeaDrop allowlist stage is not open");if(u.mintPrice*l!==f)throw new Error("envelope: SeaDrop allowlist price does not match declared totalWei")}if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&v(e.priceWei??e.artifact.priceWei,"priceWei")*l!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>v(r.maxMintTotalWei??r.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...o,provider:n,decoded:[{...u,target:O(a.to,"mint target"),value:o.totalValue,gas:o.totalGas,fee:o.totalFee}]}}function Yi(e,{localsWaiver:r=!1}={}){if(!(e in Ht))throw new Error("fee: unknown action");return r?0:Ht[e]}function lt(e,r,{nowMs:t=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:a=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let c=Ze(e.surface,"surface",16);if(!Kr.has(c))throw new Error("envelope: unsupported public surface");let u=Ze(e.action,"action",32);q(c,r.surfaces,"surface"),q(u,r.actions,"action"),q(e.owner,r.owners,"owner"),q(e.destination,r.destinations,"destination");let s=Jr(r.maxTtlMs,"maxTtlMs"),d=Jr(r.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=t||e.expiresAtMs-t>s)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(c==="evm-swap"||c==="evm-bridge")en(e,r,{nowMs:t,routeAttestationSecret:o});else if(c==="evm-nft")tn(e,r,{nowMs:t});else if(c==="evm"){if(!["transfer","approve"].includes(u))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(u==="swap"||u==="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");it({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},r,{nowMs:t,networkFees:i,requireNetworkFees:a});let w=String(l.data||"0x").toLowerCase(),y=v(l.value,"EVM value");if(w==="0x"){if(y===0n)throw new Error("envelope: native EVM transfer value required")}else if(ne(w)){if(y!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else c==="btc"?Ct(e,r):c==="sol"?qt(e,r):c==="hl"?ge(e,r):c==="poly"?ye(e,r):c==="lighter"&&Ee(e,r);let f=Number(e.fee?.oracleFeeBps)===0&&Ht[u]!==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 p=Yi(u,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==p)throw new Error("fee: final artifact fee mismatch");return!0}var Jt=Object.freeze([...Kr]),pu=Object.freeze({...Yr});function zt(e,r){if(e.surface==="hl")return ge(e,r);if(e.surface==="poly")return ye(e,r);if(e.surface==="lighter")return Ee(e,r);if(e.surface==="btc")return Ct(e,r);if(e.surface==="sol")return qt(e,r);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let t=en(e,r,{nowMs:Math.max(0,Number(e.expiresAtMs)-1),routeAttestationSecret:r.routeAttestationSecret}),n=t.totalValue.toString(),o=t.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(t.totalValue+t.totalFee).toString(),fee:o})}if(e.surface==="evm-nft"){let t=tn(e,r,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=t.totalFee.toString();if(t.provider==="anvil-nft"&&t.nftAction==="buy"){let i=v(e.maxPaymentTokenAmountRaw??e.artifact?.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw").toString(),a=t.totalValue.toString(),c=t.totalFee,u=[{unit:`erc20:${t.paymentToken}`,value:i,notional:i,fee:"0"},{unit:"wei",value:a,notional:(t.totalValue+c).toString(),fee:c.toString()}].sort((s,d)=>s.unit<d.unit?-1:s.unit>d.unit?1:0);return Object.freeze({units:u})}let o=t.totalValue.toString();return Object.freeze({unit:"wei",value:o,notional:(t.totalValue+t.totalFee).toString(),fee:n})}if(String(e.surface).startsWith("evm")){let t=v(e.artifact?.value,"EVM value"),n=v(e.artifact?.gasLimit,"EVM gasLimit"),o=v(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+v(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+v(e.artifact?.operatorFeeWei??0,"EVM operatorFeeWei");return Object.freeze({unit:"wei",value:t.toString(),notional:(t+i).toString(),fee:i.toString()})}throw new Error("envelope: unsupported public surface")}function rn(e={}){let r={};for(let t of Jt){let n=e[t];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${t} requires simulate, sign, and broadcast functions`);r[t]=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(r)}function dt(e,r){let t=e?.surface||"evm",n=r?.[t];if(!n)throw new Error(`adapter: ${t} is not configured on this self-host`);return n}import{createHash as ln}from"node:crypto";import{ed25519 as sa}from"@noble/curves/ed25519.js";import{base58 as mn}from"@scure/base";import{RawTx as Yt,SigHash as Te,Transaction as Xt}from"@scure/btc-signer";import{Transaction as Qt,keccak256 as dn,verifyTypedData as fn}from"ethers";import{encode as Xi}from"@msgpack/msgpack";import{keccak256 as Qi,verifyTypedData as Zi}from"ethers";var $e=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Vt=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function nn(e){let r=BigInt(e);if(r<0n||r>=2n**64n)throw new Error("hl-l1: nonce must fit uint64");let t=Buffer.alloc(8);return t.writeBigUInt64BE(r),t}function ea(e,r,{vaultAddress:t=null,expiresAfter:n=null}={}){let i=[Buffer.from(Xi(e)),nn(r)];if(t){let a=String(t).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]),nn(n)),Qi(Buffer.concat(i))}function Gt(e,r,{isMainnet:t=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:t?"a":"b",connectionId:ea(e,r,{vaultAddress:n,expiresAfter:o})}}function on(e){let r=e?.typedData;if(r==null)return null;if(typeof r!="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 t=Gt(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(r.domain?.name!==$e.name||String(r.domain?.version)!==$e.version||Number(r.domain?.chainId)!==$e.chainId||String(r.domain?.verifyingContract||"").toLowerCase()!==String($e.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(r.types?.Agent||[])!==JSON.stringify(Vt.Agent))throw new Error("hl-l1: typedData types must be Hyperliquid Agent");if(r.message?.source!==t.source||String(r.message?.connectionId||"").toLowerCase()!==String(t.connectionId).toLowerCase())throw new Error("hl-l1: typedData message must hash the validated action");return t}async function an({wallet:e,action:r,nonce:t,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let a=Gt(r,t,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData($e,Vt,a)}function sn({signature:e,action:r,nonce:t,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:a=null}){try{let c=Gt(r,t,{isMainnet:n,vaultAddress:i,expiresAfter:a}),u=Zi($e,Vt,c,e);return String(u).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var ta=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function Kt(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 r of e)Kt(r);return}for(let r of Object.values(e))Kt(r)}}}function ra(e){if(typeof e=="string"){if(!e.startsWith("{"))throw new Error("lighter: official signed tx_info JSON required");let r=JSON.parse(e);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("lighter: official signed tx_info JSON required");return r}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("lighter: official signed tx_info JSON required");return Kt(e),JSON.parse(JSON.stringify(e))}function ft(e,r){let t=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^(0|[1-9][0-9]*)$/.test(t))throw new Error(`lighter: ${r} must be an integer`);let n=BigInt(t);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`lighter: ${r} exceeds safe integer`);return n}function na(e,r){let t=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^-?(0|[1-9][0-9]*)$/.test(t))throw new Error(`lighter: ${r} must be an integer`);let n=BigInt(t);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`lighter: ${r} exceeds safe integer`);return n}function cn(e,r,{signed:t=!1}={}){if(typeof e!="number"||!Number.isSafeInteger(e)||!t&&e<0)throw new Error(`lighter: signed ${r} must be an exact numeric integer`);return e}function _e(e,r,t,n={}){let o=r.filter(a=>e[a]!==void 0&&e[a]!==null);if(o.length===0)throw new Error(`lighter: ${t} required`);let i=o.map(a=>cn(e[a],t,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${t}`);return i[0]}function oa(e,r,t){let n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length===0)throw new Error(`lighter: ${t} required`);let o=n.map(i=>String(e[i]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${t}`);return e[n[0]]}function Fe(e,r,t,n){let o=_e(e,r,n);if(BigInt(o)!==ft(t,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function ia(e,r,t,n){let o=_e(e,r,n,{signed:!0});if(BigInt(o)!==na(t,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function aa(e){let r={};for(let[t,n]of ta.entries()){let o=n.filter(a=>e[a]!==void 0&&e[a]!==null);if(!o.length)continue;let i=o.map(a=>{let c=e[a];if(t<3)return cn(c,n[0]);if(typeof c!="string"||c.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return c});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);r[n[0]]=i[0]}return r}function et(e,r){let t=ra(r),n=Fe(t,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=Fe(t,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=Fe(t,["Type","type"],e.orderType,"Type"),a=Fe(t,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),c=Fe(t,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),u=Fe(t,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),s=ia(t,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=_e(t,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=_e(t,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),f=_e(t,["Price","price"],"Price");if(BigInt(d)!==ft(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==ft(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==ft(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let p=oa(t,["IsAsk","is_ask","isAsk"],"IsAsk");if(typeof p!="number"||p!==0&&p!==1)throw new Error("lighter: signed IsAsk must be exact numeric 0 or 1");let w=p===1,y=e.side==="sell";if(w!==y)throw new Error("lighter: signed IsAsk must match the prepared side");let h=_e(t,["txType","tx_type","TxType"],"txType");if(h!==jt)throw new Error("lighter: signed txType must be official create-order");let m={...aa(t),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:a,ReduceOnly:c,TriggerPrice:u,OrderExpiry:s,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(f),IsAsk:w?1:0,txType:h},b=JSON.stringify(m),E=JSON.parse(b);if(E.MarketIndex!==Number(d)||E.BaseAmount!==Number(l)||E.Price!==Number(f)||E.IsAsk!==(w?1:0)||E.txType!==h)throw new Error("lighter: canonical tx_info mutated");return{txType:h,txInfo:b,submitTo:Wt(e.submitTo)}}function un(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var qe=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 r=Buffer.from(e,"base64");return r.toString("base64")===e?r:null},pt=e=>String(e||"").toLowerCase();function ca(e,r){if(typeof e!="string")return!1;let t,n;try{t=Qt.from(e),n=Qt.from({chainId:r.chainId,to:r.to,data:r.data,value:r.value,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce,type:r.type,accessList:r.accessList})}catch{return!1}return pt(t.from)!==pt(r.from)||pt(t.to)!==pt(r.to)?!1:t.unsignedHash===n.unsignedHash}function ua(e){let r=Buffer.from(Yt.encode(e)),t=ln("sha256").update(r).digest();return Buffer.from(ln("sha256").update(t).digest()).reverse().toString("hex")}function pn(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||ua(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))return!1;let r=e.nonWitnessUtxo.outputs?.[e.index];return r?BigInt(e.witnessUtxo.amount)===BigInt(r.amount)&&Buffer.from(e.witnessUtxo.script||[]).equals(Buffer.from(r.script||[])):!1}function la(e,r){let t=qe(e),n=qe(r.psbt);if(!t||!n)return!1;try{let o=Xt.fromPSBT(n),i=Xt.fromPSBT(t);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 c=i.getInput(a),u=o.getInput(a);if(!pn(u)||!pn(c))return!1;let s=(m,b)=>{if(m==null&&b==null)return!0;if(m==null||b==null)return!1;try{return Buffer.from(m).equals(Buffer.from(b))}catch{return!1}},d=(m,b)=>{if(m==null&&b==null)return!0;if(m==null||b==null)return!1;try{return Buffer.from(Yt.encode(m)).equals(Buffer.from(Yt.encode(b)))}catch{return s(m,b)}};if(!!c.witnessUtxo!=!!u.witnessUtxo||c.witnessUtxo&&(BigInt(c.witnessUtxo.amount)!==BigInt(u.witnessUtxo.amount)||!s(c.witnessUtxo.script,u.witnessUtxo.script))||!d(c.nonWitnessUtxo,u.nonWitnessUtxo)||!s(c.redeemScript,u.redeemScript)||!s(c.witnessScript,u.witnessScript)||c.sighashType!==void 0&&c.sighashType!==Te.DEFAULT&&c.sighashType!==Te.ALL)return!1;let l=m=>!(m instanceof Uint8Array)||m.length<9?!1:m[m.length-1]===Te.ALL,f=m=>m instanceof Uint8Array?m.length===64?!0:m.length===65&&m[64]===Te.ALL:!1;for(let m of c.partialSig||[]){let b=Array.isArray(m)?m[1]:m;if(!l(b))return!1}if(c.tapKeySig&&!f(c.tapKeySig))return!1;for(let m of c.tapScriptSig||[]){let b=Array.isArray(m)?m[1]:m;if(!f(b))return!1}let p=m=>m[m.length-1]===Te.ALL,w=m=>m.length>=9&&m.length<=73&&m[1]===m.length-3&&m[2]===2,y=m=>{let b=!1;for(let E of m)if(E instanceof Uint8Array){if(E[0]===48){if(!w(E)||!p(E))return!1;b=!0;continue}if(E.length===64){b=!0;continue}if(E.length===65){if(E[64]!==Te.ALL&&E[64]!==Te.DEFAULT)return!1;b=!0}}return b};if(c.finalScriptWitness){let m;if(Array.isArray(c.finalScriptWitness))m=c.finalScriptWitness;else if(c.finalScriptWitness instanceof Uint8Array){let b=c.finalScriptWitness,E=k=>{let S=b[k];return S===void 0?null:S<253?{value:S,next:k+1}:S===253?{value:b[k+1]|b[k+2]<<8,next:k+3}:null},A=E(0);if(!A)return!1;m=[];let I=A.next;for(let k=0;k<A.value;k++){let S=E(I);if(!S||I+S.value>b.length)return!1;m.push(b.slice(S.next,S.next+S.value)),I=S.next+S.value}if(I!==b.length)return!1}else return!1;if(!m.length||!y(m))return!1}if(c.finalScriptSig instanceof Uint8Array&&c.finalScriptSig.length){let m=c.finalScriptSig,b=[],E=0;for(;E<m.length;){let A=m[E];if(A>=1&&A<=75){if(E+1+A>m.length)return!1;b.push(m.slice(E+1,E+1+A)),E+=1+A;continue}if(A===76){let I=m[E+1];if(I===void 0||E+2+I>m.length)return!1;b.push(m.slice(E+2,E+2+I)),E+=2+I;continue}return!1}if(!b.length||!y(b))return!1}if(![c.partialSig,c.tapKeySig,c.tapScriptSig,c.finalScriptSig,c.finalScriptWitness].some(m=>Array.isArray(m)||m instanceof Uint8Array?m.length>0:m!=null))return!1}return!0}catch{return!1}}function wn(e){let r=0,t=0,n=0;for(;n<e.length&&n<3;){let o=e[n++];if(r|=(o&127)<<t,(o&128)===0)return{value:r,offset:n};t+=7}return null}function da(e,r,t){let n=qe(e),o=qe(r.messageBase64);if(!n||!o)return!1;let i=wn(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let c=n.subarray(i.offset,a),u=n.subarray(a);if(!u.equals(o))return!1;try{let s=mn.decode(String(t));return s.length===32&&sa.verify(c,u,s)}catch{return!1}}function hn(e,r,t,n){if(String(e).startsWith("evm"))return ca(r,t);if(e==="btc")return la(r,t);if(e==="sol")return da(r,t,n?.owner);if(e==="hl"){if(t?.typedData?.domain&&t.typedData.types&&t.typedData.message)try{return String(fn(t.typedData.domain,t.typedData.types,t.typedData.message,r)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return sn({signature:r,action:t?.action,nonce:t?.nonce,isMainnet:!String(t?.submitTo||"").includes("testnet"),owner:n?.owner})}if(e==="poly"&&t?.domain&&t.types&&t.message)try{return String(fn(t.domain,t.types,t.message,r)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return et(t,r),!0}catch{return!1}return!1}function gn(e,r){try{if(String(e).startsWith("evm"))return Qt.from(r).hash;if(e==="btc"){let t=qe(r);if(!t)return null;let n=Xt.fromPSBT(t);return n.finalize(),n.extract(),n.id}if(e==="sol"){let t=qe(r);if(!t)return null;let n=wn(t);if(!n||n.value!==1)return null;let o=t.subarray(n.offset,n.offset+64);return o.length===64?mn.encode(o):null}if(e==="hl"&&typeof r=="string"&&r.startsWith("0x"))return dn(r);if(e==="poly"&&typeof r=="string"&&r.startsWith("0x"))return dn(r)}catch{}return null}var wa=e=>String(e||"").toLowerCase();function X(e){return fa("sha256").update(JSON.stringify(e)).digest("hex")}function er(e,r,t={}){return it(e,r,t)}async function ha(e,r={}){if(!oe(e?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(typeof r.estimateNetworkFees!="function")throw new Error("policy: rollup fee estimate required");let t=await r.estimateNetworkFees(e);if(!t||t.l1FeeWei===void 0||t.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");return{l1FeeWei:String(t.l1FeeWei),operatorFeeWei:String(t.operatorFeeWei)}}function En(e,r,t=!1){if(!oe(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(t||r!=null){if(!r||r.l1FeeWei===void 0||r.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let n=BigInt(e.l1FeeWei)+BigInt(e.operatorFeeWei),o=BigInt(r.l1FeeWei)+BigInt(r.operatorFeeWei);if(n<o)throw new Error("policy: rollup fee attestation understates estimate")}return!0}var mt=class{#e=new Map;constructor({now:r=Date.now}={}){this.now=r}issue({artifact:r,owner:t,ttlMs:n=6e4}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=pa(32).toString("hex");return this.#e.set(o,{digest:X(r),owner:wa(t),expiresAtMs:this.now()+n}),o}consume(r,t){let n=this.#e.get(String(r));if(!n)throw new Error("confirmation: used or unknown nonce");if(n.expiresAtMs<=this.now())throw this.#e.delete(String(r)),new Error("confirmation: expired nonce");let o=Buffer.from(n.digest,"hex"),i=Buffer.from(X(t),"hex");if(!ma(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(r)),n}clear(){this.#e.clear()}};function ga(e){let r=String(e?.data||"0x").toLowerCase(),t=BigInt(e?.value??0);if(r==="0x"){if(t<=0n)throw new Error("signer: native EVM transfer value required");return!0}if(ne(r)){if(t!==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 ya(e={},r={}){let t={};for(let n of new Set([...Object.keys(e||{}),...Object.keys(r||{})]))t[n]=(BigInt(r?.[n]??0)-BigInt(e?.[n]??0)).toString();return t}function wt(e,r){let t=String(r||"");if(String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(t);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(t);if(e==="sol")try{let n=yn.decode(t);return n.length===64&&yn.encode(n)===t}catch{return!1}return e==="hl"?/^0x[0-9a-fA-F]{64}$/.test(t):e==="poly"?/^0x[0-9a-fA-F]{64}$/.test(t):!1}function bn(e,r,t){return!wt(e,r)||!wt(e,t)?!1:e==="sol"?String(r)===String(t):String(r).toLowerCase()===String(t).toLowerCase()}function Ea(e){let r=e?.confirmationMode;if(r!=="exact-human"&&r!=="auto-within-rails")throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");return r}async function Zt({artifact:e,envelope:r,nonce:t,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:c}){let u=Ea(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(u!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(r?.triggerAttestation,e,c())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(u!=="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(t,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=c())throw new Error("confirmation: expired nonce");return i}function ba(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function xa(e,r){return e&&ba(e.surface)?ut(e):[r]}function Sa(e,r){let t=e?.hash??null,n=e?.transactionHash??null;if(t!=null&&n!=null&&!bn(r,t,n))throw new Error("signer: receipt reports conflicting transaction hashes");return t||n||null}function Aa(e,r){let t=e?.verifiedBefore??e?.before,n=e?.verifiedAfter??e?.after;return{transactionHash:r,status:e?.status,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:ya(t,n)}}async function xn(e,r,t){if(!t.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:h,...m}=e||{};return m})(),i=xa(n,o),a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=()=>typeof t.nowMs=="function"?t.nowMs():t.nowMs??Date.now(),u=await Zt({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:null,consumeNonce:!0,nowMs:c}),s=X(e),d=(h={})=>{n?lt(n,a,h):(er(o,a,{nowMs:h.nowMs,networkFees:h.networkFees,requireNetworkFees:h.requireNetworkFees}),ga(o))},l=async h=>{let m=n&&!String(n.surface||"").startsWith("evm")?void 0:await ha(h,t);return{nowMs:c(),verifyFeeWaiver:t.verifyFeeWaiver,routeAttestationSecret:t.routeAttestationSecret,networkFees:m,requireNetworkFees:oe(h?.chainId)}};d({nowMs:c(),verifyFeeWaiver:t.verifyFeeWaiver,routeAttestationSecret:t.routeAttestationSecret});for(let h of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof t[h]!="function")throw new Error(`signer: ${h} is required`);let f=t.reserveLedger(n||e,a);if(!f)throw new Error("signer: ledger reservation required");let p=!1,w=[];try{for(let h of i){if(typeof t.simulate!="function"||await t.simulate(h,n)!==!0)throw new Error("signer: strict affirmative simulation required");let m=await l(h);if(En(h,m.networkFees,m.requireNetworkFees),!t.isArmed())throw new Error("signer: disarmed before signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,u=await Zt({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:u,consumeNonce:!1,nowMs:c}),d(m),t.validateReservation(f,a,n&&typeof t.decodeEconomics=="function"?t.decodeEconomics(n,a):void 0),p=!0;let b=await t.sign(h,n);if(typeof t.verifySigned!="function"||await t.verifySigned(b,h,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!t.isArmed())throw new Error("signer: disarmed before broadcast");if(X(e)!==s)throw new Error("signer: artifact mutated after signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,u=await Zt({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:u,consumeNonce:!1,nowMs:c});let E=await l(h);En(h,E.networkFees,E.requireNetworkFees),d(E),t.validateReservation(f,a,n&&typeof t.decodeEconomics=="function"?t.decodeEconomics(n,a):void 0);let A=await t.broadcast(b,h,n),I=A?.status,k=n?.surface||"evm",S=Sa(A,k),B=gn(k,b);if(!bn(k,S,B))throw new Error("signer: receipt transaction hash does not match signed bytes");if(I===0||I==="0x0")throw wt(k,S)?(t.settleFailedLedger(f),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(!wt(k,S))throw new Error("signer: successful broadcast requires a valid transaction hash");w.push(Aa(A,S))}}catch(h){throw p||t.releaseLedger(f),h}if(t.commitLedger(f),w.length===1){let h={receipt:w[0]};return n?.surface==="evm-bridge"&&(h.originStatus="success",h.destinationStatus="unverified",h.destinationSuccess=!1,h.note="Origin-chain receipts do not prove destination-chain settlement."),h}let y={receipts:w,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 Sn=new Set(["127.0.0.1","::1","localhost"]),ka=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&Ia(t,n)},U=(e,r,t)=>{let n=JSON.stringify(t);e.writeHead(r,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function Ta(e){let r=String(e||"");if(r.startsWith("[")){let t=r.indexOf("]");if(t>1)return r.slice(1,t)}return r.split(":")[0]}var An=e=>new Promise((r,t)=>{let n=0,o=[],i=!1;e.on("data",a=>{n+=a.length,n>64*1024&&!i?(i=!0,t(new Error("request refused")),e.resume()):i||o.push(a)}),e.on("end",()=>{if(!i)try{r(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{t(new Error("request refused"))}}),e.on("error",t)});function vn(e={}){let r=e.host||"127.0.0.1";if(!Sn.has(r))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 t=e.confirmations||new mt,n=e.origin||`http://${r}`;return va.createServer(async(i,a)=>{try{let c=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!ka(c,e.token))return U(a,401,{error:"unauthorized"});let u=Ta(i.headers.host);if(!Sn.has(u))return U(a,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return U(a,403,{error:"origin refused"});if(i.method==="GET"&&i.url==="/status"){let s=typeof e.readPolicy=="function"?e.readPolicy():e.policy,d=new Set(Jt),l=Array.isArray(s?.surfaces)?s.surfaces.filter(f=>typeof f=="string"&&d.has(f)):[];return U(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(),t.clear(),U(a,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return U(a,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return U(a,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return U(a,403,{error:"autonomous signer does not issue human confirmation nonces"});let s=await An(i),d=X(s.artifact),l=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(l?.confirmationMode!=="exact-human")return U(a,403,{error:"exact-human policy required"});let f=typeof e.nowMs=="function"?e.nowMs():Date.now();if(s.artifact?.version===1&&s.artifact?.surface)lt(s.artifact,l,{nowMs:f,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:p,...w}=s.artifact||{};er(w,l,{nowMs:f})}return typeof e.confirmArtifact!="function"?U(a,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(s.artifact,d,l)!==!0?U(a,400,{error:"exact human confirmation refused"}):U(a,200,{confirmationNonce:t.issue({artifact:s.artifact,owner:s.artifact?.owner??s.artifact?.from,ttlMs:s.ttlMs})})}if(i.method==="POST"&&i.url==="/execute"){let s=await An(i),d=await xn(s.artifact,s.confirmationNonce,{...e,confirmations:t});return U(a,200,d)}return U(a,404,{error:"not found"})}catch(c){return e.onError?.(String(c?.message||c)),U(a,400,{error:"request refused"})}})}import{createCipheriv as Uu,createDecipheriv as Na,randomBytes as Oa,scryptSync as La}from"node:crypto";import L from"node:fs";import Me from"node:path";var Ba="ORACLE-LOCAL-VAULT",Ca=1,gt=Object.freeze({N:1<<17,r:8,p:1}),Pa=256*1024*1024,Ra=16*1024;function ht(e,r,t,{max:n=r}={}){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 ${t} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<r||o.length>n)throw new Error(`local-vault: invalid ${t} length`);return o}function $a(e,r,t=gt){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return La(n,r,32,{...t,maxmem:Pa})}function In(e,r){if(e?.magic!==Ba||e?.version!==Ca)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!==gt.N||e.kdf.r!==gt.r||e.kdf.p!==gt.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 t=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(l=>!t.includes(l)))throw new Error("local-vault: unexpected vault field");let n=ht(e.kdf.salt,32,"salt"),o=ht(e.cipher.iv,12,"iv"),i=ht(e.tag,16,"tag"),a=ht(e.ciphertext,1,"ciphertext",{max:Ra}),{ciphertext:c,tag:u,...s}=e,d=$a(r,n);try{let l=Na("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(s))),l.setAuthTag(i),Buffer.concat([l.update(a),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function 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 _a(e){let r=Me.dirname(e),t=L.lstatSync(r);if(!t.isDirectory()||t.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(t.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((t.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=L.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!==t.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function $(e){let r;try{r=L.openSync(e,L.constants.O_RDONLY|L.constants.O_NOFOLLOW)}catch(t){throw t.code==="ELOOP"?new Error("local-vault: refusing symlink"):t}try{let t=L.fstatSync(r);if(Fa(t),t.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=L.lstatSync(e);if(n.isSymbolicLink()||n.dev!==t.dev||n.ino!==t.ino)throw new Error("local-vault: secret source changed or is too large");return L.readFileSync(r,"utf8").replace(/[\r\n]+$/,"")}finally{L.closeSync(r)}}function kn(e){return JSON.parse($(e))}function be(e,r){L.mkdirSync(Me.dirname(e),{recursive:!0,mode:448}),_a(e);let t=Me.join(Me.dirname(e),`.${Me.basename(e)}.${process.pid}.${Oa(6).toString("hex")}.tmp`);try{let n=L.openSync(t,L.constants.O_CREAT|L.constants.O_EXCL|L.constants.O_WRONLY|L.constants.O_NOFOLLOW,384);try{L.writeFileSync(n,String(r)),L.fsyncSync(n)}finally{L.closeSync(n)}L.renameSync(t,e),L.chmodSync(e,384);let o=L.openSync(Me.dirname(e),"r");try{L.fsyncSync(o)}finally{L.closeSync(o)}}catch(n){try{L.unlinkSync(t)}catch{}throw n}}import{createHmac as Ma,randomBytes as Da,timingSafeEqual as Ua}from"node:crypto";import j from"node:fs";import Ne from"node:path";import{homedir as tr}from"node:os";import{join as rr}from"node:path";var Tn=process.env.ORACLE_PUBLIC_DESKTOP==="1",qa=Tn?process.env.ORACLE_CONFIG_DIR||rr(tr(),".config","oracle"):rr(tr(),".config","oracle"),Vu=Tn?qa:rr(tr(),".config","mad-desk");var Qu="0".repeat(64),Zu=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 yt(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(yt).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+yt(e[t])).join(",")+"}"}var el=Promise.resolve();function Ue(e,r){if(!e)throw new Error("ledger: separate freshness anchor required");let t=a=>{try{return j.realpathSync(a)}catch{return Ne.resolve(a)}},n=t(Ne.dirname(Ne.resolve(e))),o=t(Ne.dirname(Ne.resolve(r))),i=(a,c)=>c===a||c.startsWith(a+Ne.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var ja=864e5,J=(e,r)=>Ma("sha256",r).update(yt(e)).digest("hex"),se=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&Ua(t,n)},Wa=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:r,...t}=e;return t};function Ha(e,r){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!se(e.integrity.mac,J(e.policy,r)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function bt(e,r){if(!e)throw new Error("policy: sequence anchor required");let t;try{t=$(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(t)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!se(n?.integrity?.mac,J(n?.marker,r)))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 Ja(e,r,t,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 c=bt(e,t);i=c.present&&c.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(r),policyMac:String(n)};i&&(a.ledgerInitialized=!0),be(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:J(a,t)}})+`
4
+ `)}function za(e,r){let t=bt(e,r);if(!t.present)throw new Error("policy: sequence anchor required");if(t.ledgerInitialized)return!0;if(t.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");return Ja(e,t.sequence,r,t.policyMac,{ledgerInitialized:!0}),!0}function Nn(e,r,{sequenceAnchorFile:t}={}){if(!t)throw new Error("policy: sequence anchor required");let n=$(r),o;try{o=JSON.parse($(e))}catch(u){throw new Error(`policy: cannot read sealed policy: ${u?.message||u}`)}let i=Ha(o,n);Ue(t,e);let a=bt(t,n),c=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(c!==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(!se(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function tt(e,r,t,n,o){let i=`${e}.continuity`,a;try{let c=JSON.parse($(e));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!se(c?.integrity?.mac,J(c.ledger,r)))throw new Error("integrity verification failed");if(a=c.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(c){if(c?.code==="ENOENT"){if(j.existsSync(i)||j.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let u=bt(o,r);if(u.present&&u.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:t,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${c?.message||c}`)}try{let c=JSON.parse($(i));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!se(c?.integrity?.mac,J(c.marker,r)))throw new Error("continuity verification failed");if(c.marker?.version===2&&(c.marker.sequence!==a.sequence||!se(c.marker.ledgerMac,J(a,r))))throw new Error("continuity rollback detected");if(c.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(j.existsSync(n)&&(c.marker?.version!==2||a.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(c.marker?.version===2){let u=JSON.parse($(n));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!se(u?.integrity?.mac,J(u.marker,r))||u.marker?.version!==1||u.marker.sequence!==a.sequence||!se(u.marker.ledgerMac,J(a,r)))throw new Error("checkpoint rollback detected")}}catch(c){throw new Error(`ledger: corrupt or unreadable: ${c?.message||c}`)}if(t-a.windowStartMs>=ja){let c=a.entries.map(u=>u.state==="reserved"?u:Array.isArray(u.units)?{...u,state:"consumed",units:u.units.map(s=>({...s,value:"0",notional:"0"}))}:{...u,state:"consumed",value:"0",notional:"0"});return{windowStartMs:t,entries:c,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function Va(e){return Array.isArray(e.units)?e.units:[{unit:e.unit||"wei",value:e.value,notional:e.notional,fee:e.fee}]}function xe(e,r,t){return e.reduce((n,o)=>{let i=Va(o).find(a=>a.unit===t);return i?n+BigInt(i[r]??0):n},0n)}function nr(e){if(!Array.isArray(e)||e.length===0)throw new Error("ledger: units array required");let r=new Set,t=e.map(n=>{let o=String(n?.unit||"");if(!o)throw new Error("ledger: unit required");if(r.has(o))throw new Error("ledger: duplicate unit in units array");r.add(o);let i=BigInt(n.value??0),a=BigInt(n.notional??0);if(i<0n||a<0n)throw new Error("ledger: unit value/notional must be non-negative");let c=n.fee===void 0?0n:BigInt(n.fee);if(c<0n)throw new Error("ledger: unit fee must be non-negative");return{unit:o,value:i.toString(),notional:a.toString(),fee:c.toString()}});return t.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),t}function Ga(e,r){let t=e[r];if(t==null||t==="")throw new Error(`ledger: ${r} required`);return Q(t,`ledger: ${r}`)}function Et(e,r){if(String(r).startsWith("erc20:")){let n=String(r).slice(6).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("ledger: invalid ERC20 accounting unit");let o=Object.entries(e.nftPaymentTokenCaps||{}).find(([a])=>String(a).toLowerCase()===n)?.[1];if(!o)throw new Error("ledger: NFT payment-token caps required");let i=["maxDailyValueRaw","maxDailyNotionalRaw","maxPerTradeRaw"];for(let a of i)if(o[a]===void 0||o[a]===null||o[a]==="")throw new Error(`ledger: ${a} required`);return i.map(a=>BigInt(o[a]))}let t=r==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:r==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:r==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:r==="usdc"?["maxDailyValueUsdc","maxDailyNotionalUsdc","maxPerTradeUsdc"]:null;if(!t)throw new Error("ledger: unsupported accounting unit");if(r==="usdc"){let n=t.filter(u=>e[u]!==void 0&&e[u]!==null&&e[u]!=="");if(n.length===t.length)return t.map(u=>Ga(e,u));if(n.length>0){let u=t.filter(s=>!n.includes(s));throw new Error(`ledger: ${u[0]} required`)}let o=e.maxDailyNotionalUsd??e.maxNotionalUsd??e.maxNotionalUsdc,i=e.maxPerTradeUsd??e.maxNotionalUsd??e.maxNotionalUsdc;if(o==null||o==="")throw new Error("ledger: maxDailyValueUsdc required");if(i==null||i==="")throw new Error("ledger: maxPerTradeUsdc required");let a=P(o,6,"ledger: maxDailyNotionalUsdc"),c=P(i,6,"ledger: maxPerTradeUsdc");return[a,a,c]}for(let n of t)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return t.map(n=>BigInt(e[n]))}function rt(e,r){let t=`${e}.lock`,n=Da(16).toString("hex"),o;try{o=j.openSync(t,j.constants.O_CREAT|j.constants.O_EXCL|j.constants.O_WRONLY|(j.constants.O_NOFOLLOW||0),384),j.writeFileSync(o,n),j.fsyncSync(o)}catch(i){throw o!==void 0&&j.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return r()}finally{j.closeSync(o);try{$(t)===n&&j.unlinkSync(t)}catch{}}}function De(e,r,t,n,o){let i=`${e}.continuity`,a={...r,sequence:(r.sequence??0)+1},c=J(a,t);be(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:c}})+`
5
+ `);let u={version:2,sequence:a.sequence,ledgerMac:c};be(i,JSON.stringify({marker:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:J(u,t)}})+`
6
+ `);let s={version:1,sequence:a.sequence,ledgerMac:c};j.mkdirSync(Ne.dirname(n),{recursive:!0,mode:448}),be(n,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:J(s,t)}})+`
7
+ `),o&&za(o,t)}function or({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:c=0,fee:u,units:s,policy:d,nowMs:l=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");Ue(t,e);let p=$(r);return rt(e,()=>{let w=tt(e,p,l,t,n);if(w.entries.some(h=>String(h.tradeId)===f))throw new Error("ledger: replayed tradeId");let y;if(s!==void 0){let h=nr(s);for(let m of h){let[b,E,A]=Et(d,m.unit),I=BigInt(m.value),k=BigInt(m.notional);if(k>A)throw new Error("ledger: per-trade cap exceeded");if(xe(w.entries,"value",m.unit)+I>b||xe(w.entries,"notional",m.unit)+k>E)throw new Error("ledger: daily cap exceeded")}y={tradeId:f,units:h,state:"reserved",atMs:l}}else{let h=BigInt(a),m=BigInt(c),[b,E,A]=Et(d,i);if(h<0n||m<0n||m>A)throw new Error("ledger: per-trade cap exceeded");if(xe(w.entries,"value",i)+h>b||xe(w.entries,"notional",i)+m>E)throw new Error("ledger: daily cap exceeded");y={tradeId:f,unit:i,value:h.toString(),notional:m.toString(),fee:u===void 0?"0":BigInt(u).toString(),state:"reserved",atMs:l}}return w.entries.push(y),De(e,w,p,t,n),structuredClone(y)})}function On({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:c=Date.now()}){Ue(t,e);let u=$(r);return rt(e,()=>{let s=tt(e,u,c,t,n),d=s.entries.find(y=>String(y.tradeId)===String(o?.tradeId??"")&&y.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let y=nr(o.units);if(JSON.stringify(y)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(a){if(!Array.isArray(a.units))throw new Error("ledger: reserved units no longer match decoded economics");let h=nr(a.units);if(h.length!==d.units.length||h.some((m,b)=>m.unit!==d.units[b].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let m=0;m<h.length;m++)if(BigInt(h[m].value)>BigInt(d.units[m].value)||BigInt(h[m].notional)>BigInt(d.units[m].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let h of d.units){let[m,b,E]=Et(i,h.unit);if(BigInt(h.notional)>E)throw new Error("ledger: per-trade cap exceeded");if(xe(s.entries,"value",h.unit)>m||xe(s.entries,"notional",h.unit)>b)throw new Error("ledger: daily cap exceeded")}return structuredClone(d)}if(d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(d.value)||BigInt(a.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[f,p,w]=Et(i,l);if(BigInt(d.notional)>w)throw new Error("ledger: per-trade cap exceeded");if(xe(s.entries,"value",l)>f||xe(s.entries,"notional",l)>p)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function Ln({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Ue(t,e);let a=$(r);return rt(e,()=>{let c=tt(e,a,i,t,n),u=c.entries.find(s=>String(s.tradeId)===String(o??"")&&s.state==="reserved");if(!u||u.state!=="reserved")throw new Error("ledger: reservation unavailable");return u.state="committed",u.committedAtMs=i,De(e,c,a,t,n),structuredClone(u)})}function Bn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Ue(t,e);let a=$(r);return rt(e,()=>{let c=tt(e,a,i,t,n),u=c.entries.findIndex(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(u<0)throw new Error("ledger: reservation unavailable");let[s]=c.entries.splice(u,1);return De(e,c,a,t,n),structuredClone(s)})}function Cn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Ue(t,e);let a=$(r);return rt(e,()=>{let c=tt(e,a,i,t,n),u=c.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!u)throw new Error("ledger: reservation unavailable");if(Array.isArray(u.units))return u.state="committed",u.committedAtMs=i,u.units=u.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),u.settledAs=u.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",De(e,c,a,t,n),structuredClone(u);let s=BigInt(u.fee??0);return s<=0n?(u.state="committed",u.committedAtMs=i,u.value="0",u.notional="0",u.settledAs="no-fee",De(e,c,a,t,n),structuredClone(u)):(u.state="committed",u.committedAtMs=i,u.value="0",u.notional=s.toString(),u.settledAs="fee-only",De(e,c,a,t,n),structuredClone(u))})}function Pn(e,r,t,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(Wa(r))};return se(e.mac,J(o,$(t)))}function Ka(e){let r={...e?.fee||{}};return delete r.waiverAttestation,{...e,fee:r}}function Rn(e,r,t,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(r.owner).toLowerCase(),action:String(r.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:X(Ka(r))};return se(e.mac,J(o,$(t)))}import{spawnSync as Ya}from"node:child_process";function $n(e="oracle-local-signer",r=process.env.USER||process.env.USERNAME||"oracle"){let t,n;if(process.platform==="darwin")t="/usr/bin/security",n=["find-generic-password","-s",e,"-a",r,"-w"];else if(process.platform==="linux")t="secret-tool",n=["lookup","service",e,"account",r];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let o=Ya(t,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 ir}from"ethers";import{base58 as ar}from"@scure/base";import{ed25519 as Dn}from"@noble/curves/ed25519.js";import{NETWORK as Un,TEST_NETWORK as jn,WIF as Xa,p2wpkh as Fn}from"@scure/btc-signer";import{pubECDSA as Qa}from"@scure/btc-signer/utils.js";var xt=e=>{let r=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(r)||r.length%2?null:Buffer.from(r,"hex")},Za=e=>{let r=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r))return null;let t=Buffer.from(r,"base64");return t.toString("base64")===r?t:null},_n=e=>{let r=String(e||"").trim();try{let t=Buffer.from(ar.decode(r));return ar.encode(t)===r?t:null}catch{return null}},sr=e=>{if(!(e instanceof Uint8Array))throw new Error("sol: key bytes required");if(e.length!==32&&e.length!==64)throw new Error("sol: expected 32-byte private key material");let r=Buffer.from(e.subarray(0,32));if(e.length===64){let t=Buffer.from(e.subarray(32,64)),n=Buffer.from(Dn.getPublicKey(r));if(!t.equals(n))throw new Error("sol: supplied public key does not match seed")}return r},qn=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),fe=(e,r)=>{if(r==="sol")return sr(e);if(!(e instanceof Uint8Array))throw new Error(`${r}: 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(`${r}: expected 32-byte private key material`)},es=(e,r)=>{if(!Array.isArray(e))throw new Error(`${r}: expected byte array`);let t=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${r}: expected integer bytes in 0..255`);t[n]=o}return fe(t,r)};function cr(e,r){let t=String(r||"").trim();if(e==="evm")return new ir(t).privateKey;if(e==="btc")for(let i of[Un,jn])try{return Buffer.from(Xa(i).decode(t))}catch{}if(e==="sol"){if(/^hex:/i.test(t)){let s=xt(t.slice(4));if(!s)throw new Error("sol: invalid explicit hex private key");return fe(s,"sol")}if(/^base58:/i.test(t)){let s=_n(t.slice(7));if(!qn(s))throw new Error("sol: invalid explicit base58 private key");return sr(s)}if(/^0x/i.test(t)){let s=xt(t);if(!s)throw new Error("sol: invalid explicit hex private key");return fe(s,"sol")}let i=xt(t),a=i&&(i.length===32||i.length===64)?fe(i,"sol"):null,c=_n(t),u=qn(c);if(a&&u&&!a.equals(u))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(u)return sr(c);if(i)return fe(i,"sol")}let n=xt(t);if(n)return e==="evm"?new ir(`0x${n.toString("hex")}`).privateKey:fe(n,e);let o=Za(t);if(o)return fe(o,e);if(t.startsWith("[")||t.startsWith("{")){let i=JSON.parse(t);if(Array.isArray(i))return es(i,e);let a=i.privateKey??i.secretKey??i.key;if(a)return cr(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function Mn(e,r){if(e==="evm"){let t=new ir(String(r));return{kind:e,secret:t.privateKey,addresses:[t.address.toLowerCase()]}}if(e==="btc"){let t=fe(r,"btc"),n=Qa(t);return{kind:e,secret:t.toString("hex"),addresses:[Fn(n,Un).address,Fn(n,jn).address]}}if(e==="sol"){let t=fe(r,"sol");return{kind:e,secret:t.toString("hex"),addresses:[ar.encode(Dn.getPublicKey(t))]}}throw new Error(`unsupported signer kind ${e}`)}function Wn(e,r={}){let t=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(r.kind||"")!=="multichain")return{[r.kind||"evm"]:Mn(r.kind||"evm",cr(r.kind||"evm",t))};let n=JSON.parse(t),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Mn(i,cr(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function ur(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var ue=new pr(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Jn=new pr(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),dr=new pr(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function cs(e){let r=process.env.ORACLE_SIGNER_STATE_DIR||re.join(process.env.XDG_STATE_HOME||re.join(ts.homedir(),".local","state"),"oracle"),t=rs("sha256").update(re.resolve(e)).digest("hex").slice(0,16);return{vault:re.join(e,"vault.json"),policy:re.join(e,"signer-policy.json"),policyKey:re.join(e,"policy-integrity-key"),policyAnchor:re.join(r,`signer-policy-${t}.high-water`),ledger:re.join(e,"signer-ledger.json"),ledgerAnchor:re.join(r,`signer-ledger-${t}.high-water`),token:re.join(e,"signer-token"),lock:re.join(r,`signer-${t}.lock`)}}function us(e){try{return $(e)}catch(t){if(t.code!=="ENOENT")throw t}let r=ns(32).toString("hex");return be(e,r+`
8
+ `),r}function Vl(e,r,t){let n=String(e||"").toLowerCase();if(n!==String(r||"").toLowerCase())throw new Error("signer: wallet does not match vault metadata");if(!Array.isArray(t)||!t.some(o=>String(o).toLowerCase()===n))throw new Error("signer: wallet is not an allowed policy owner");return!0}function fr(e,r,t){if(!r)throw new Error(`signer: ${e} key is required by policy`);let n=new Set((t||[]).map(o=>String(o).toLowerCase()));if(!r.addresses.some(o=>n.has(String(o).toLowerCase())))throw new Error(`signer: ${e} vault address is not an allowed policy owner`);return!0}function zn(e){return e.surfaces.some(r=>String(r).startsWith("evm"))}function H(e,r){return e.surfaces.includes(r)}function ce(e,r){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(t))throw new Error(`signer: invalid ${r}`);return t}function Vn(e,r){return Object.entries(e||{}).find(([t])=>t.toLowerCase()===r)?.[1]}function ls(e,r){let t=e?.anvilQuote;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("signer: exact prepared Anvil quote is required");if(!e?.artifact?.anvilQuote||JSON.stringify(e.artifact.anvilQuote)!==JSON.stringify(t))throw new Error("signer: exact prepared Anvil quote artifact mismatch");return Object.freeze(r==="buy"?{totalCostRaw:BigInt(t.totalCostRaw).toString(),baseCostRaw:BigInt(t.baseCostRaw).toString(),feeRaw:BigInt(t.feeRaw).toString(),protocolFeeRaw:BigInt(t.protocolFeeRaw).toString(),available:t.available===!0}:{netPayoutRaw:BigInt(t.netPayoutRaw).toString(),grossPayoutRaw:BigInt(t.grossPayoutRaw).toString(),feeRaw:BigInt(t.feeRaw).toString(),protocolFeeRaw:BigInt(t.protocolFeeRaw).toString()})}function ds(e,r,t){if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("signer: exact prepared Anvil quote confirmation required");let n=e.artifact,o=r==="buy"?[t.totalCostRaw,e.maxPaymentTokenAmountRaw,n?.maxPaymentTokenAmountRaw,e.exactQuoteTotalCostRaw,n?.exactQuoteTotalCostRaw,e.preconditions?.confirmedTotalCostRaw]:[t.netPayoutRaw,e.minPayoutRaw,n?.minPayoutRaw,e.exactQuoteNetPayoutRaw,n?.exactQuoteNetPayoutRaw,e.preconditions?.confirmedNetPayoutRaw],i;try{i=BigInt(o[0]);for(let s of o.slice(1))if(BigInt(s)!==i)throw new Error("mismatch")}catch{throw new Error(`signer: exact Anvil ${r} settlement limit mismatch`)}let a=n?.transactions;if(!Array.isArray(a)||a.length!==1)throw new Error("signer: exact Anvil action transaction required");let c=r==="buy"?"buySpecificNFT":"sellNFT",u;try{if(u=ue.decodeFunctionData(c,a[0].data),ue.encodeFunctionData(c,[u[0],u[1]]).toLowerCase()!==String(a[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${r} calldata required`)}if(BigInt(u[0])!==BigInt(e.tokenId)||BigInt(u[1])!==i)throw new Error(`signer: exact Anvil ${r} calldata limit mismatch`);return i}async function pe(e,r,t,n,o,i=[]){let a=await e.send("eth_call",[{to:r,data:t.encodeFunctionData(n,i)},o]);return t.decodeFunctionResult(n,a)[0]}async function fs(e,r,t,{nowMs:n=Date.now(),signerAddress:o}={}){if(r?.surface!=="evm-nft"||String(r?.provider).toLowerCase()!=="anvil-nft")return null;if(!e||typeof e.send!="function")throw new Error("signer: trusted RPC cannot attest Anvil market");let i=ce(r.destination,"Anvil market"),a=ce(r.contract,"Anvil collection"),c=ce(r.paymentToken,"Anvil payment token"),u=BigInt(r.nativeSwapFeeWei),s=Number(r.paymentTokenDecimals),d=ce(o,"Anvil signer identity"),l=ce(r.owner,"Anvil envelope owner");if(d!==l)throw new Error("signer: Anvil signer identity mismatch");let f=BigInt(r.tokenId);if(f<0n)throw new Error("signer: invalid Anvil tokenId");let p=String(r.nftAction||"").toLowerCase();if(p!=="buy"&&p!=="sell")throw new Error("signer: unsupported Anvil NFT action");let w=ls(r,p),y=ds(r,p,w),h=r.anvilAttestation;if(!h||typeof h!="object"||Number(h.snapshotExpiresAtMs)<=Number(n))throw new Error("signer: fresh provider Anvil attestation required");let m=String(Vn(t.anvilRuntimeCodeHashes,i)||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(m)||m!==String(h.runtimeCodeHash||"").toLowerCase())throw new Error("signer: Anvil runtime is not reviewed by policy");let b=Vn(t.nftPaymentTokenCaps,c);if(!b||Number(b.decimals)!==s)throw new Error("signer: Anvil payment token decimals are not reviewed by policy");let E=String(await e.send("eth_chainId",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(E)||BigInt(E)!==4663n)throw new Error("signer: trusted RPC Anvil chain mismatch");let A=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(A))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let I=BigInt(A),k=await e.send("eth_getBlockByNumber",[A,!1]),S=String(k?.hash||"").toLowerCase();if(String(k?.number||"").toLowerCase()!==A||!/^0x[0-9a-f]{64}$/.test(S))throw new Error("signer: trusted RPC returned an invalid Anvil block attestation");let B=Object.freeze({blockHash:S,requireCanonical:!0}),F=String(await e.send("eth_getCode",[i,B])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(F)||F==="0x")throw new Error("signer: Anvil market runtime is empty");let z=as(F).toLowerCase();if(z!==m)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[me,vt,It]=await Promise.all([pe(e,i,ue,"collection",B),pe(e,i,ue,"token",B),pe(e,i,ue,"robinhoodSwapFeeWei",B)]),we=ce(me,"live Anvil collection"),Oe=ce(vt,"live Anvil payment token"),je=BigInt(It).toString();if(we!==a)throw new Error("signer: live Anvil collection mismatch");if(Oe!==c)throw new Error("signer: live Anvil payment token mismatch");if(je!==u.toString())throw new Error("signer: live Anvil native swap fee mismatch");let Se=Number(await pe(e,Oe,Jn,"decimals",B));if(!Number.isSafeInteger(Se)||Se!==s)throw new Error("signer: live Anvil payment token decimals mismatch");let We=ce(await pe(e,we,dr,"ownerOf",B,[f]),"live Anvil token owner"),He=null,le=null,Ae=null,g=null,x;if(p==="buy"){let[T,N,_]=await Promise.all([pe(e,i,ue,"inventory",B,[f]),pe(e,Oe,Jn,"allowance",B,[d,i]),e.send("eth_call",[{to:i,data:ue.encodeFunctionData("quoteSpecificBuy",[f])},B])]);He=!!T,le=BigInt(N).toString();let C=ue.decodeFunctionResult("quoteSpecificBuy",_);if(x=Object.freeze({totalCostRaw:BigInt(C[0]).toString(),baseCostRaw:BigInt(C[1]).toString(),feeRaw:BigInt(C[2]).toString(),protocolFeeRaw:BigInt(C[3]).toString(),available:!!C[4]}),JSON.stringify(x)!==JSON.stringify(w))throw new Error("signer: exact Anvil buy quote changed after preparation");if(We!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!He)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt(le)!==BigInt(r.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(le)<y)throw new Error("signer: live Anvil ERC20 allowance is insufficient");if(!x.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(x.totalCostRaw)!==y)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(x.totalCostRaw)!==BigInt(x.baseCostRaw)+BigInt(x.feeRaw)+BigInt(x.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[T,N,_]=await Promise.all([pe(e,we,dr,"getApproved",B,[f]),pe(e,we,dr,"isApprovedForAll",B,[d,i]),e.send("eth_call",[{to:i,data:ue.encodeFunctionData("quoteSellNFT")},B])]);Ae=ce(T,"live Anvil token approval"),g=!!N;let C=ue.decodeFunctionResult("quoteSellNFT",_);if(x=Object.freeze({netPayoutRaw:BigInt(C[0]).toString(),grossPayoutRaw:BigInt(C[1]).toString(),feeRaw:BigInt(C[2]).toString(),protocolFeeRaw:BigInt(C[3]).toString()}),JSON.stringify(x)!==JSON.stringify(w))throw new Error("signer: exact Anvil sell quote changed after preparation");if(We!==d)throw new Error("signer: exact Anvil token owner does not match signer");if(Ae!==i&&!g)throw new Error("signer: live Anvil NFT approval is insufficient");if(Ae!==ce(r.preconditions?.approvedAddress,"prepared Anvil token approval")||g!==!!r.preconditions?.approvedForAll)throw new Error("signer: live Anvil NFT approval changed after preparation");if(BigInt(x.netPayoutRaw)!==y)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(x.netPayoutRaw)+BigInt(x.feeRaw)+BigInt(x.protocolFeeRaw)!==BigInt(x.grossPayoutRaw))throw new Error("signer: exact Anvil sell quote fee arithmetic mismatch")}return Object.freeze({source:"local-signer-trusted-rpc",chainId:4663,market:i,collection:we,paymentToken:Oe,paymentTokenDecimals:Se,nativeSwapFeeWei:je,signerAddress:d,nftAction:p,tokenId:f.toString(),tokenOwner:We,inventoryMember:He,allowanceRaw:le,approvedAddress:Ae,approvedForAll:g,quote:x,blockNumber:I.toString(),blockHash:S,runtimeCodeHash:z,verifiedAtMs:Number(n)})}function Gn(e,r,t="execution"){if(!e||!r)throw new Error("signer: complete Anvil revalidation evidence required");for(let n of["runtimeCodeHash","market","collection","paymentToken","paymentTokenDecimals","nativeSwapFeeWei","signerAddress","nftAction","tokenId","tokenOwner","inventoryMember","allowanceRaw","approvedAddress","approvedForAll"])if(String(r[n]).toLowerCase()!==String(e[n]).toLowerCase())throw new Error(`signer: Anvil ${n} changed after simulation at ${t}`);if(JSON.stringify(r.quote)!==JSON.stringify(e.quote))throw new Error(`signer: Anvil quote changed after simulation at ${t}`);return!0}function ps(e,r,t,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:a}={}){let c=is(new URL("./anvil-attestation-worker.mjs",import.meta.url)),u={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},s;try{s=os(process.execPath,[c],{input:JSON.stringify({rpcUrl:e,chainId:r,envelope:t,policy:u,nowMs:Number(o),signerAddress:a}),encoding:"utf8",timeout:i,maxBuffer:64e3,env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_OPTIONS:""},stdio:["pipe","pipe","pipe"]})}catch{throw new Error("signer: fresh independent Anvil attestation failed before reservation")}let d;try{d=JSON.parse(s)}catch{throw new Error("signer: invalid Anvil reservation attestation result")}if(!d||d.source!=="local-signer-trusted-rpc"||!/^0x[0-9a-f]{64}$/.test(String(d.blockHash||"")))throw new Error("signer: invalid Anvil reservation attestation result");return Object.freeze(d)}function ms(e,r,t,n=null){let o=e?.version===1&&e?.surface?e:null,i=o?.artifact||e||{},a=[`surface=${o?.surface||"evm"} action=${o?.action||"evm"}`,`chain=${i.chainId??i.network??i.cluster??"n/a"} owner=${o?.owner||i.from||"n/a"}`,`to=${i.to||o?.destination||"n/a"} calldata=${String(i.data||"0x")} value=${i.value??"n/a"}`,`gas=${i.gasLimit??"n/a"} maxFeePerGas=${i.maxFeePerGas??i.gasPrice??"n/a"} maxPriorityFeePerGas=${i.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${i.l1FeeWei??"n/a"} operatorFeeWei=${i.operatorFeeWei??"n/a"}`,`nonce=${i.nonce??"n/a"} type=${i.type??"n/a"} accessList=${Array.isArray(i.accessList)?i.accessList.length:0}`,`slippageBps=${o?.slippageBps??i.slippageBps??"n/a"} expiresAtMs=${o?.expiresAtMs??i.expiresAtMs??"n/a"}`],c=(s,d)=>{if(a.push(`LEG ${d} chain=${s.chainId??"n/a"} from=${s.from??"n/a"} to=${s.to??"n/a"}`),a.push(`LEG ${d} calldata=${String(s.data||"0x")} value=${s.value??"n/a"}`),a.push(`LEG ${d} gas=${s.gasLimit??"n/a"} maxFeePerGas=${s.maxFeePerGas??s.gasPrice??"n/a"} maxPriorityFeePerGas=${s.maxPriorityFeePerGas??"n/a"}`),a.push(`LEG ${d} l1FeeWei=${s.l1FeeWei??"n/a"} operatorFeeWei=${s.operatorFeeWei??"n/a"} nonce=${s.nonce??"n/a"} type=${s.type??"n/a"}`),ne(String(s.data||"0x")))try{let l=Ve(String(s.data||"0x"));a.push(`LEG ${d} APPROVAL token=${l.token||s.to||"n/a"} spender=${l.spender} amount=${l.amount}`)}catch{a.push(`LEG ${d} APPROVAL spender=undecodable amount=undecodable`)}},u=String(i.data||"0x");if(ne(u))try{let s=Ve(u);a.push(`APPROVAL token=${s.token||i.to||"n/a"} spender=${s.spender} amount=${s.amount}`)}catch{a.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(i.transactions)&&(a.push(`batchLegs=${i.transactions.length}`),i.transactions.forEach((s,d)=>c(s,d))),o?.surface==="btc"){let s=Bt(o,t);a.push(`amount=${s.value} sats fee=${s.fee} sats outputs=${s.outputs.join(",")}`)}if(o?.surface==="sol"){let s=_t(o,t);a.push(`amount=${s.value} lamports fee=${s.fee} lamports programs=${s.programs.join(",")}`)}if(o?.surface==="hl"){let s=ge(o,t);a.push(`hlKind=${s.kind} actionType=${s.actionType} coin=${s.coin||"n/a"} amount=${s.amount} notionalUsd=${s.notional} submitTo=${s.submitTo}`)}if(o?.surface==="poly"){let s=ye(o,t);a.push(`polyKind=${s.kind} tokenId=${s.tokenId} side=${s.side} price=${s.price} quantity=${s.quantity} notionalUsdc=${s.notionalUsdc} submitTo=${s.submitTo}`)}if(o?.surface==="evm-nft"&&o?.provider==="anvil-nft"&&(a.push(`anvilAction=${o.nftAction} collection=${o.contract} tokenId=${o.tokenId} market=${o.destination}`),a.push(`paymentToken=${o.paymentToken} paymentTokenDecimals=${o.paymentTokenDecimals} maxPaymentTokenAmountRaw=${o.maxPaymentTokenAmountRaw??"n/a"} minPayoutRaw=${o.minPayoutRaw??"n/a"} nativeSwapFeeWei=${o.nativeSwapFeeWei}`),n&&(a.push(`SIGNER VERIFIED block=${n.blockNumber} blockHash=${n.blockHash} runtimeCodeHash=${n.runtimeCodeHash} signer=${n.signerAddress} collection=${n.collection} paymentToken=${n.paymentToken} paymentTokenDecimals=${n.paymentTokenDecimals} nativeSwapFeeWei=${n.nativeSwapFeeWei}`),a.push(`SIGNER DYNAMIC tokenId=${n.tokenId} owner=${n.tokenOwner} inventory=${n.inventoryMember} allowanceRaw=${n.allowanceRaw} approved=${n.approvedAddress} approvedForAll=${n.approvedForAll} quote=${JSON.stringify(n.quote)}`))),o?.surface==="lighter"){let s=Ee(o,t);a.push(`lighterKind=${s.kind} actionType=${s.actionType} market=${s.symbol} amount=${s.amount} submitTo=${s.submitTo}`)}return`
9
9
  Confirm exact action
10
10
  ${a.join(`
11
11
  `)}
12
- Type digest ${r}: `}async function bt(e,r){let t=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),n=await t.text();if(!t.ok)throw new Error(`rpc: HTTP ${t.status}`);let o=JSON.parse(n||"{}");if(o.error)throw new Error(`rpc: ${o.error.message||"request failed"}`);return o.result}function Hn(e,r){return Buffer.concat([Buffer.from([1]),Buffer.from(r),Buffer.from(e)]).toString("base64")}async function zn(e,r,t){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation and broadcast");return bt(n,{jsonrpc:"1.0",id:"oracle",method:r,params:t})}async function us(e,r,t){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/${r}/outspend/${t}`);if(a.ok){let c=await a.json();if(c?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(c?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await zn(e,"gettxout",[r,Number(t),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function ls(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 ds(e,r){return{simulate:async(t,n)=>(we(n,e()),!0),sign:async(t,n)=>{we(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(r.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(r.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return t?.typedData?(tn(t),r.signTypedData(t.typedData.domain,t.typedData.types,t.typedData.message)):rn({wallet:r,action:t.action,nonce:t.nonce,isMainnet:!String(t.submitTo||"").includes("testnet")})},broadcast:async(t,n,o)=>{we(o,e());let{Signature:i,keccak256:a}=await import("ethers"),c=i.from(t);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:c.r,s:c.s,v:c.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(t),status:1}}}}function fs(e){return{simulate:async(r,t)=>(ge(t,e()),!0),sign:async(r,t)=>{ge(t,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(r,t);return Ze(r,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(r,t,n)=>{let o=ge(n,e()),i=Ze(t,r),a=an(i),c=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),u=await c.json().catch(()=>({}));if(!c.ok||Number(u?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(u?.tx_hash||u?.txHash||"lighter"),status:1}}}}function ps(e,r){return{simulate:async(t,n)=>(he(n,e()),!0),sign:async(t,n)=>{he(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(r.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(r.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return r.signTypedData(t.domain,t.types,t.message)},broadcast:async(t,n,o)=>{let i=e(),a=he(o,i),c=Dt(i),{keccak256:u}=await import("ethers"),s=$r({message:n.message,side:n.side,signature:t,orderType:n.orderType||"GTC",apiKey:c.key}),d=JSON.stringify(s),l=Rr({creds:c,address:o.owner,method:"POST",path:"/order",body:d}),f=await fetch(a.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:u(t),status:1}}}}function ms(e,r){let t=ar(r);return{simulate:async n=>{let o=e(),i=sr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let a=0;a<i.inputsLength;a++){let c=i.getInput(a),u=Buffer.from(c.txid||[]).toString("hex");await us(o,u,c.index)}return!0},sign:n=>{let o=sr.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(t),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=sr.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let c;try{let s=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(c=(await s.text()).trim(),!s.ok)throw new Error(`signer: Bitcoin broadcast failed ${s.status}`)}catch(s){if(!/Bitcoin broadcast failed 404/.test(String(s?.message||s)))throw s;c=await zn(o,"sendrawtransaction",[a.hex])}if(c&&String(c).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let u=null;try{let s=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${s}/tx/${a.id}/status`);d.ok&&(u=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:u}}}}function ws(e,r){let t=ar(r);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"),c=Hn(a,new Uint8Array(64)),u=await bt(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[c,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return ls(u)},sign:n=>Hn(Buffer.from(n.messageBase64,"base64"),ts.sign(Buffer.from(n.messageBase64,"base64"),t)),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 bt(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),u=(await bt(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(u?.err)return{hash:a,status:0};let s=u?.confirmationStatus==="confirmed"||u?.confirmationStatus==="finalized"||u?.confirmations===null;return{hash:a,status:s?1:null}}}}function hs(e,r={}){for(let t of Object.keys(r||{}))if(Object.prototype.hasOwnProperty.call(e,t))throw new Error(`signer: cannot replace built-in ${t} transport`)}async function Ul({configDir:e,passphraseFile:r,credentialService:t,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:c,Wallet:u}=await import("ethers");if(!r&&!t)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 s=rs(e),d=()=>Object.freeze(In(s.policy,s.policyKey,{sequenceAnchorFile:s.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(H(l,"poly")&&(Dt(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(H(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(H(l,"hl")){let y=Array.isArray(l.coins)?l.coins.map(String):[],x=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(y.filter(N=>N!=="*"&&N!=="#*").length&&!y.includes("*")&&x.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let m=t?Bn(t):R(r),p=An(s.vault),g=Sn(p,m),h;try{h=qn(g,p.meta)}finally{g.fill(0)}(Un(l)||H(l,"hl")||H(l,"poly"))&&ur("evm",h.evm,l.owners),H(l,"btc")&&ur("btc",h.btc,l.owners),H(l,"sol")&&ur("sol",h.sol,l.owners);let w=Array.isArray(l.chains)?l.chains.filter(y=>Number.isInteger(Number(y))&&String(y).trim()!==""):[],b=Un(l);if(b&&(w.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(H(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(H(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=b?new c(l.rpcUrl,Number(w[0])):null,S=h.evm&&(b||H(l,"hl")||H(l,"poly"))?E?new u(h.evm.secret).connect(E):new u(h.evm.secret):null,I=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=>S.signTransaction(y),broadcast:async(y,x)=>{if((await E.getNetwork()).chainId!==BigInt(x.chainId))throw new Error("signer: RPC chain mismatch");let N={native:(await E.getBalance(x.from)).toString()},$=await E.broadcastTransaction(y),B=await $.wait(),Se={native:(await E.getBalance(x.from)).toString()};return{hash:B?.hash??$.hash,status:B?.status??null,verifiedBefore:N,verifiedAfter:Se}}}:null,T=E?async y=>gs(E,y):void 0,v=new Map,C=y=>y?.surface==="evm-nft"&&String(y?.provider).toLowerCase()==="anvil-nft",F=async(y,x=d(),k="execution")=>{if(!C(y))return null;let N=await as(E,y,x,{nowMs:Date.now(),signerAddress:S.address}),$=v.get(Y(y));return $&&Wn($,N,k),N},z={...I?{evm:I,"evm-swap":I,"evm-bridge":I,"evm-nft":I}:{},...h.btc?{btc:ms(d,h.btc)}:{},...h.sol?{sol:ws(d,h.sol)}:{},...S&&H(l,"hl")?{hl:ds(d,S)}:{},...S&&H(l,"poly")?{poly:ps(d,S)}:{},...H(l,"lighter")?{lighter:fs(d)}:{}};hs(z,n);let fe=Zr({...z,...n}),St=new Set(Object.keys(z)),At=new Set(Object.keys(n||{})),pe=l.surfaces.filter(y=>!St.has(y)&&!At.has(y));if(pe.length)throw new Error(`signer: ${pe.join(",")} require local keys or injected surface transports`);let ke=Date.now(),Ue=ke+a,be=!1,je=()=>be?!1:Mn.existsSync(s.lock)?(be=!0,!1):Mn.existsSync(s.vault)&&Date.now()<Ue,We=()=>(be=!0,ye(s.lock,`disarmed ${new Date().toISOString()}
13
- `),!0),ce=xn({host:o,port:i,token:ns(s.token),policy:l,readPolicy:d,isArmed:je,disarm:We,sessionExpiresAtMs:Ue,nowMs:Date.now,simulate:async(y,x)=>(await F(x,d(),"before simulation"),lt(x,fe).simulate(y,x)),estimateNetworkFees:T,sign:async(y,x)=>(await F(x,d(),"before signing"),lt(x,fe).sign(y,x)),verifySigned:(y,x,k)=>pn(k?.surface||"evm",y,x,k),broadcast:async(y,x,k)=>(await F(k,d(),"before broadcast"),lt(k,fe).broadcast(y,x,k)),confirmArtifact:async(y,x,k)=>{let N=await F(y,k),$=await Es(y,x,k,N);return $===!0&&N&&v.set(x,N),$},decodeEconomics:(y,x)=>Jt(y,x),reserveLedger:(y,x)=>{let k=y?.version===1&&y?.surface?y:null,N=k?.artifact||y;if(C(k)){let Se=Y(k),Ne=v.get(Se);if(!Ne||Date.now()-Number(Ne.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let He=ss(x.rpcUrl,N.chainId,k,x,{nowMs:Date.now(),signerAddress:S.address});Wn(Ne,He,"before reservation"),v.set(Se,He)}let $=k?.tradeId||N?.tradeId;if(!$)throw new Error("ledger: executable artifact requires a tradeId");let B;if(k)B=Jt(k,x);else{if(N?.value===void 0)throw new Error("ledger: executable artifact value required");let Se=BigInt(N.value),Ne=BigInt(N.gasLimit??0),He=BigInt(N.maxFeePerGas??N.gasPrice??0);if(Ne<=0n||He<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let dr=Ne*He+BigInt(N.l1FeeWei??0)+BigInt(N.operatorFeeWei??0);B={unit:"wei",value:Se.toString(),notional:(Se+dr).toString(),fee:dr.toString()}}if(Array.isArray(B.units))return nr({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:$,units:B.units,policy:x});if(B.value===void 0||B.notional===void 0)throw new Error("ledger: decoded value and notional required");return nr({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:$,...B,policy:x})},commitLedger:y=>kn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),releaseLedger:y=>Nn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),settleFailedLedger:y=>On({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),validateReservation:(y,x,k)=>Tn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,reservation:y,policy:x,economics:k}),verifyFeeWaiver:(y,x)=>Cn(y,x,s.policyKey),verifyTriggerAttestation:(y,x,k)=>Ln(y,x,s.policyKey,k),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),xe=setTimeout(()=>ce.close(),a);return xe.unref(),ce.on("close",()=>{clearTimeout(xe)}),ce.listen(i,o),ce}var xt="0x420000000000000000000000000000000000000F";function Jn(e){let r=e?.code;if(r==="CALL_EXCEPTION"||r==="BAD_DATA")return!0;let t=String(e?.shortMessage||e?.message||e);return/network|timeout|ECONN|ENOTFOUND|EAI_AGAIN|server error|fetch failed|socket/i.test(t)?!1:/execution reverted|revert|invalid opcode|function selector|could not decode/i.test(t)}async function gs(e,r){if(!re(r?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:t,Transaction:n}=await import("ethers"),o=new t(["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:r.chainId,to:r.to,data:r.data,value:r.value,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce??0,type:r.type,accessList:r.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let a;try{let c=await e.call({to:xt,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",c)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await ys(e,o,r.gasLimit)}}async function ys(e,r,t){let n;try{n=BigInt(t)}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:xt,data:r.encodeFunctionData("getOperatorFee",[n])});return r.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Jn(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:xt,data:r.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:xt,data:r.encodeFunctionData("operatorFeeConstant")}),a=BigInt(r.decodeFunctionResult("operatorFeeScalar",o)[0]),c=BigInt(r.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+c).toString()}catch(o){if(!Jn(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function Es(e,r,t,n=null){return process.stdin.isTTY?(process.stderr.write(cs(e,r,t,n)),process.stdin.resume(),new Promise(o=>{let i=a=>{process.stdin.off("data",i),process.stdin.pause(),o(String(a).trim()===r)};process.stdin.once("data",i)})):!1}export{Wn as assertAnvilAttestationUnchanged,hs as assertNoBuiltinTransportOverride,Dl as assertSignerIdentity,as as attestAnvilMarket,ss as attestAnvilMarketSync,ns as ensureSignerToken,gs as estimateProviderNetworkFees,cs as renderConfirmationArtifact,rs as signerPaths,Ul as startLocalSigner};
12
+ Type digest ${r}: `}async function St(e,r){let t=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),n=await t.text();if(!t.ok)throw new Error(`rpc: HTTP ${t.status}`);let o=JSON.parse(n||"{}");if(o.error)throw new Error(`rpc: ${o.error.message||"request failed"}`);return o.result}function Kn(e,r){return Buffer.concat([Buffer.from([1]),Buffer.from(r),Buffer.from(e)]).toString("base64")}async function Xn(e,r,t){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation and broadcast");return St(n,{jsonrpc:"1.0",id:"oracle",method:r,params:t})}async function ws(e,r,t){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/${r}/outspend/${t}`);if(a.ok){let c=await a.json();if(c?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(c?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await Xn(e,"gettxout",[r,Number(t),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function hs(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 gs(e,r){return{simulate:async(t,n)=>(ge(n,e()),!0),sign:async(t,n)=>{ge(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(r.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(r.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return t?.typedData?(on(t),r.signTypedData(t.typedData.domain,t.typedData.types,t.typedData.message)):an({wallet:r,action:t.action,nonce:t.nonce,isMainnet:!String(t.submitTo||"").includes("testnet")})},broadcast:async(t,n,o)=>{ge(o,e());let{Signature:i,keccak256:a}=await import("ethers"),c=i.from(t);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:c.r,s:c.s,v:c.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(t),status:1}}}}function ys(e){return{simulate:async(r,t)=>(Ee(t,e()),!0),sign:async(r,t)=>{Ee(t,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(r,t);return et(r,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(r,t,n)=>{let o=Ee(n,e()),i=et(t,r),a=un(i),c=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),u=await c.json().catch(()=>({}));if(!c.ok||Number(u?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(u?.tx_hash||u?.txHash||"lighter"),status:1}}}}function Es(e,r){return{simulate:async(t,n)=>(ye(n,e()),!0),sign:async(t,n)=>{ye(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(r.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(r.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return r.signTypedData(t.domain,t.types,t.message)},broadcast:async(t,n,o)=>{let i=e(),a=ye(o,i),c=Ut(i),{keccak256:u}=await import("ethers"),s=Mr({message:n.message,side:n.side,signature:t,orderType:n.orderType||"GTC",apiKey:c.key}),d=JSON.stringify(s),l=_r({creds:c,address:o.owner,method:"POST",path:"/order",body:d}),f=await fetch(a.submitTo,{method:"POST",headers:l,body:d}),p=await f.json().catch(()=>({}));if(!f.ok||p?.success===!1||p?.error||p?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:u(t),status:1}}}}function bs(e,r){let t=ur(r);return{simulate:async n=>{let o=e(),i=lr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let a=0;a<i.inputsLength;a++){let c=i.getInput(a),u=Buffer.from(c.txid||[]).toString("hex");await ws(o,u,c.index)}return!0},sign:n=>{let o=lr.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(t),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=lr.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let c;try{let s=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(c=(await s.text()).trim(),!s.ok)throw new Error(`signer: Bitcoin broadcast failed ${s.status}`)}catch(s){if(!/Bitcoin broadcast failed 404/.test(String(s?.message||s)))throw s;c=await Xn(o,"sendrawtransaction",[a.hex])}if(c&&String(c).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let u=null;try{let s=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${s}/tx/${a.id}/status`);d.ok&&(u=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:u}}}}function xs(e,r){let t=ur(r);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"),c=Kn(a,new Uint8Array(64)),u=await St(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[c,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return hs(u)},sign:n=>Kn(Buffer.from(n.messageBase64,"base64"),ss.sign(Buffer.from(n.messageBase64,"base64"),t)),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 St(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),u=(await St(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(u?.err)return{hash:a,status:0};let s=u?.confirmationStatus==="confirmed"||u?.confirmationStatus==="finalized"||u?.confirmations===null;return{hash:a,status:s?1:null}}}}function Ss(e,r={}){for(let t of Object.keys(r||{}))if(Object.prototype.hasOwnProperty.call(e,t))throw new Error(`signer: cannot replace built-in ${t} transport`)}async function Gl({configDir:e,passphraseFile:r,credentialService:t,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:c,Wallet:u}=await import("ethers");if(!r&&!t)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 s=cs(e),d=()=>Object.freeze(Nn(s.policy,s.policyKey,{sequenceAnchorFile:s.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(g=>String(g).startsWith("evm"))&&f.push("chains","spenders");for(let g of f)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(H(l,"poly")&&(Ut(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(H(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(H(l,"hl")){let g=Array.isArray(l.coins)?l.coins.map(String):[],x=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(g.filter(N=>N!=="*"&&N!=="#*").length&&!g.includes("*")&&x.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let p=t?$n(t):$(r),w=kn(s.vault),y=In(w,p),h;try{h=Wn(y,w.meta)}finally{y.fill(0)}(zn(l)||H(l,"hl")||H(l,"poly"))&&fr("evm",h.evm,l.owners),H(l,"btc")&&fr("btc",h.btc,l.owners),H(l,"sol")&&fr("sol",h.sol,l.owners);let m=Array.isArray(l.chains)?l.chains.filter(g=>Number.isInteger(Number(g))&&String(g).trim()!==""):[],b=zn(l);if(b&&(m.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(H(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(H(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=b?new c(l.rpcUrl,Number(m[0])):null,A=h.evm&&(b||H(l,"hl")||H(l,"poly"))?E?new u(h.evm.secret).connect(E):new u(h.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=>A.signTransaction(g),broadcast:async(g,x)=>{if((await E.getNetwork()).chainId!==BigInt(x.chainId))throw new Error("signer: RPC chain mismatch");let N={native:(await E.getBalance(x.from)).toString()},_=await E.broadcastTransaction(g),C=await _.wait(),ve={native:(await E.getBalance(x.from)).toString()};return{hash:C?.hash??_.hash,status:C?.status??null,verifiedBefore:N,verifiedAfter:ve}}}:null,k=E?async g=>As(E,g):void 0,S=new Map,B=g=>g?.surface==="evm-nft"&&String(g?.provider).toLowerCase()==="anvil-nft",F=async(g,x=d(),T="execution")=>{if(!B(g))return null;let N=await fs(E,g,x,{nowMs:Date.now(),signerAddress:A.address}),_=S.get(X(g));return _&&Gn(_,N,T),N},z={...I?{evm:I,"evm-swap":I,"evm-bridge":I,"evm-nft":I}:{},...h.btc?{btc:bs(d,h.btc)}:{},...h.sol?{sol:xs(d,h.sol)}:{},...A&&H(l,"hl")?{hl:gs(d,A)}:{},...A&&H(l,"poly")?{poly:Es(d,A)}:{},...H(l,"lighter")?{lighter:ys(d)}:{}};Ss(z,n);let me=rn({...z,...n}),vt=new Set(Object.keys(z)),It=new Set(Object.keys(n||{})),we=l.surfaces.filter(g=>!vt.has(g)&&!It.has(g));if(we.length)throw new Error(`signer: ${we.join(",")} require local keys or injected surface transports`);let Oe=Date.now(),je=Oe+a,Se=!1,We=()=>Se?!1:Hn.existsSync(s.lock)?(Se=!0,!1):Hn.existsSync(s.vault)&&Date.now()<je,He=()=>(Se=!0,be(s.lock,`disarmed ${new Date().toISOString()}
13
+ `),!0),le=vn({host:o,port:i,token:us(s.token),policy:l,readPolicy:d,isArmed:We,disarm:He,sessionExpiresAtMs:je,nowMs:Date.now,simulate:async(g,x)=>(await F(x,d(),"before simulation"),dt(x,me).simulate(g,x)),estimateNetworkFees:k,sign:async(g,x)=>(await F(x,d(),"before signing"),dt(x,me).sign(g,x)),verifySigned:(g,x,T)=>hn(T?.surface||"evm",g,x,T),broadcast:async(g,x,T)=>(await F(T,d(),"before broadcast"),dt(T,me).broadcast(g,x,T)),confirmArtifact:async(g,x,T)=>{let N=await F(g,T),_=await Is(g,x,T,N);return _===!0&&N&&S.set(x,N),_},decodeEconomics:(g,x)=>zt(g,x),reserveLedger:(g,x)=>{let T=g?.version===1&&g?.surface?g:null,N=T?.artifact||g;if(B(T)){let ve=X(T),Le=S.get(ve);if(!Le||Date.now()-Number(Le.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let Je=ps(x.rpcUrl,N.chainId,T,x,{nowMs:Date.now(),signerAddress:A.address});Gn(Le,Je,"before reservation"),S.set(ve,Je)}let _=T?.tradeId||N?.tradeId;if(!_)throw new Error("ledger: executable artifact requires a tradeId");let C;if(T)C=zt(T,x);else{if(N?.value===void 0)throw new Error("ledger: executable artifact value required");let ve=BigInt(N.value),Le=BigInt(N.gasLimit??0),Je=BigInt(N.maxFeePerGas??N.gasPrice??0);if(Le<=0n||Je<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let mr=Le*Je+BigInt(N.l1FeeWei??0)+BigInt(N.operatorFeeWei??0);C={unit:"wei",value:ve.toString(),notional:(ve+mr).toString(),fee:mr.toString()}}if(Array.isArray(C.units))return or({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:_,units:C.units,policy:x});if(C.value===void 0||C.notional===void 0)throw new Error("ledger: decoded value and notional required");return or({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:_,...C,policy:x})},commitLedger:g=>Ln({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:g.tradeId}),releaseLedger:g=>Bn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:g.tradeId}),settleFailedLedger:g=>Cn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:g.tradeId}),validateReservation:(g,x,T)=>On({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,reservation:g,policy:x,economics:T}),verifyFeeWaiver:(g,x)=>Rn(g,x,s.policyKey),verifyTriggerAttestation:(g,x,T)=>Pn(g,x,s.policyKey,T),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),Ae=setTimeout(()=>le.close(),a);return Ae.unref(),le.on("close",()=>{clearTimeout(Ae)}),le.listen(i,o),le}var At="0x420000000000000000000000000000000000000F";function Yn(e){let r=e?.code;if(r==="CALL_EXCEPTION"||r==="BAD_DATA")return!0;let t=String(e?.shortMessage||e?.message||e);return/network|timeout|ECONN|ENOTFOUND|EAI_AGAIN|server error|fetch failed|socket/i.test(t)?!1:/execution reverted|revert|invalid opcode|function selector|could not decode/i.test(t)}async function As(e,r){if(!oe(r?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:t,Transaction:n}=await import("ethers"),o=new t(["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:r.chainId,to:r.to,data:r.data,value:r.value,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce??0,type:r.type,accessList:r.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let a;try{let c=await e.call({to:At,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",c)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await vs(e,o,r.gasLimit)}}async function vs(e,r,t){let n;try{n=BigInt(t)}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:At,data:r.encodeFunctionData("getOperatorFee",[n])});return r.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Yn(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:At,data:r.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:At,data:r.encodeFunctionData("operatorFeeConstant")}),a=BigInt(r.decodeFunctionResult("operatorFeeScalar",o)[0]),c=BigInt(r.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+c).toString()}catch(o){if(!Yn(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function Is(e,r,t,n=null){return process.stdin.isTTY?(process.stderr.write(ms(e,r,t,n)),process.stdin.resume(),new Promise(o=>{let i=a=>{process.stdin.off("data",i),process.stdin.pause(),o(String(a).trim()===r)};process.stdin.once("data",i)})):!1}export{Gn as assertAnvilAttestationUnchanged,Ss as assertNoBuiltinTransportOverride,Vl as assertSignerIdentity,fs as attestAnvilMarket,ps as attestAnvilMarketSync,us as ensureSignerToken,As as estimateProviderNetworkFees,ms as renderConfirmationArtifact,cs as signerPaths,Gl as startLocalSigner};