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