@oracle-agent/oracle 0.28.30 → 0.29.0

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 zs from"node:path";import st from"node:fs";import co from"node:os";import Ce from"node:path";import{fileURLToPath as uo}from"node:url";var lo=Ce.dirname(uo(import.meta.url)),Qs=Ce.resolve(lo,"../..");function Sr(){return process.env.ORACLE_FAKE_HOME||co.homedir()}function fo(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function ct(){return fo()?process.env.ORACLE_CONFIG_DIR||Ce.join(Sr(),".config","oracle"):Ce.join(Sr(),".config","oracle")}function po(){return Ce.join(ct(),"desk.json")}function mo(){return Ce.join(ct(),"env")}function Le({force:e=!1}={}){if(Le._done&&!e)return Le._result||null;Le._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=mo();if(st.existsSync(o))for(let i of st.readFileSync(o,"utf8").split(/\r?\n/)){let a=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let u=a[2];(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),t(a[1],u)}}catch{}try{let o=po();if(st.existsSync(o)){let i=JSON.parse(st.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)),Le._result=Object.keys(r).length?r:null,Le._result}try{Le()}catch{}import Qn from"node:fs";import re from"node:path";import bs from"node:os";import{createHash as xs,randomBytes as Ss}from"node:crypto";import{execFileSync as As}from"node:child_process";import{fileURLToPath as vs}from"node:url";import{Interface as br,keccak256 as Is}from"ethers";import{Transaction as gr}from"@scure/btc-signer";import{ed25519 as ks}from"@noble/curves/ed25519.js";import Da from"node:http";import{timingSafeEqual as Ua}from"node:crypto";import{createHash as Na,randomBytes as Oa,timingSafeEqual as La}from"node:crypto";import{base58 as kn}from"@scure/base";import{Interface as rn}from"ethers";import{Interface as Lo,MaxUint256 as Co,isAddress as Po,keccak256 as $c,toUtf8Bytes as Fc}from"ethers";import{Interface as No,isAddress as gc}from"ethers";import{isAddress as dc}from"ethers";import{createHash as Eo,createHmac as bo,timingSafeEqual as xo}from"node:crypto";import{readFileSync as ho}from"node:fs";import{homedir as wo}from"node:os";import{join as ut}from"node:path";function go(){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=wo();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||ut(r,".config","oracle")).trim();return[e,ut(t,"exec.env")].filter(Boolean)}return[e,ut(r,".config","oracle","exec.env"),ut(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 go())try{let i=ho(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 ${yo(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 yo(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var Ar=100;function Bt(e){return Array.isArray(e)?`[${e.map(Bt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Bt(e[r])}`).join(",")}}`:JSON.stringify(e??null)}function So(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 Ao(e){let{signature:r,...t}=e;return t}function vo(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 Eo("sha256").update(Buffer.from(r.slice(2),"hex")).digest("hex")}function Io(e,r){let t=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(r??""),"utf8");return t.length!==n.length||t.length===0?!1:xo(t,n)}function ko(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 Rt(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 u=So(o,{required:a});if(a&&!u)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(u){let m=bo("sha256",u).update(Bt(Ao(e))).digest("hex");if(!Io(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>Ar)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(s)||s<0||s>Ar||c>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(m){throw new Error(`${m.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-c),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 m=ko(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==vo(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(m!=null&&m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is hash-bound but the calldata encodes ${m}, not the guard floor ${e.minAmountOut}`)}else{if(m==null){let 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(m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${m}`)}}return!0}var xc=new No(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Oo,isAddress as vc}from"ethers";var Nc=new Oo(["function approve(address spender,uint256 amount) returns (bool)"]),Oc=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 j(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 G(e,r="amount"){let t=Q(e,r);if(t<=0n)throw new Error(`${r} must be positive`);return t}function B(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",u=""]=i.split(".");if(u.length>r)throw new Error(`${t} has more than ${r} decimal places, which would lose precision`);let c=BigInt((a||"0")+u.padEnd(r,"0"));return o?-c:c}var Wc=new Lo(["function approve(address spender,uint256 amount) returns (bool)"]);function vr(e,r){let t=String(e||"").trim();if(!Po(t))throw new Error(`${r} must be an address`);return t.toLowerCase()}function Bo(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>=Co)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var Ir=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),Ro=new Set(["0x39509351","0xf9255c1f"]);function ne(e){let r=String(e||"").toLowerCase();return r.length<10?!1:Ir.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,u=null,c=null;switch(t){case"0x095ea7b3":case"0x39509351":a=o(0),u=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),a=o(1),u=i(2);break;case"0xd505accf":a=o(1),u=i(2);break;case"0x8fcbaf0c":{a=o(1),u=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),a=o(1),u=i(2);break;default:throw new Error(`approval selector ${t} is recognised but not decodable; refusing to bound it`)}if(a==null||u==null)throw new Error("invalid approve calldata");return{spender:vr(a,"approval spender"),token:c==null?null:vr(c,"approval token"),amount:Bo(u,"approval amount",{allowZero:!0}),selector:t,additive:Ro.has(t)}}import{createHash as _o,createHmac as zc,timingSafeEqual as Vc}from"node:crypto";var $o=2,_t=300*1e3,kr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function Fo(e){let r=e==null||e===""?_t:Number(e);return!Number.isFinite(r)||r<0?_t:Math.min(r,kr)}function $t(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map($t).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${$t(e[t])}`).join(",")}}`}function Mo(e){let{prepareHash:r,prepareMac:t,note:n,...o}=e||{};return o}function qo(e){let r=Mo(e);return _o("sha256").update($t(r)).digest("hex")}function Tr(e,{maxAgeMs:r=_t,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)!==$o)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let a=qo(e);if(String(e.prepareHash||"")!==a)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let u=Number(e.preparedAt),c=Number(e.expiresAt),s=Fo(r),d=t-u,l=c-u;if(!Number.isFinite(d)||!Number.isFinite(c)||!Number.isFinite(l)||d<0||l<=0||l>kr||d>s||t>=c)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 lt=e=>String(e||"").toLowerCase(),Do=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),Uo=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function oe(e){try{return Uo.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`)}},Nr=(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 dt(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=>!Do.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,m)=>{try{return BigInt(p)===BigInt(m)}catch{return String(p)===String(m)}};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",lt),Ye(String(e.data||"0x").slice(0,10),r.selectors,"selector",p=>String(p).toLowerCase()),Ye(e.from,r.owners,"owner",lt),ne(e.data)){let p;try{p=Ke(e.data)}catch(g){throw new Error(`policy: malformed approval calldata: ${g?.message||g}`)}Ye(p.spender,r.spenders,"spender",lt),Ye(p.token||e.to,r.erc20Tokens,"ERC-20 token",lt);let m=Z(r.maxApproval,"maxApproval");if(BigInt(p.amount)>m)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 u=e.maxFeePerGas??e.gasPrice,c=Z(u,"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(c+s>Z(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=Nr(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=Nr(r.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-t>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as Or}from"node:crypto";import{Address as jo,NETWORK as Wo,OutScript as Lr,RawTx as Ho,SigHash as Cr,TEST_NETWORK as Jo,Transaction as zo}from"@scure/btc-signer";var Pr=(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`)}},Vo=(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},Go=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,Ko=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),ve=e=>Ko(e)?String(e).toLowerCase():String(e),Ft=(e,r)=>Array.isArray(r)&&r.some(t=>ve(t)===ve(e)),Yo=(e,r)=>Buffer.from(e||[]).equals(Buffer.from(r||[]));function Xo(e){let r=Buffer.from(Ho.encode(e)),t=Or("sha256").update(r).digest();return Buffer.from(Or("sha256").update(t).digest()).reverse().toString("hex")}function Qo(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(Xo(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)||!Yo(e.witnessUtxo.script,r.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return r}function Mt(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(!Ft(t.network,r.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(t.network).toLowerCase())?Wo:["testnet","signet","regtest"].includes(String(t.network).toLowerCase())?Jo:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=zo.fromPSBT(Vo(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=jo(n);for(let l=0;l<o.inputsLength;l++){let f=o.getInput(l);for(let g of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(Go(f[g]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==Cr.DEFAULT&&f.sighashType!==Cr.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let p=Qo(f),m;try{let g=Lr.decode(p.script);if(!["wpkh"].includes(g.type))throw new Error("unsupported input");m=i.encode(g)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!Ft(m,r.owners)||ve(m)!==ve(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...r.changeAddresses||[]].map(l=>ve(l))),u=0n,c=!1,s=[];for(let l=0;l<o.outputsLength;l++){let f=o.getOutput(l),p;try{p=i.encode(Lr.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=ve(p);if(s.push(`${p}:${f.amount}`),m===ve(e.destination)){c=!0,u+=f.amount;continue}if(Ft(p,r.destinations)){u+=f.amount;continue}if(!a.has(m))throw new Error("policy: Bitcoin output destination not allowed")}if(!c)throw new Error("envelope: Bitcoin destination mismatch");let d;try{d=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(d<0n||d>Pr(r.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(u>Pr(r.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:u.toString(),notional:(u+d).toString(),fee:d.toString(),outputs:Object.freeze(s)})}function qt(e,r){let{unit:t,value:n,notional:o,fee:i}=Mt(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}import{createHash as Ut}from"node:crypto";import{base58 as Mr}from"@scure/base";import{getCompiledTransactionMessageDecoder as Zo}from"@solana/transaction-messages";var jt="11111111111111111111111111111111",ei="ComputeBudget111111111111111111111111111111",ti="So11111111111111111111111111111111111111112",qr="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var Dr="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",ri=5000n,ni=2039280n,oi=37095705934669439343138083508754565189542113879843219016388785533085940283555n,q=57896044618658097711785492504343953926634992332820282019728792003956564819949n,Br=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Rr=e=>Ut("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),ii=new Map([[Rr("route"),{name:"route",prefixBytes:0}],[Rr("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),Y=(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`)}},ai=(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||""),si=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,pt=e=>Ut("sha256").update(e).digest("hex");function ft(e,r){try{let t=Buffer.from(Mr.decode(String(e||"")));if(t.length!==32)throw new Error("wrong length");return t}catch{throw new Error(`envelope: invalid Solana ${r}`)}}function K(e){let r=e%q;return r>=0n?r:q+r}function ie(e,r){let t=e;for(;r-- >0n;)t=t*t%q;return t}function ci(e){let t=e*e%q*e%q,n=ie(t,2n)*t%q,o=ie(n,1n)*e%q,i=ie(o,5n)*o%q,a=ie(i,10n)*i%q,u=ie(a,20n)*a%q,c=ie(u,40n)*u%q,s=ie(c,80n)*c%q,d=ie(s,80n)*c%q,l=ie(d,10n)*i%q;return ie(l,2n)*e%q}function ui(e,r){let t=K(r*r*r),n=K(t*t*r),o=ci(e*n),i=K(e*t*o),a=K(r*i*i),u=i,c=K(i*Br),s=a===e,d=a===K(-e),l=a===K(-e*Br);return s&&(i=u),(d||l)&&(i=c),(K(i)&1n)===1n&&(i=K(-i)),!s&&!d?null:i}function li(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=K(r*r),n=ui(K(t-1n),K(oi*t+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function di(e,r){let t=Buffer.concat([...e,ft(r,"program id"),Buffer.from("ProgramDerivedAddress")]),n=Ut("sha256").update(t).digest();if(li(n))throw new Error("envelope: derived Solana program address is on curve");return Mr.encode(n)}function Wt(e,r,t=qr){let n=[ft(e,"owner"),ft(t,"token program"),ft(r,"mint")];for(let o=255;o>=0;o--)try{return di([...n,Buffer.from([o])],Dr)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function fi(e,r){return(r.accountIndices||[]).map(t=>ee(e.staticAccounts[t]))}function Xe(e){return Buffer.from(e.data||[])}function pi(e,r){return ee(e.staticAccounts[r.programAddressIndex])}function Ur(e,r){return Number(r)<e.header.numSignerAccounts}function mi(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 Dt(e,r){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${r} allowlist required`);return e.map(String)}function _r(e,r){let t=Qe(r).map(n=>{let o=Ur(e,n)?"s":"n",i=mi(e,n)?"w":"r";return`${n}:${ee(e.staticAccounts[n])}:${o}:${i}`});return pt(Buffer.from(t.join(`
2
- `)))}function $r(e,r,t){if(r+8>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readBigUInt64LE(r)}function hi(e,r,t){if(r+2>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readUInt16LE(r)}function wi(e,r,t){if(r+4>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readUInt32LE(r)}function gi(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,u=0,c=[];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"),m=t.jupiterRouteVariantPayloads?.[String(d)];if(!Array.isArray(m)||!m.map(String).includes(p))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!==s||h!==s+1)throw new Error("envelope: unsupported Jupiter route-plan token index");u+=g,c.push(Object.freeze({swapVariant:d,variantPayloadHex:p,percent:g,inputIndex:w,outputIndex:h}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(u!==100*r)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function yi(e,r){let t=Xe({data:e}),n=t.subarray(0,8).toString("hex"),o=ii.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 u=8+o.prefixBytes,c=u+4,s=t.length-i;if(s<=c)throw new Error("envelope: malformed Jupiter route payload");let d=wi(t,u,"route plan length"),l=t.subarray(c,s),f=gi(l,d,r);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:d,routePlan:f,routePlanHash:pt(l),inAmount:$r(t,s,"in_amount"),quotedOutAmount:$r(t,s+8,"quoted_out_amount"),slippageBps:hi(t,s+16,"slippage_bps"),platformFeeBps:t[s+18],instructionHash:pt(t)})}function Ei(e,r,t){let n=fi(e,r),o=(i,a)=>{let u=n[i];if(!u)throw new Error(`envelope: Jupiter ${a} account missing`);return u};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 Fr(e,r){return e&&e!==r?e:null}function X(e,r,t){let n=ee(e.staticAccounts[r]);if(!n)throw new Error(`envelope: Jupiter ${t} missing`);return n}function bi(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 xi(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 u=Qe(r);if(u.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=X(e,u[0],"ATA payer"),s=X(e,u[1],"ATA account"),d=X(e,u[2],"ATA owner"),l=X(e,u[3],"ATA mint"),f=X(e,u[4],"ATA system program"),p=X(e,u[5],"ATA token program");if(c!==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!==jt)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!==Wt(t.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:s,debit:i}}function Si(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 u=X(e,i[0],"wrap payer"),c=X(e,i[1],"wrap target"),s=a.readBigUInt64LE(4);if(u!==t.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(s!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return s}function Ai(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||X(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=X(e,o[0],"closeAccount source"),u=X(e,o[1],"closeAccount destination"),c=X(e,o[2],"closeAccount authority");if(a!==n||u!==t.owner||c!==t.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function vi(e,r,t,n,o,i,a){let u=Wt(r.owner,r.artifact.inputMint,a);if(o.userSourceTokenAccount!==u)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=Y(t.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<ni)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 m=pi(e,p);if(m===ei)bi(p,t);else if(m===Dr){let{ata:g,debit:w}=xi(e,p,r,r.artifact,a,c);s.set(g,w)}else if(m===jt)d+=Si(e,p,r,u,i);else if(m===a){let g=Ai(e,p,r,u);g.kind==="syncNative"&&(l=!0),g.kind==="closeAccount"&&(f=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(d>0n&&(!l||!f))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(d!==0n&&d!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...s.values()].reduce((p,m)=>p+m,0n)}function Ii(e){let r;try{r=Zo().decode(ai(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 ki(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 Ti(e,r,t){let n=Y(t.lamportsPerSignature,"lamportsPerSignature");if(n<ri)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=t.maxLamportsPerSignature===void 0?n:Y(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,u=i*o;if(r.exactFeeLamports!==void 0){let s=Y(r.exactFeeLamports,"exactFeeLamports");if(s<a)throw new Error("policy: Solana exact fee below the base signature fee");if(s>u)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=u;if(c>Y(t.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function Ni(e,r,t,n){let o=0n,i=!1;for(let a of e.instructions){if(ee(e.staticAccounts[a.programAddressIndex])!==jt)throw new Error("envelope: unsupported Solana program decoder");let c=a.accountIndices||[];if(c.length!==2||ee(e.staticAccounts[c[0]])!==r.owner)throw new Error("envelope: Solana transfer owner mismatch");let s=ee(e.staticAccounts[c[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>Y(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function Oi(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!==ti)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=si(t);if(!de(o.inputMint,i)||!de(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=Y(o.inAmount,"inAmount"),u=Y(o.outAmount,"outAmount"),c=Y(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>Y(t.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>Y(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(u<=0n||c<=0n||c>u)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=yi(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(!Dt(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!==u)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(c!==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 m=Ei(e,l,f),g=Qe(l),w=f.instruction==="shared_accounts_route"?2:1;if(!Ur(e,g[w]))throw new Error("envelope: Jupiter transfer authority must be signer");if(m.program!==s)throw new Error("envelope: Jupiter program account mismatch");if(m.userTransferAuthority!==r.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(m.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(m.sourceMint!==void 0&&m.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let h=Array.isArray(t.tokenPrograms)&&t.tokenPrograms.length?t.tokenPrograms:[qr];if(!de(m.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let b=Wt(r.owner,o.outputMint,m.tokenProgram);if(m.userDestinationTokenAccount!==b)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=Fr(m.destinationTokenAccount,s);if(E&&E!==b)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(Fr(m.platformFeeAccount,s))throw new Error("policy: Jupiter platform fee account not allowed");if(!Dt(t.jupiterRouteAccountHashes,"Jupiter route account hash").includes(_r(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let A=pt(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,_r(e,l)].join(`
3
- `)));if(!Dt(t.jupiterRouteReviewHashes,"Jupiter route review hash").includes(A))throw new Error("policy: Jupiter route review hash not allowed");let I=vi(e,r,t,l,m,a,m.tokenProgram),k=a+I;if(k>Y(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:k,programs:n}}function Ht(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(c=>!n.includes(c)))throw new Error("envelope: unexpected Solana artifact field");if(!de(t.cluster,r.chains))throw new Error("policy: chain not allowed");let o=Ii(t),i=ki(o,e,r),a=e.action==="transfer"?Ni(o,e,r,i):Oi(o,e,r,i),u=Ti(o,t,r);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+u).toString(),fee:u.toString(),programs:Object.freeze(a.programs)})}function Jt(e,r){let{unit:t,value:n,notional:o,fee:i}=Ht(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}var lu=64*1024;var Li=1e8;function zt(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=Li+r;return Number.isSafeInteger(o)?{encoding:r,outcome:n,side:t,coin:`#${r}`,assetId:o}:null}var Ci=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),Pi=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),Bi=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"}),Ri=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 _i(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 jr(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 $i(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 Fi(e,r,t){let n=jr(e.s,"signed size"),o=jr(e.p,"signed price"),i=n.decimals+o.decimals,a=n.raw*o.raw,u=B(r.notionalUsd,i,"hl: notionalUsd");if(u<=0n||a!==u)throw new Error("hl: signed notional must match");let c=B(t.maxNotionalUsd,i,"hl: maxNotionalUsd");if(a>c)throw new Error("hl: notional exceeds cap")}function Mi(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(j(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(r.hlBuilders)?r.hlBuilders.map(u=>String(u).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=B(r.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>a)throw new Error("hl: order builder fee exceeds cap")}function Wr(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 Hr(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 qi(e){let r=String(e||"").replace(/\/$/,"");if(!Ci.has(r))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return r}function Vt(e){return zt(e)!=null}function Di(e,r){let t=String(e||""),n=Array.isArray(r.coins)?r.coins.map(String):[];if(Vt(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 Ui(e,r,t){let n=Array.isArray(t.hlMarkets)?t.hlMarkets:[];if(n.length){if(!n.some(a=>{if(typeof a=="string"){let[u,c]=String(a).split(":");return u===e&&Number(c)===r}return String(a?.coin)===e&&Number(a?.assetId)===r}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(Vt(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=Bi[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=qi(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!==Ri[n])throw new Error("hl: action type must match kind");let u=t.notionalUsd??0;if(Pi.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let c=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=zt(c);if(!d||d.coin!==c)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(Di(c,r),Ui(c,s,r),n==="hip4-order"&&!Vt(c))throw new Error("hl: HIP-4 orders must use an outcome coin");if(n==="perp-order"||n==="hip3-order"||n==="hip4-order"||n==="perp-bracket"){if(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");$i(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");Wr(d[0],t,s);let m=1;l!=null&&Hr(d[m++],t,s,l,"tp"),f!=null&&Hr(d[m],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");Wr(d[0],t,s)}Fi(d[0],t,r),Mi(t,r),u=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=B(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=B(r.maxNotionalUsd,6,"hl: maxNotionalUsd"),m=l<0n?-l:l;if(m>p)throw new Error("hl: margin notional exceeds cap");u=_i(m,6)}}if(n==="builder-fee-approval"){let c=we(t.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(we(t.action.builder,"signed builder",42).toLowerCase()!==c)throw new Error("hl: signed builder must match");if(!(Array.isArray(r.hlBuilders)?r.hlBuilders.map(m=>String(m).toLowerCase()):[]).includes(c))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=B(d.slice(0,-1),12,"hl: builder fee percent"),f=B(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 c=n==="hype-undelegate";if(typeof t.action.isUndelegate!="boolean"||t.action.isUndelegate!==c)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(u??t.action.wei??0),notional:String(u??0),fee:"0",kind:n,actionType:t.action.type,amount:String(t.action.wei??u??0),coin:t.coin||null,submitTo:i})}import{createHmac as ji}from"node:crypto";var Be="0x"+"00".repeat(32);function Gt(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 Jr({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)),u=String(t||"").toUpperCase(),c=String(n||"");if(u!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let s=a+u+c+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),f=ji("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 Wi(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 Hi(e){let r=typeof e=="bigint"?e:G(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 zr(e,r){let t=G(e.makerAmount,"poly: makerAmount"),n=G(e.takerAmount,"poly: takerAmount");return Hi(r==="BUY"?t:n)}function Ji(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 Vr({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=Wi(e,r);if(j(e.metadata||Be,"poly: metadata").toLowerCase()!==Be)throw new Error("poly: metadata must be zero");if(j(e.builder||Be,"poly: builder").toLowerCase()!==Be)throw new Error("poly: builder must be zero");let a=Ji(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 zi=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"]]),Tu=Object.freeze(Ze.map(e=>e[0])),Vi=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),Gi="0xe111180000d2663c0091e4f400237545b87b996b",Ki="0xe2222d279d744050d28e00520010520000310f59",Gr=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`poly: bounded ${r} required`);return e};function Kr(e){let r=String(e||"").replace(/\/$/,"");if(!zi.has(r))throw new Error("poly: submitTo must be the official Polymarket CLOB");return r}function Yr(e){let r=j(e,"poly: exchange").toLowerCase();if(!Vi.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=Gr(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(j(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(Kr(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(Yr(o.verifyingContract),Yr(t.exchange),j(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==j(t.exchange,"poly: exchange").toLowerCase())throw new Error("poly: exchange/domain mismatch");if(typeof t.negRisk!="boolean")throw new Error("poly: negRisk must be a boolean");let i=t.negRisk?Ki:Gi;if(j(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 u=t.types?.Order;if(!Array.isArray(u)||u.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(u[S]?.name!==Ze[S][0]||u[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 c=String(e.owner||"").toLowerCase();if(j(a.maker,"poly: maker").toLowerCase()!==c)throw new Error("poly: maker must equal owner");if(j(a.signer,"poly: signer").toLowerCase()!==c)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=Gr(t.tokenId,"tokenId",80);if(j(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=G(a.makerAmount,"poly: makerAmount"),p=G(a.takerAmount,"poly: takerAmount"),m=G(t.makerAmount,"poly: prepared makerAmount"),g=G(t.takerAmount,"poly: prepared takerAmount");if(f!==m)throw new Error("poly: signed makerAmount differs from prepared envelope");if(p!==g)throw new Error("poly: signed takerAmount differs from prepared envelope");let w=l==="BUY"?f:p,h=l==="BUY"?p:f,b=B(t.quantity,6,"poly: quantity");if(b<=0n||b!==h)throw new Error("poly: quantity must match CLOB v2 amounts");let E=B(t.price,6,"poly: price");if(E<=0n||E>=1000000n)throw new Error("poly: price must be within (0,1)");if(h*E!==w*1000000n)throw new Error("poly: price must match CLOB v2 amounts");if(B(t.notionalUsdc,6,"poly: notionalUsdc")!==w)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let I=zr(a,l);if(B(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=B(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:Kr(t.submitTo)})}var Yi=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),Kt=14,Xr=(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 Yt(e){let r=String(e||"").replace(/\/$/,"");if(!Yi.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=Xr(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=Yt(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 u=Number(Q(t.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(u)||u<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 c=Xr(t.symbol||t.coin,"symbol",32),s=Array.isArray(r.lighterMarkets)?r.lighterMarkets.map(String):[];if(s.length&&!s.includes(c)&&!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=G(t.baseAmount,"lighter: baseAmount"),l=G(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),m=Number(t.sizeDecimals??0),g=Number(t.priceDecimals??0);if(!Number.isInteger(m)||m<0||m>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(g)||g<0||g>12)throw new Error("lighter: priceDecimals required");let w=m+g,h=d*l,b=B(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=B(r.maxNotionalUsd??Number.MAX_SAFE_INTEGER,w,"lighter: maxNotionalUsd");if(h>E)throw new Error("lighter: notional exceeds cap");let A=R(t.notionalUsd,"lighter: notionalUsd");return Re(t.txType,Kt,"txType"),Object.freeze({unit:"usd",value:String(A),notional:String(A),fee:"0",kind:n,symbol:c,marketIndex:i,side:t.side,baseAmount:f,price:p,submitTo:o,actionType:"create-order",amount:String(A)})}var nn=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var Xt=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}),Xi=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),on=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"}}),Qi=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),mt=new rn(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Qr=new rn(["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"]),Zi=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`)}},Zr=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},ea=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${r} allowlist is empty`);return e},M=(e,r,t)=>{if(!ea(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&&M(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},Ie=e=>String(e||"0x").slice(0,10).toLowerCase(),an=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 ta(e){if(Ie(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 sn(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 ra(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 na(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 en(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,u=Number(o(a,"path offset")),c=n[a+1],s=o(a+(r?3:2),"amountIn"),d=o(a+(r?4:3),"amountOutMinimum"),l=a+u/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:m,outputToken:g}=na(`0x${p}`);return{kind:"action",action:"swap",inputToken:m,outputToken:g,recipient:D(c,"recipient"),amountIn:s,minimumOut:d}}function oa(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 ia(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]}`)),u=o+1+a/32,c=Number(BigInt(`0x${t[u]}`)),d=`0x${r.slice(10+(u+1)*64,10+(u+1)*64+c*2)}`,l=Ie(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return sn(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function aa(e,r){let t=Ie(e),n=on[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{...sn(e,n.layout),selector:t,provider:n.provider};if(n.layout==="exact-input-deadline")return{...en(e,{hasDeadline:!0}),selector:t,provider:n.provider};if(n.layout==="exact-input")return{...en(e,{hasDeadline:!1}),selector:t,provider:n.provider};if(n.layout==="multicall-deadline")return{...ia(e),selector:t,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...oa(e),selector:t,provider:n.provider};if(n.action==="bridge")return{...ra(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function sa(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 ca(e){let r;try{r=Qr.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(c=>!/^0x[0-9a-fA-F]{64}$/.test(c)))throw new Error("envelope: bounded canonical SeaDrop allowlist proof required");if(Qr.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 u=BigInt(r[3]);if(BigInt(t.maxTotalMintableByWallet)<u)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:u,mintPrice:BigInt(t.mintPrice),startTime:i,endTime:a,dropStageIndex:BigInt(t.dropStageIndex),proof:n}}function ua(e,r){let t=Ie(e);if(String(r).toLowerCase()==="nft-mint")return la(e);let n=Qi[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{...sa(e),selector:t,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...ca(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function la(e){let r=Ie(e);if(r==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let t=Zi[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 ht(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 cn(e,r,t,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=O(e.owner,"owner"),u=e.artifact,c=Number(u?.chainId??ht(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(M(c,r.chains,"chain"),u?.owner!==void 0&&O(u.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let s=ht(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)!==c)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(M(Ie(p.data),r.selectors,"selector"),d+=v(p.value??0,"value"),l+=v(p.gasLimit,"gasLimit"),f+=an(p),oe(c)&&(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:c,owner:a,totalValue:d,totalGas:l,totalFee:f}}function un(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();M(i,r.providers,"provider");let a=cn(e,r,o,{nowMs:t}),u=[],c=-1;for(let m=0;m<a.transactions.length;m++){let g=a.transactions[m],w=ta(g.data),h;if(w){if(c!==-1)throw new Error("envelope: approval must be before action");if(v(g.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let A=O(g.to,"approval token");if(M(A,r.tokens,"token"),M(w.spender,r.spenders,"spender"),w.amount>v(r.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...w,token:A,index:m}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");M(g.to,r.destinations,"destination"),h={...aa(g.data,i),target:O(g.to,"action target"),index:m},c=m}let b=v(g.value??0,"value"),E=v(g.gasLimit,"gasLimit");u.push({...h,value:b,gas:E,fee:an(g)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let s=u[c],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(M(s.inputToken,r.tokens,"input token"),M(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(Rt(e.autoSlippage,{nowMs:t,chainId:a.chainId,venue:i,tx:a.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(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=u.filter(m=>m.kind==="approval");if(!new Set([...Xi,...Array.isArray(r.nativeInputTokens)?r.nativeInputTokens.map(m=>String(m).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:u,action:s,provider:i,authenticatedQuote:p}}function da(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"),u=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")!==u)throw new Error("envelope: Anvil attestation payment token mismatch");let c=Number(e.paymentTokenDecimals??e.artifact?.paymentTokenDecimals);if(!Number.isSafeInteger(c)||c<0||c>255||Number(n.paymentTokenDecimals)!==c)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 m=Object.entries(r.anvilRuntimeCodeHashes||{}).find(([w])=>w.toLowerCase()===i)?.[1];if(!m||String(m).toLowerCase()!==p)throw new Error("policy: Anvil runtime code hash is not reviewed");let g=Object.entries(r.nftPaymentTokenCaps||{}).find(([w])=>w.toLowerCase()===u)?.[1];if(!g||Number(g.decimals)!==c)throw new Error("policy: Anvil payment token decimals are not reviewed");return Object.freeze({...n,market:i,collection:a,paymentToken:u,paymentTokenDecimals:c,runtimeCodeHash:p,blockNumber:f})}function tn(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[u,c]of i.slice(1))if(v(u,c)!==a)throw new Error(`envelope: Anvil ${r} exact settlement limit mismatch`);return a}function ln(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=cn(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,m=O(e.destination,"Anvil market");if(O(p.to,"Anvil action target")!==m)throw new Error("envelope: Anvil action target mismatch");M(m,r.destinations,"destination");let g=O(e.contract??e.artifact?.contract,"NFT contract");if(et(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");et(h,r.erc20Tokens,"ERC20 token");let b=da(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=tn(e,I),P=Object.entries(r.nftPaymentTokenCaps||{}).find(([me])=>me.toLowerCase()===h)?.[1];if(!P)throw new Error("policy: Anvil payment-token cap required");if(S>v(P.maxPerTradeRaw,"maxPerTradeRaw"))throw new Error("policy: Anvil payment amount exceeds cap");if(e.preconditions?.allowanceVerified!==!0||v(e.preconditions?.allowanceRaw,"allowanceRaw")<S)throw new Error("envelope: Anvil pre-existing allowance proof required");let F=mt.decodeFunctionData("buySpecificNFT",p.data);if(mt.encodeFunctionData("buySpecificNFT",[F[0],F[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil buy calldata");if(BigInt(F[0])!==E)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(F[1])!==S)throw new Error("envelope: Anvil maxCost mismatch");k={kind:"nft",action:"buy",tokenId:E,maxPaymentTokenAmountRaw:S,target:m}}else if(I==="sell"){let S=e.preconditions||{},P=O(S.approvedAddress,"NFT approval address");if(S.nftApprovalVerified!==!0||P!==m&&S.approvedForAll!==!0)throw new Error("envelope: Anvil pre-existing NFT approval proof required");let F=tn(e,I),V=mt.decodeFunctionData("sellNFT",p.data);if(mt.encodeFunctionData("sellNFT",[V[0],V[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil sell calldata");if(BigInt(V[0])!==E)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(V[1])!==F)throw new Error("envelope: Anvil minPayout mismatch");k={kind:"nft",action:"sell",tokenId:E,minPayoutRaw:F,target:m}}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&&Tr(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],u=Ie(a.data);M(u,r.selectors,"selector"),M(a.to,r.destinations,"destination");let c=ua(a.data,n),s=O(e.contract??e.artifact?.contract,"NFT contract");if(et(s,r.nftContracts,"NFT contract"),(c.contract||O(a.to,"NFT contract"))!==s)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==o.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&et(c.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(c.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(c.mintType==="allowlist"){let p=BigInt(Math.floor(t/1e3));if(c.startTime>p||c.endTime<=p)throw new Error("policy: SeaDrop allowlist stage is not open");if(c.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:[{...c,target:O(a.to,"mint target"),value:o.totalValue,gas:o.totalGas,fee:o.totalFee}]}}function fa(e,{localsWaiver:r=!1}={}){if(!(e in Xt))throw new Error("fee: unknown action");return r?0:Xt[e]}function rt(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 u=tt(e.surface,"surface",16);if(!nn.has(u))throw new Error("envelope: unsupported public surface");let c=tt(e.action,"action",32);M(u,r.surfaces,"surface"),M(c,r.actions,"action"),M(e.owner,r.owners,"owner"),M(e.destination,r.destinations,"destination");let s=Zr(r.maxTtlMs,"maxTtlMs"),d=Zr(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(u==="evm-swap"||u==="evm-bridge")un(e,r,{nowMs:t,routeAttestationSecret:o});else if(u==="evm-nft")ln(e,r,{nowMs:t});else if(u==="evm"){if(!["transfer","approve"].includes(c))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(String(l.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(String(l.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: artifact from mismatch with owner");dt({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},r,{nowMs:t,networkFees:i,requireNetworkFees:a});let m=String(l.data||"0x").toLowerCase(),g=v(l.value,"EVM value");if(m==="0x"){if(g===0n)throw new Error("envelope: native EVM transfer value required")}else if(ne(m)){if(g!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else u==="btc"?qt(e,r):u==="sol"?Jt(e,r):u==="hl"?ge(e,r):u==="poly"?ye(e,r):u==="lighter"&&Ee(e,r);let f=Number(e.fee?.oracleFeeBps)===0&&Xt[c]!==0;if(e.fee?.waiver||f&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(f&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let p=fa(c,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==p)throw new Error("fee: final artifact fee mismatch");return!0}var Qt=Object.freeze([...nn]),Uu=Object.freeze({...on});function Zt(e,r){if(e.surface==="hl")return ge(e,r);if(e.surface==="poly")return ye(e,r);if(e.surface==="lighter")return Ee(e,r);if(e.surface==="btc")return qt(e,r);if(e.surface==="sol")return Jt(e,r);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let t=un(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=ln(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(),u=t.totalFee,c=[{unit:`erc20:${t.paymentToken}`,value:i,notional:i,fee:"0"},{unit:"wei",value:a,notional:(t.totalValue+u).toString(),fee:u.toString()}].sort((s,d)=>s.unit<d.unit?-1:s.unit>d.unit?1:0);return Object.freeze({units:c})}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 dn(e={}){let r={};for(let t of Qt){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 wt(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 yn}from"node:crypto";import{ed25519 as Aa}from"@noble/curves/ed25519.js";import{base58 as Sn}from"@scure/base";import{RawTx as nr,SigHash as ke,Transaction as or}from"@scure/btc-signer";import{Transaction as ir,keccak256 as En,verifyTypedData as bn}from"ethers";import{encode as pa}from"@msgpack/msgpack";import{keccak256 as ma,verifyTypedData as ha}from"ethers";var $e=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),er=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function fn(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 wa(e,r,{vaultAddress:t=null,expiresAfter:n=null}={}){let i=[Buffer.from(pa(e)),fn(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]),fn(n)),ma(Buffer.concat(i))}function tr(e,r,{isMainnet:t=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:t?"a":"b",connectionId:wa(e,r,{vaultAddress:n,expiresAfter:o})}}function pn(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=tr(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(er.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 mn({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=tr(r,t,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData($e,er,a)}function hn({signature:e,action:r,nonce:t,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:a=null}){try{let u=tr(r,t,{isMainnet:n,vaultAddress:i,expiresAfter:a}),c=ha($e,er,u,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var ga=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function rr(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)rr(r);return}for(let r of Object.values(e))rr(r)}}}function ya(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 rr(e),JSON.parse(JSON.stringify(e))}function gt(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 Ea(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 wn(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=>wn(e[a],t,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${t}`);return i[0]}function ba(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=Me(e,r,n);if(BigInt(o)!==gt(t,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function xa(e,r,t,n){let o=Me(e,r,n,{signed:!0});if(BigInt(o)!==Ea(t,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Sa(e){let r={};for(let[t,n]of ga.entries()){let o=n.filter(a=>e[a]!==void 0&&e[a]!==null);if(!o.length)continue;let i=o.map(a=>{let u=e[a];if(t<3)return wn(u,n[0]);if(typeof u!="string"||u.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return u});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);r[n[0]]=i[0]}return r}function nt(e,r){let t=ya(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"),u=Fe(t,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),c=Fe(t,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),s=xa(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)!==gt(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==gt(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==gt(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let p=ba(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 m=p===1,g=e.side==="sell";if(m!==g)throw new Error("lighter: signed IsAsk must match the prepared side");let w=Me(t,["txType","tx_type","TxType"],"txType");if(w!==Kt)throw new Error("lighter: signed txType must be official create-order");let h={...Sa(t),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:a,ReduceOnly:u,TriggerPrice:c,OrderExpiry:s,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(f),IsAsk:m?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!==(m?1:0)||E.txType!==w)throw new Error("lighter: canonical tx_info mutated");return{txType:w,txInfo:b,submitTo:Yt(e.submitTo)}}function gn(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var qe=e=>{if(typeof e!="string"||e.length===0||e.length>262144||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return null;let r=Buffer.from(e,"base64");return r.toString("base64")===e?r:null},yt=e=>String(e||"").toLowerCase();function va(e,r){if(typeof e!="string")return!1;let t,n;try{t=ir.from(e),n=ir.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 yt(t.from)!==yt(r.from)||yt(t.to)!==yt(r.to)?!1:t.unsignedHash===n.unsignedHash}function Ia(e){let r=Buffer.from(nr.encode(e)),t=yn("sha256").update(r).digest();return Buffer.from(yn("sha256").update(t).digest()).reverse().toString("hex")}function xn(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Ia(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 ka(e,r){let t=qe(e),n=qe(r.psbt);if(!t||!n)return!1;try{let o=or.fromPSBT(n),i=or.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 u=i.getInput(a),c=o.getInput(a);if(!xn(c)||!xn(u))return!1;let s=(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(nr.encode(h)).equals(Buffer.from(nr.encode(b)))}catch{return s(h,b)}};if(!!u.witnessUtxo!=!!c.witnessUtxo||u.witnessUtxo&&(BigInt(u.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!s(u.witnessUtxo.script,c.witnessUtxo.script))||!d(u.nonWitnessUtxo,c.nonWitnessUtxo)||!s(u.redeemScript,c.redeemScript)||!s(u.witnessScript,c.witnessScript)||u.sighashType!==void 0&&u.sighashType!==ke.DEFAULT&&u.sighashType!==ke.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===ke.ALL,f=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===ke.ALL:!1;for(let h of u.partialSig||[]){let b=Array.isArray(h)?h[1]:h;if(!l(b))return!1}if(u.tapKeySig&&!f(u.tapKeySig))return!1;for(let h of u.tapScriptSig||[]){let b=Array.isArray(h)?h[1]:h;if(!f(b))return!1}let p=h=>h[h.length-1]===ke.ALL,m=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(!m(E)||!p(E))return!1;b=!0;continue}if(E.length===64){b=!0;continue}if(E.length===65){if(E[64]!==ke.ALL&&E[64]!==ke.DEFAULT)return!1;b=!0}}return b};if(u.finalScriptWitness){let h;if(Array.isArray(u.finalScriptWitness))h=u.finalScriptWitness;else if(u.finalScriptWitness instanceof Uint8Array){let b=u.finalScriptWitness,E=k=>{let S=b[k];return S===void 0?null:S<253?{value:S,next:k+1}:S===253?{value:b[k+1]|b[k+2]<<8,next:k+3}:null},A=E(0);if(!A)return!1;h=[];let I=A.next;for(let k=0;k<A.value;k++){let S=E(I);if(!S||I+S.value>b.length)return!1;h.push(b.slice(S.next,S.next+S.value)),I=S.next+S.value}if(I!==b.length)return!1}else return!1;if(!h.length||!g(h))return!1}if(u.finalScriptSig instanceof Uint8Array&&u.finalScriptSig.length){let h=u.finalScriptSig,b=[],E=0;for(;E<h.length;){let A=h[E];if(A>=1&&A<=75){if(E+1+A>h.length)return!1;b.push(h.slice(E+1,E+1+A)),E+=1+A;continue}if(A===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(![u.partialSig,u.tapKeySig,u.tapScriptSig,u.finalScriptSig,u.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function An(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 Ta(e,r,t){let n=qe(e),o=qe(r.messageBase64);if(!n||!o)return!1;let i=An(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let u=n.subarray(i.offset,a),c=n.subarray(a);if(!c.equals(o))return!1;try{let s=Sn.decode(String(t));return s.length===32&&Aa.verify(u,c,s)}catch{return!1}}function vn(e,r,t,n){if(String(e).startsWith("evm"))return va(r,t);if(e==="btc")return ka(r,t);if(e==="sol")return Ta(r,t,n?.owner);if(e==="hl"){if(t?.typedData?.domain&&t.typedData.types&&t.typedData.message)try{return String(bn(t.typedData.domain,t.typedData.types,t.typedData.message,r)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return hn({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(bn(t.domain,t.types,t.message,r)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return nt(t,r),!0}catch{return!1}return!1}function In(e,r){try{if(String(e).startsWith("evm"))return ir.from(r).hash;if(e==="btc"){let t=qe(r);if(!t)return null;let n=or.fromPSBT(t);return n.finalize(),n.extract(),n.id}if(e==="sol"){let t=qe(r);if(!t)return null;let n=An(t);if(!n||n.value!==1)return null;let o=t.subarray(n.offset,n.offset+64);return o.length===64?Sn.encode(o):null}if(e==="hl"&&typeof r=="string"&&r.startsWith("0x"))return En(r);if(e==="poly"&&typeof r=="string"&&r.startsWith("0x"))return En(r)}catch{}return null}var Ca=e=>String(e||"").toLowerCase();function J(e){return Na("sha256").update(JSON.stringify(e)).digest("hex")}function xt(e,r,t={}){return dt(e,r,t)}async function Pa(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 Tn(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 Et=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=Oa(32).toString("hex");return this.#e.set(o,{digest:J(r),owner:Ca(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(J(t),"hex");if(!La(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(r)),n}clear(){this.#e.clear()}};function Ba(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 Ra(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 bt(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=kn.decode(t);return n.length===64&&kn.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 Nn(e,r,t){return!bt(e,r)||!bt(e,t)?!1:e==="sol"?String(r)===String(t):String(r).toLowerCase()===String(t).toLowerCase()}function _a(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 ar({artifact:e,envelope:r,nonce:t,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:u}){let c=_a(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(r?.triggerAttestation,e,u())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(a)return n.confirmations.consume(t,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=u())throw new Error("confirmation: expired nonce");return i}function $a(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Fa(e,r){return e&&$a(e.surface)?ht(e):[r]}function Ma(e,r){let t=e?.hash??null,n=e?.transactionHash??null;if(t!=null&&n!=null&&!Nn(r,t,n))throw new Error("signer: receipt reports conflicting transaction hashes");return t||n||null}function qa(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:Ra(t,n)}}async function sr(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=Fa(n,o),a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,u=()=>typeof t.nowMs=="function"?t.nowMs():t.nowMs??Date.now(),c=await ar({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:null,consumeNonce:!0,nowMs:u}),s=J(e),d=(w={})=>{n?rt(n,a,w):(xt(o,a,{nowMs:w.nowMs,networkFees:w.networkFees,requireNetworkFees:w.requireNetworkFees}),Ba(o))},l=async w=>{let h=n&&!String(n.surface||"").startsWith("evm")?void 0:await Pa(w,t);return{nowMs:u(),verifyFeeWaiver:t.verifyFeeWaiver,routeAttestationSecret:t.routeAttestationSecret,networkFees:h,requireNetworkFees:oe(w?.chainId)}};d({nowMs:u(),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,m=[];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(Tn(w,h.networkFees,h.requireNetworkFees),!t.isArmed())throw new Error("signer: disarmed before signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=await ar({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:c,consumeNonce:!1,nowMs:u}),d(h),t.validateReservation(f,a,n&&typeof t.decodeEconomics=="function"?t.decodeEconomics(n,a):void 0),p=!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(J(e)!==s)throw new Error("signer: artifact mutated after signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=await ar({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:c,consumeNonce:!1,nowMs:u});let E=await l(w);Tn(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(b,w,n),I=A?.status,k=n?.surface||"evm",S=Ma(A,k),P=In(k,b);if(!Nn(k,S,P))throw new Error("signer: receipt transaction hash does not match signed bytes");if(I===0||I==="0x0")throw bt(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(!bt(k,S))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(qa(A,S))}}catch(w){throw p||t.releaseLedger(f),w}if(t.commitLedger(f),m.length===1){let w={receipt:m[0]};return n?.surface==="evm-bridge"&&(w.originStatus="success",w.destinationStatus="unverified",w.destinationSuccess=!1,w.note="Origin-chain receipts do not prove destination-chain settlement."),w}let g={receipts:m,status:"success"};return n?.surface==="evm-bridge"&&(g.originStatus="success",g.destinationStatus="unverified",g.destinationSuccess=!1,g.note="Origin-chain receipts do not prove destination-chain settlement."),g}var On=new Set(["127.0.0.1","::1","localhost"]),ja=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&Ua(t,n)},N=(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 Wa(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 ot=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(!On.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 c of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[c]!="function")throw new Error(`signer: ${c} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let t=e.confirmations||new Et,n=e.pending||new Map;function o(c){let s=c.artifact?.version===1&&c.artifact?.surface?c.artifact:null,d=s?.artifact||c.artifact||{};return{id:c.digest.slice(0,8),digest:c.digest,surface:s?.surface||"evm",action:s?.action||"evm",chain:d.chainId??d.network??null,to:d.to||s?.destination||null,value:d.value??null,createdAtMs:c.createdAtMs}}function i(c){let s=String(c||"").trim().toLowerCase().replace(/^0x/,"");return s?[...n.values()].filter(d=>d.digest.toLowerCase().startsWith(s)||d.digest.slice(0,8)===s):[...n.values()]}let a=e.origin||`http://${r}`;return Da.createServer(async(c,s)=>{try{let d=String(c.headers.authorization||"").replace(/^Bearer /i,"");if(!ja(d,e.token))return N(s,401,{error:"unauthorized"});let l=Wa(c.headers.host);if(!On.has(l))return N(s,403,{error:"host refused"});if(c.headers.origin&&c.headers.origin!==a)return N(s,403,{error:"origin refused"});if(c.method==="GET"&&c.url==="/status"){let f=typeof e.readPolicy=="function"?e.readPolicy():e.policy,p=new Set(Qt),m=Array.isArray(f?.surfaces)?f.surfaces.filter(g=>typeof g=="string"&&p.has(g)):[];return N(s,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:m,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(c.method==="POST"&&c.url==="/disarm")return e.disarm(),t.clear(),n.clear(),N(s,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(c.method))return N(s,405,{error:"request refused"});if(c.method==="POST"&&String(c.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return N(s,415,{error:"request refused"});if(c.method==="GET"&&c.url==="/pending"){let f=[...n.values()].map(o);return N(s,200,{ok:!0,armed:e.isArmed?.()===!0,count:f.length,items:f})}if(c.method==="POST"&&c.url==="/pending"){if(e.autonomous===!0)return N(s,403,{error:"autonomous signer does not queue human approvals"});let p=(await ot(c)).artifact;if(!p||typeof p!="object")return N(s,400,{error:"artifact required"});let m=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(m?.confirmationMode!=="exact-human")return N(s,403,{error:"exact-human policy required"});let g=typeof e.nowMs=="function"?e.nowMs():Date.now();if(p?.version===1&&p?.surface)rt(p,m,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:h,...b}=p||{};xt(b,m,{nowMs:g})}let w=J(p);return n.set(w,{artifact:p,digest:w,createdAtMs:g}),N(s,200,{ok:!0,...o(n.get(w))})}if(c.method==="POST"&&c.url==="/ack"){if(e.autonomous===!0)return N(s,403,{error:"autonomous signer does not accept messaging acks"});let f=await ot(c),p=i(f.digest||f.id);if(p.length===0)return N(s,404,{error:"no pending artifact"});if(p.length>1)return N(s,409,{error:"ambiguous digest; pass more hex"});let m=p[0];if((typeof e.readPolicy=="function"?e.readPolicy():e.policy)?.confirmationMode!=="exact-human")return N(s,403,{error:"exact-human policy required"});if(e.isArmed?.()!==!0)return N(s,403,{error:"signer is disarmed"});n.delete(m.digest);let w=t.issue({artifact:m.artifact,owner:m.artifact?.owner??m.artifact?.from,ttlMs:f.ttlMs}),h=await sr(m.artifact,w,{...e,confirmations:t});return N(s,200,{ok:!0,executed:!0,confirmationNonce:w,digest:m.digest,id:m.digest.slice(0,8),result:h})}if(c.method==="POST"&&c.url==="/deny"){let f=await ot(c),p=i(f.digest||f.id);return p.length===0?N(s,404,{error:"no pending artifact"}):p.length>1?N(s,409,{error:"ambiguous digest; pass more hex"}):(n.delete(p[0].digest),N(s,200,{ok:!0,denied:!0,id:p[0].digest.slice(0,8)}))}if(c.method==="POST"&&c.url==="/confirm"){if(e.autonomous===!0)return N(s,403,{error:"autonomous signer does not issue human confirmation nonces"});let f=await ot(c),p=J(f.artifact),m=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(m?.confirmationMode!=="exact-human")return N(s,403,{error:"exact-human policy required"});let g=typeof e.nowMs=="function"?e.nowMs():Date.now();if(f.artifact?.version===1&&f.artifact?.surface)rt(f.artifact,m,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:w,...h}=f.artifact||{};xt(h,m,{nowMs:g})}return typeof e.confirmArtifact!="function"?N(s,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(f.artifact,p,m)!==!0?N(s,400,{error:"exact human confirmation refused"}):N(s,200,{confirmationNonce:t.issue({artifact:f.artifact,owner:f.artifact?.owner??f.artifact?.from,ttlMs:f.ttlMs})})}if(c.method==="POST"&&c.url==="/execute"){let f=await ot(c),p=await sr(f.artifact,f.confirmationNonce,{...e,confirmations:t});return N(s,200,p)}return N(s,404,{error:"not found"})}catch(d){e.onError?.(String(d?.message||d));let l=String(c.url||"");return l==="/pending"||l==="/ack"||l==="/deny"?N(s,400,{error:String(d?.message||"request refused").slice(0,300)}):N(s,400,{error:"request refused"})}})}import{createCipheriv as hl,createDecipheriv as Ha,randomBytes as Ja,scryptSync as za}from"node:crypto";import L from"node:fs";import De from"node:path";var Va="ORACLE-LOCAL-VAULT",Ga=1,At=Object.freeze({N:1<<17,r:8,p:1}),Ka=256*1024*1024,Ya=16*1024;function St(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 Xa(e,r,t=At){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return za(n,r,32,{...t,maxmem:Ka})}function Cn(e,r){if(e?.magic!==Va||e?.version!==Ga)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!==At.N||e.kdf.r!==At.r||e.kdf.p!==At.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=St(e.kdf.salt,32,"salt"),o=St(e.cipher.iv,12,"iv"),i=St(e.tag,16,"tag"),a=St(e.ciphertext,1,"ciphertext",{max:Ya}),{ciphertext:u,tag:c,...s}=e,d=Xa(r,n);try{let l=Ha("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 Qa(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 Za(e){let r=De.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(Qa(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 Pn(e){return JSON.parse(_(e))}function be(e,r){L.mkdirSync(De.dirname(e),{recursive:!0,mode:448}),Za(e);let t=De.join(De.dirname(e),`.${De.basename(e)}.${process.pid}.${Ja(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(De.dirname(e),"r");try{L.fsyncSync(o)}finally{L.closeSync(o)}}catch(n){try{L.unlinkSync(t)}catch{}throw n}}var Bn=/^0x[0-9a-fA-F]+$/,es=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});function ts(e){let r=process.env[`ORACLE_PRIVATE_RELAY_${Number(e)}`];if(!r)return null;let t=r.split(",").map(n=>n.trim()).filter(Boolean);return t.length?t:null}function rs(e,{requirePrivate:r=!1}={}){let t=Number(e);if(!Number.isInteger(t))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=es[t]||{name:`chain-${t}`,mode:"public-only",endpoints:[]},o=ts(t),i=o||n.endpoints,a=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&a!=="public-only";if(r&&!u)throw new Error(`private relay: no keyless private endpoint for chain ${t} (${n.name}); set ORACLE_PRIVATE_RELAY_${t} to force one, or allow public fallback`);return{chainId:t,name:n.name,mode:a,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function Rn(e,{chainId:r,requirePrivate:t=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!Bn.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let a=rs(r,{requirePrivate:t}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let c=[];for(let s of a.endpoints){let d=new AbortController,l=setTimeout(()=>d.abort(),i);try{let f=await u(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendRawTransaction",params:[e]}),signal:d.signal}),p=await f.text(),m=null;try{m=JSON.parse(p)}catch{}if(m&&m.result&&Bn.test(m.result))return{hash:m.result,endpoint:s,mode:a.mode,chainId:a.chainId,fellBack:!1};c.push({endpoint:s,error:m&&m.error&&m.error.message||`http ${f.status}`})}catch(f){c.push({endpoint:s,error:String(f&&f.message||f).slice(0,160)})}finally{clearTimeout(l)}}if(n&&!t)return{fellBack:!0,mode:a.mode,chainId:a.chainId,attempts:c};throw new Error(`submitPrivate: all private endpoints failed for chain ${a.chainId} (${c.map(s=>`${s.endpoint}:${s.error}`).join("; ")||"none configured"})`)}import{createHmac as os,randomBytes as is,timingSafeEqual as as}from"node:crypto";import U from"node:fs";import Te from"node:path";import{homedir as cr}from"node:os";import{join as ur}from"node:path";var _n=process.env.ORACLE_PUBLIC_DESKTOP==="1",ns=_n?process.env.ORACLE_CONFIG_DIR||ur(cr(),".config","oracle"):ur(cr(),".config","oracle"),Sl=_n?ns:ur(cr(),".config","mad-desk");var Tl="0".repeat(64),Nl=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 vt(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(vt).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+vt(e[t])).join(",")+"}"}var Ol=Promise.resolve();function je(e,r){if(!e)throw new Error("ledger: separate freshness anchor required");let t=a=>{try{return U.realpathSync(a)}catch{return Te.resolve(a)}},n=t(Te.dirname(Te.resolve(e))),o=t(Te.dirname(Te.resolve(r))),i=(a,u)=>u===a||u.startsWith(a+Te.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var ss=864e5,z=(e,r)=>os("sha256",r).update(vt(e)).digest("hex"),se=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&as(t,n)},cs=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:r,...t}=e;return t};function us(e,r){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!se(e.integrity.mac,z(e.policy,r)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function kt(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,z(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 ls(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 u=kt(e,t);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(r),policyMac:String(n)};i&&(a.ledgerInitialized=!0),be(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:z(a,t)}})+`
4
- `)}function ds(e,r){let t=kt(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 ls(e,t.sequence,r,t.policyMac,{ledgerInitialized:!0}),!0}function $n(e,r,{sequenceAnchorFile:t}={}){if(!t)throw new Error("policy: sequence anchor required");let n=_(r),o;try{o=JSON.parse(_(e))}catch(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=us(o,n);je(t,e);let a=kt(t,n),u=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(u!==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 it(e,r,t,n,o){let i=`${e}.continuity`,a;try{let u=JSON.parse(_(e));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!se(u?.integrity?.mac,z(u.ledger,r)))throw new Error("integrity verification failed");if(a=u.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(u){if(u?.code==="ENOENT"){if(U.existsSync(i)||U.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=kt(o,r);if(c.present&&c.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:t,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}try{let u=JSON.parse(_(i));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!se(u?.integrity?.mac,z(u.marker,r)))throw new Error("continuity verification failed");if(u.marker?.version===2&&(u.marker.sequence!==a.sequence||!se(u.marker.ledgerMac,z(a,r))))throw new Error("continuity rollback detected");if(u.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(U.existsSync(n)&&(u.marker?.version!==2||a.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(u.marker?.version===2){let c=JSON.parse(_(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!se(c?.integrity?.mac,z(c.marker,r))||c.marker?.version!==1||c.marker.sequence!==a.sequence||!se(c.marker.ledgerMac,z(a,r)))throw new Error("checkpoint rollback detected")}}catch(u){throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}if(t-a.windowStartMs>=ss){let u=a.entries.map(c=>c.state==="reserved"?c:Array.isArray(c.units)?{...c,state:"consumed",units:c.units.map(s=>({...s,value:"0",notional:"0"}))}:{...c,state:"consumed",value:"0",notional:"0"});return{windowStartMs:t,entries:u,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function fs(e){return Array.isArray(e.units)?e.units:[{unit:e.unit||"wei",value:e.value,notional:e.notional,fee:e.fee}]}function xe(e,r,t){return e.reduce((n,o)=>{let i=fs(o).find(a=>a.unit===t);return i?n+BigInt(i[r]??0):n},0n)}function lr(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 u=n.fee===void 0?0n:BigInt(n.fee);if(u<0n)throw new Error("ledger: unit fee must be non-negative");return{unit:o,value:i.toString(),notional:a.toString(),fee:u.toString()}});return t.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),t}function ps(e,r){let t=e[r];if(t==null||t==="")throw new Error(`ledger: ${r} required`);return Q(t,`ledger: ${r}`)}function It(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(c=>e[c]!==void 0&&e[c]!==null&&e[c]!=="");if(n.length===t.length)return t.map(c=>ps(e,c));if(n.length>0){let c=t.filter(s=>!n.includes(s));throw new Error(`ledger: ${c[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=B(o,6,"ledger: maxDailyNotionalUsdc"),u=B(i,6,"ledger: maxPerTradeUsdc");return[a,a,u]}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 at(e,r){let t=`${e}.lock`,n=is(16).toString("hex"),o;try{o=U.openSync(t,U.constants.O_CREAT|U.constants.O_EXCL|U.constants.O_WRONLY|(U.constants.O_NOFOLLOW||0),384),U.writeFileSync(o,n),U.fsyncSync(o)}catch(i){throw o!==void 0&&U.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return r()}finally{U.closeSync(o);try{_(t)===n&&U.unlinkSync(t)}catch{}}}function Ue(e,r,t,n,o){let i=`${e}.continuity`,a={...r,sequence:(r.sequence??0)+1},u=z(a,t);be(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:u}})+`
5
- `);let c={version:2,sequence:a.sequence,ledgerMac:u};be(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:z(c,t)}})+`
6
- `);let s={version:1,sequence:a.sequence,ledgerMac:u};U.mkdirSync(Te.dirname(n),{recursive:!0,mode:448}),be(n,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:z(s,t)}})+`
7
- `),o&&ds(o,t)}function dr({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:u=0,fee:c,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");je(t,e);let p=_(r);return at(e,()=>{let m=it(e,p,l,t,n);if(m.entries.some(w=>String(w.tradeId)===f))throw new Error("ledger: replayed tradeId");let g;if(s!==void 0){let w=lr(s);for(let h of w){let[b,E,A]=It(d,h.unit),I=BigInt(h.value),k=BigInt(h.notional);if(k>A)throw new Error("ledger: per-trade cap exceeded");if(xe(m.entries,"value",h.unit)+I>b||xe(m.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(u),[b,E,A]=It(d,i);if(w<0n||h<0n||h>A)throw new Error("ledger: per-trade cap exceeded");if(xe(m.entries,"value",i)+w>b||xe(m.entries,"notional",i)+h>E)throw new Error("ledger: daily cap exceeded");g={tradeId:f,unit:i,value:w.toString(),notional:h.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:l}}return m.entries.push(g),Ue(e,m,p,t,n),structuredClone(g)})}function Fn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:u=Date.now()}){je(t,e);let c=_(r);return at(e,()=>{let s=it(e,c,u,t,n),d=s.entries.find(g=>String(g.tradeId)===String(o?.tradeId??"")&&g.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let g=lr(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=lr(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]=It(i,w.unit);if(BigInt(w.notional)>E)throw new Error("ledger: per-trade cap exceeded");if(xe(s.entries,"value",w.unit)>h||xe(s.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,p,m]=It(i,l);if(BigInt(d.notional)>m)throw new Error("ledger: per-trade cap exceeded");if(xe(s.entries,"value",l)>f||xe(s.entries,"notional",l)>p)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function Mn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){je(t,e);let a=_(r);return at(e,()=>{let u=it(e,a,i,t,n),c=u.entries.find(s=>String(s.tradeId)===String(o??"")&&s.state==="reserved");if(!c||c.state!=="reserved")throw new Error("ledger: reservation unavailable");return c.state="committed",c.committedAtMs=i,Ue(e,u,a,t,n),structuredClone(c)})}function qn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){je(t,e);let a=_(r);return at(e,()=>{let u=it(e,a,i,t,n),c=u.entries.findIndex(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(c<0)throw new Error("ledger: reservation unavailable");let[s]=u.entries.splice(c,1);return Ue(e,u,a,t,n),structuredClone(s)})}function Dn({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){je(t,e);let a=_(r);return at(e,()=>{let u=it(e,a,i,t,n),c=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");if(Array.isArray(c.units))return c.state="committed",c.committedAtMs=i,c.units=c.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),c.settledAs=c.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",Ue(e,u,a,t,n),structuredClone(c);let s=BigInt(c.fee??0);return s<=0n?(c.state="committed",c.committedAtMs=i,c.value="0",c.notional="0",c.settledAs="no-fee",Ue(e,u,a,t,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=s.toString(),c.settledAs="fee-only",Ue(e,u,a,t,n),structuredClone(c))})}function Un(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:J(cs(r))};return se(e.mac,z(o,_(t)))}function ms(e){let r={...e?.fee||{}};return delete r.waiverAttestation,{...e,fee:r}}function jn(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:J(ms(r))};return se(e.mac,z(o,_(t)))}import{spawnSync as hs}from"node:child_process";function Wn(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=hs(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 fr}from"ethers";import{base58 as pr}from"@scure/base";import{ed25519 as Gn}from"@noble/curves/ed25519.js";import{NETWORK as Kn,TEST_NETWORK as Yn,WIF as ws,p2wpkh as Hn}from"@scure/btc-signer";import{pubECDSA as gs}from"@scure/btc-signer/utils.js";var Tt=e=>{let r=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(r)||r.length%2?null:Buffer.from(r,"hex")},ys=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},Jn=e=>{let r=String(e||"").trim();try{let t=Buffer.from(pr.decode(r));return pr.encode(t)===r?t:null}catch{return null}},mr=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(Gn.getPublicKey(r));if(!t.equals(n))throw new Error("sol: supplied public key does not match seed")}return r},zn=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),fe=(e,r)=>{if(r==="sol")return mr(e);if(!(e instanceof Uint8Array))throw new Error(`${r}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${r}: expected 32-byte private key material`)},Es=(e,r)=>{if(!Array.isArray(e))throw new Error(`${r}: expected byte array`);let t=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${r}: expected integer bytes in 0..255`);t[n]=o}return fe(t,r)};function hr(e,r){let t=String(r||"").trim();if(e==="evm")return new fr(t).privateKey;if(e==="btc")for(let i of[Kn,Yn])try{return Buffer.from(ws(i).decode(t))}catch{}if(e==="sol"){if(/^hex:/i.test(t)){let s=Tt(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=Jn(t.slice(7));if(!zn(s))throw new Error("sol: invalid explicit base58 private key");return mr(s)}if(/^0x/i.test(t)){let s=Tt(t);if(!s)throw new Error("sol: invalid explicit hex private key");return fe(s,"sol")}let i=Tt(t),a=i&&(i.length===32||i.length===64)?fe(i,"sol"):null,u=Jn(t),c=zn(u);if(a&&c&&!a.equals(c))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(c)return mr(u);if(i)return fe(i,"sol")}let n=Tt(t);if(n)return e==="evm"?new fr(`0x${n.toString("hex")}`).privateKey:fe(n,e);let o=ys(t);if(o)return fe(o,e);if(t.startsWith("[")||t.startsWith("{")){let i=JSON.parse(t);if(Array.isArray(i))return Es(i,e);let a=i.privateKey??i.secretKey??i.key;if(a)return hr(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function Vn(e,r){if(e==="evm"){let t=new fr(String(r));return{kind:e,secret:t.privateKey,addresses:[t.address.toLowerCase()]}}if(e==="btc"){let t=fe(r,"btc"),n=gs(t);return{kind:e,secret:t.toString("hex"),addresses:[Hn(n,Kn).address,Hn(n,Yn).address]}}if(e==="sol"){let t=fe(r,"sol");return{kind:e,secret:t.toString("hex"),addresses:[pr.encode(Gn.getPublicKey(t))]}}throw new Error(`unsupported signer kind ${e}`)}function Xn(e,r={}){let t=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(r.kind||"")!=="multichain")return{[r.kind||"evm"]:Vn(r.kind||"evm",hr(r.kind||"evm",t))};let n=JSON.parse(t),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Vn(i,hr(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function wr(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var ue=new br(["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 br(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),yr=new br(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function Ts(e){let r=process.env.ORACLE_SIGNER_STATE_DIR||re.join(process.env.XDG_STATE_HOME||re.join(bs.homedir(),".local","state"),"oracle"),t=xs("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 Ns(e){try{return _(e)}catch(t){if(t.code!=="ENOENT")throw t}let r=Ss(32).toString("hex");return be(e,r+`
8
- `),r}function Er(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 eo(e){return e.surfaces.some(r=>String(r).startsWith("evm"))}function W(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 to(e,r){return Object.entries(e||{}).find(([t])=>t.toLowerCase()===r)?.[1]}function Os(e,r){let t=e?.anvilQuote;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("signer: exact prepared Anvil quote is required");if(!e?.artifact?.anvilQuote||JSON.stringify(e.artifact.anvilQuote)!==JSON.stringify(t))throw new Error("signer: exact prepared Anvil quote artifact mismatch");return Object.freeze(r==="buy"?{totalCostRaw:BigInt(t.totalCostRaw).toString(),baseCostRaw:BigInt(t.baseCostRaw).toString(),feeRaw:BigInt(t.feeRaw).toString(),protocolFeeRaw:BigInt(t.protocolFeeRaw).toString(),available:t.available===!0}:{netPayoutRaw:BigInt(t.netPayoutRaw).toString(),grossPayoutRaw:BigInt(t.grossPayoutRaw).toString(),feeRaw:BigInt(t.feeRaw).toString(),protocolFeeRaw:BigInt(t.protocolFeeRaw).toString()})}function Ls(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 u=r==="buy"?"buySpecificNFT":"sellNFT",c;try{if(c=ue.decodeFunctionData(u,a[0].data),ue.encodeFunctionData(u,[c[0],c[1]]).toLowerCase()!==String(a[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${r} calldata required`)}if(BigInt(c[0])!==BigInt(e.tokenId)||BigInt(c[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 Cs(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"),u=ce(r.paymentToken,"Anvil payment token"),c=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 m=Os(r,p),g=Ls(r,p,m),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(to(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=to(t.nftPaymentTokenCaps,u);if(!b||Number(b.decimals)!==s)throw new Error("signer: Anvil payment token decimals are not reviewed by policy");let E=String(await e.send("eth_chainId",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(E)||BigInt(E)!==4663n)throw new Error("signer: trusted RPC Anvil chain mismatch");let A=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(A))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let I=BigInt(A),k=await e.send("eth_getBlockByNumber",[A,!1]),S=String(k?.hash||"").toLowerCase();if(String(k?.number||"").toLowerCase()!==A||!/^0x[0-9a-f]{64}$/.test(S))throw new Error("signer: trusted RPC returned an invalid Anvil block attestation");let P=Object.freeze({blockHash:S,requireCanonical:!0}),F=String(await e.send("eth_getCode",[i,P])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(F)||F==="0x")throw new Error("signer: Anvil market runtime is empty");let V=Is(F).toLowerCase();if(V!==h)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[me,Ct,Pt]=await Promise.all([pe(e,i,ue,"collection",P),pe(e,i,ue,"token",P),pe(e,i,ue,"robinhoodSwapFeeWei",P)]),he=ce(me,"live Anvil collection"),Ne=ce(Ct,"live Anvil payment token"),We=BigInt(Pt).toString();if(he!==a)throw new Error("signer: live Anvil collection mismatch");if(Ne!==u)throw new Error("signer: live Anvil payment token mismatch");if(We!==c.toString())throw new Error("signer: live Anvil native swap fee mismatch");let Se=Number(await pe(e,Ne,Zn,"decimals",P));if(!Number.isSafeInteger(Se)||Se!==s)throw new Error("signer: live Anvil payment token decimals mismatch");let He=ce(await pe(e,he,yr,"ownerOf",P,[f]),"live Anvil token owner"),Je=null,le=null,Ae=null,y=null,x;if(p==="buy"){let[T,C,H]=await Promise.all([pe(e,i,ue,"inventory",P,[f]),pe(e,Ne,Zn,"allowance",P,[d,i]),e.send("eth_call",[{to:i,data:ue.encodeFunctionData("quoteSpecificBuy",[f])},P])]);Je=!!T,le=BigInt(C).toString();let $=ue.decodeFunctionResult("quoteSpecificBuy",H);if(x=Object.freeze({totalCostRaw:BigInt($[0]).toString(),baseCostRaw:BigInt($[1]).toString(),feeRaw:BigInt($[2]).toString(),protocolFeeRaw:BigInt($[3]).toString(),available:!!$[4]}),JSON.stringify(x)!==JSON.stringify(m))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(le)!==BigInt(r.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(le)<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,C,H]=await Promise.all([pe(e,he,yr,"getApproved",P,[f]),pe(e,he,yr,"isApprovedForAll",P,[d,i]),e.send("eth_call",[{to:i,data:ue.encodeFunctionData("quoteSellNFT")},P])]);Ae=ce(T,"live Anvil token approval"),y=!!C;let $=ue.decodeFunctionResult("quoteSellNFT",H);if(x=Object.freeze({netPayoutRaw:BigInt($[0]).toString(),grossPayoutRaw:BigInt($[1]).toString(),feeRaw:BigInt($[2]).toString(),protocolFeeRaw:BigInt($[3]).toString()}),JSON.stringify(x)!==JSON.stringify(m))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(Ae!==i&&!y)throw new Error("signer: live Anvil NFT approval is insufficient");if(Ae!==ce(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:he,paymentToken:Ne,paymentTokenDecimals:Se,nativeSwapFeeWei:We,signerAddress:d,nftAction:p,tokenId:f.toString(),tokenOwner:He,inventoryMember:Je,allowanceRaw:le,approvedAddress:Ae,approvedForAll:y,quote:x,blockNumber:I.toString(),blockHash:S,runtimeCodeHash:V,verifiedAtMs:Number(n)})}function ro(e,r,t="execution"){if(!e||!r)throw new Error("signer: complete Anvil revalidation evidence required");for(let n of["runtimeCodeHash","market","collection","paymentToken","paymentTokenDecimals","nativeSwapFeeWei","signerAddress","nftAction","tokenId","tokenOwner","inventoryMember","allowanceRaw","approvedAddress","approvedForAll"])if(String(r[n]).toLowerCase()!==String(e[n]).toLowerCase())throw new Error(`signer: Anvil ${n} changed after simulation at ${t}`);if(JSON.stringify(r.quote)!==JSON.stringify(e.quote))throw new Error(`signer: Anvil quote changed after simulation at ${t}`);return!0}function Ps(e,r,t,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:a}={}){let u=vs(new URL("./anvil-attestation-worker.mjs",import.meta.url)),c={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},s;try{s=As(process.execPath,[u],{input:JSON.stringify({rpcUrl:e,chainId:r,envelope:t,policy:c,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 Bs(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"}`],u=(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`)}},c=String(i.data||"0x");if(ne(c))try{let s=Ke(c);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)=>u(s,d))),o?.surface==="btc"){let s=Mt(o,t);a.push(`amount=${s.value} sats fee=${s.fee} sats outputs=${s.outputs.join(",")}`)}if(o?.surface==="sol"){let s=Ht(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`
1
+ var So=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};import lr from"node:fs";import vo from"node:os";import Pe from"node:path";import{fileURLToPath as ko}from"node:url";function Nt(){return process.env.ORACLE_FAKE_HOME||vo.homedir()}function Io(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function dr(){return Io()?process.env.ORACLE_CONFIG_DIR||Pe.join(Nt(),".config","oracle"):Pe.join(Nt(),".config","oracle")}function Oo(){return Pe.join(dr(),"desk.json")}function No(){return Pe.join(dr(),"env")}function Be({force:e=!1}={}){if(Be._done&&!e)return Be._result||null;Be._done=!0;let t={},r=(o,i)=>{if(i==null)return;let a=String(i).trim();a&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=a,t[o]=a))};try{let o=No();if(lr.existsSync(o))for(let i of lr.readFileSync(o,"utf8").split(/\r?\n/)){let a=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let u=a[2];(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),r(a[1],u)}}catch{}try{let o=Oo();if(lr.existsSync(o)){let i=JSON.parse(lr.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),Be._result=Object.keys(t).length?t:null,Be._result}var To,bc,Ct=So(()=>{To=Pe.dirname(ko(import.meta.url)),bc=Pe.resolve(To,"../..");try{Be()}catch{}});Ct();import pc from"node:path";import po from"node:fs";import ne from"node:path";import qs from"node:os";import{createHash as Us,randomBytes as js}from"node:crypto";import{execFileSync as Ws}from"node:child_process";import{fileURLToPath as Hs}from"node:url";import{Interface as It,keccak256 as Js}from"ethers";import{Transaction as vt}from"@scure/btc-signer";import{ed25519 as zs}from"@noble/curves/ed25519.js";import as from"node:http";import{timingSafeEqual as ss}from"node:crypto";import{createHash as Ga,randomBytes as Va,timingSafeEqual as Ka}from"node:crypto";import{base58 as qn}from"@scure/base";import{Interface as En}from"ethers";import{Interface as Jo,MaxUint256 as zo,isAddress as Go,keccak256 as ou,toUtf8Bytes as iu}from"ethers";import{Interface as Wo,isAddress as Dc}from"ethers";import{isAddress as Pc}from"ethers";import{createHash as Ro,createHmac as _o,timingSafeEqual as $o}from"node:crypto";import{readFileSync as Co}from"node:fs";import{homedir as Lo}from"node:os";import{join as fr}from"node:path";function Bo(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let r=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return r?[r]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),t=Lo();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||fr(t,".config","oracle")).trim();return[e,fr(r,"exec.env")].filter(Boolean)}return[e,fr(t,".config","oracle","exec.env"),fr(t,".config","mad-desk","exec.env")].filter(Boolean)}function Xe(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of Bo())try{let i=Co(o,"utf8"),a=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}function Re(e,t,r="guard"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${r}: current time must be a finite number (got ${Po(t)})`);let n=t,o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${r} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function Po(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var Lt=100;function _r(e){return Array.isArray(e)?`[${e.map(_r).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${_r(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Fo(e,{required:t=!1}={}){try{return Xe(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Mo(e){let{signature:t,...r}=e;return r}function Do(e){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<10||t.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return Ro("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function qo(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:$o(r,n)}function Uo(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=t.length;i+=64)n.push(t.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(r){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function $r(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:i,requireSigned:a=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let u=Fo(o,{required:a});if(a&&!u)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(u){let m=_o("sha256",u).update(_r(Mo(e))).digest("hex");if(!qo(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>Lt)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(s)||s<0||s>Lt||c>s)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{Re({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},t,"auto-slippage quote")}catch(m){throw new Error(`${m.message}; re-quote before signing`)}if(r!=null&&Number(e.chainId)!==Number(r))throw new Error("auto-slippage guard chain mismatch");if(n&&String(e.venue).toLowerCase()!==String(n).toLowerCase())throw new Error("auto-slippage guard venue mismatch");let l=BigInt(e.quoteAmountOut??0),d=BigInt(e.minAmountOut??0);if(l<=0n||d<=0n)throw new Error("auto-slippage guard amounts must be positive");let f=l*BigInt(1e4-c),p=f/10000n;if(f%10000n!==0n&&(p+=1n),d<p)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let m=Uo(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==Do(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(m!=null&&m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is hash-bound but the calldata encodes ${m}, not the guard floor ${e.minAmountOut}`)}else{if(m==null){let 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(m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${m}`)}}return!0}var Wc=new Wo(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Ho,isAddress as zc}from"ethers";var Yc=new Ho(["function approve(address spender,uint256 amount) returns (bool)"]),Xc=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function R(e,t="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${t} must be a number or decimal string`);return e}throw new Error(`${t} must be a number or decimal string`)}function W(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function Z(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let r=R(e,t);if(r==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(r)}`)}}function V(e,t="amount"){let r=Z(e,t);if(r<=0n)throw new Error(`${t} must be positive`);return r}function P(e,t,r="amount"){let n=R(e,r);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${r} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[a="0",u=""]=i.split(".");if(u.length>t)throw new Error(`${r} has more than ${t} decimal places, which would lose precision`);let c=BigInt((a||"0")+u.padEnd(t,"0"));return o?-c:c}var du=new Jo(["function approve(address spender,uint256 amount) returns (bool)"]);function Bt(e,t){let r=String(e||"").trim();if(!Go(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Vo(e,t="approval amount",{allowZero:r=!1}={}){let n=Z(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=zo)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var Pt=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),Ko=new Set(["0x39509351","0xf9255c1f"]);function oe(e){let t=String(e||"").toLowerCase();return t.length<10?!1:Pt.has(t.slice(0,10))}function Qe(e){if(!oe(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=s=>n[s]?"0x"+n[s].slice(24):null,i=s=>n[s]?BigInt("0x"+n[s]):null,a=null,u=null,c=null;switch(r){case"0x095ea7b3":case"0x39509351":a=o(0),u=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),a=o(1),u=i(2);break;case"0xd505accf":a=o(1),u=i(2);break;case"0x8fcbaf0c":{a=o(1),u=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),a=o(1),u=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(a==null||u==null)throw new Error("invalid approve calldata");return{spender:Bt(a,"approval spender"),token:c==null?null:Bt(c,"approval token"),amount:Vo(u,"approval amount",{allowZero:!0}),selector:r,additive:Ko.has(r)}}import{createHash as Yo,createHmac as mu,timingSafeEqual as wu}from"node:crypto";var Xo=2,Fr=300*1e3,Rt=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function Qo(e){let t=e==null||e===""?Fr:Number(e);return!Number.isFinite(t)||t<0?Fr:Math.min(t,Rt)}function Mr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Mr).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Mr(e[r])}`).join(",")}}`}function Zo(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function ei(e){let t=Zo(e);return Yo("sha256").update(Mr(t)).digest("hex")}function _t(e,{maxAgeMs:t=Fr,nowMs:r=Date.now(),providers:n=null,kinds:o=null,label:i="operator"}={}){if(!e||typeof e!="object")throw new Error(`${i}: prepared envelope object required`);if(e.oraclePrepared!==!0)throw new Error(`${i}: prepared integrity envelope missing \u2014 use an @oracle-agent/oracle prepare result`);if(Number(e.prepareVersion)!==Xo)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let a=ei(e);if(String(e.prepareHash||"")!==a)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let u=Number(e.preparedAt),c=Number(e.expiresAt),s=Qo(t),l=r-u,d=c-u;if(!Number.isFinite(l)||!Number.isFinite(c)||!Number.isFinite(d)||l<0||d<=0||d>Rt||l>s||r>=c)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${l}, 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 Ze=e=>String(e||"").toLowerCase(),ri=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","authorizationList","slippageBps","expiresAtMs"]),ti=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function ie(e){try{return ti.has(BigInt(e))}catch{return!1}}var K=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},$t=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},_e=(e,t,r,n=String)=>{if(!Array.isArray(t)||t.length===0)throw new Error(`policy: ${r} allowlist is empty`);if(!t.map(n).includes(n(e)))throw new Error(`policy: ${r} not allowed`)};function pr(e,t,{nowMs:r=Date.now(),networkFees:n,requireNetworkFees:o=!1}={}){if(!e||!t)throw new Error("policy: artifact and policy required");if(Object.keys(e).some(p=>!ri.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,4].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");if(Number(e.type)===4){if(!Array.isArray(e.authorizationList)||e.authorizationList.length===0||e.authorizationList.length>8)throw new Error("policy: type-4 requires 1-8 authorizationList entries");for(let[p,m]of e.authorizationList.entries()){if(!m||typeof m!="object")throw new Error(`policy: authorizationList[${p}] required`);_e(m.address,t.destinations,"destination",Ze);try{if(BigInt(m.chainId)!==BigInt(e.chainId))throw new Error("policy: type-4 authorization chainId must match transaction")}catch(g){throw String(g?.message||"").includes("authorization chainId")?g:new Error("policy: type-4 authorization chainId must match transaction")}}if(String(e.data||"0x").toLowerCase()!=="0x")throw new Error("policy: type-4 calldata must be empty");if(K(e.value,"value")!==0n)throw new Error("policy: type-4 cannot transfer native value")}else if(e.authorizationList!=null)throw new Error("policy: authorizationList is only valid on type-4");let i=(p,m)=>{try{return BigInt(p)===BigInt(m)}catch{return String(p)===String(m)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(p=>i(p,e.chainId)))throw new Error("policy: chain not allowed");if(_e(e.to,t.destinations,"destination",Ze),_e(String(e.data||"0x").slice(0,10),t.selectors,"selector",p=>String(p).toLowerCase()),_e(e.from,t.owners,"owner",Ze),oe(e.data)){let p;try{p=Qe(e.data)}catch(g){throw new Error(`policy: malformed approval calldata: ${g?.message||g}`)}_e(p.spender,t.spenders,"spender",Ze),_e(p.token||e.to,t.erc20Tokens,"ERC-20 token",Ze);let m=K(t.maxApproval,"maxApproval");if(BigInt(p.amount)>m)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(K(e.value,"value")>K(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=K(e.gasLimit,"gasLimit");if(a>K(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let u=e.maxFeePerGas??e.gasPrice,c=K(u,"feePerGas")*a,s=0n;try{if(ie(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+=K(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(s+=K(e.operatorFeeWei,"operatorFeeWei")),ie(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=K(n.l1FeeWei,"estimated l1FeeWei")+K(n.operatorFeeWei,"estimated operatorFeeWei");if(s<p)throw new Error("policy: rollup fee attestation understates estimate")}if(c+s>K(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let d=$t(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>d)throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r)throw new Error("policy: artifact expired");let f=$t(t.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-r>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as Ft}from"node:crypto";import{Address as ni,NETWORK as oi,OutScript as Mt,RawTx as ii,SigHash as Dt,TEST_NETWORK as ai,Transaction as si}from"@scure/btc-signer";var qt=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},ci=(e,t)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${t}`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`envelope: invalid ${t}`);return r},ui=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,li=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),ke=e=>li(e)?String(e).toLowerCase():String(e),Dr=(e,t)=>Array.isArray(t)&&t.some(r=>ke(r)===ke(e)),di=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function fi(e){let t=Buffer.from(ii.encode(e)),r=Ft("sha256").update(t).digest();return Buffer.from(Ft("sha256").update(r).digest()).reverse().toString("hex")}function pi(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(fi(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))throw new Error("envelope: Bitcoin prevout txid mismatch");let t=e.nonWitnessUtxo.outputs?.[e.index];if(!t)throw new Error("envelope: Bitcoin prevout output missing");if(!e.witnessUtxo)throw new Error("envelope: PSBT input witness UTXO required");if(BigInt(e.witnessUtxo.amount)!==BigInt(t.amount)||!di(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function qr(e,t){if(e.action!=="transfer")throw new Error("envelope: BTC decoder requires transfer action");let r=e?.artifact;if(Object.keys(r).some(d=>!["network","psbt"].includes(d)))throw new Error("envelope: unexpected BTC artifact field");if(!Dr(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?oi:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?ai:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=si.fromPSBT(ci(r.psbt,"PSBT"))}catch(d){throw new Error(`envelope: invalid PSBT: ${d?.message||d}`)}if(o.inputsLength===0||o.outputsLength===0)throw new Error("envelope: PSBT inputs and outputs required");let i=ni(n);for(let d=0;d<o.inputsLength;d++){let f=o.getInput(d);for(let g of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(ui(f[g]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==Dt.DEFAULT&&f.sighashType!==Dt.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let p=pi(f),m;try{let g=Mt.decode(p.script);if(!["wpkh"].includes(g.type))throw new Error("unsupported input");m=i.encode(g)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!Dr(m,t.owners)||ke(m)!==ke(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...t.changeAddresses||[]].map(d=>ke(d))),u=0n,c=!1,s=[];for(let d=0;d<o.outputsLength;d++){let f=o.getOutput(d),p;try{p=i.encode(Mt.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=ke(p);if(s.push(`${p}:${f.amount}`),m===ke(e.destination)){c=!0,u+=f.amount;continue}if(Dr(p,t.destinations)){u+=f.amount;continue}if(!a.has(m))throw new Error("policy: Bitcoin output destination not allowed")}if(!c)throw new Error("envelope: Bitcoin destination mismatch");let l;try{l=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(l<0n||l>qt(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(u>qt(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:u.toString(),notional:(u+l).toString(),fee:l.toString(),outputs:Object.freeze(s)})}function Ur(e,t){let{unit:r,value:n,notional:o,fee:i}=qr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as Wr}from"node:crypto";import{base58 as zt}from"@scure/base";import{getCompiledTransactionMessageDecoder as mi}from"@solana/transaction-messages";var Hr="11111111111111111111111111111111",wi="ComputeBudget111111111111111111111111111111",hi="So11111111111111111111111111111111111111112",Gt="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var Vt="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",gi=5000n,yi=2039280n,Ei=37095705934669439343138083508754565189542113879843219016388785533085940283555n,D=57896044618658097711785492504343953926634992332820282019728792003956564819949n,Ut=19681161376707505956807079304988542015446066515923890162744021073123829784752n,jt=e=>Wr("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),bi=new Map([[jt("route"),{name:"route",prefixBytes:0}],[jt("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),X=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},xi=(e,t)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${t}`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`envelope: invalid ${t}`);return r},fe=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),ee=e=>String(e||""),Ai=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,wr=e=>Wr("sha256").update(e).digest("hex");function mr(e,t){try{let r=Buffer.from(zt.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function Y(e){let t=e%D;return t>=0n?t:D+t}function ae(e,t){let r=e;for(;t-- >0n;)r=r*r%D;return r}function Si(e){let r=e*e%D*e%D,n=ae(r,2n)*r%D,o=ae(n,1n)*e%D,i=ae(o,5n)*o%D,a=ae(i,10n)*i%D,u=ae(a,20n)*a%D,c=ae(u,40n)*u%D,s=ae(c,80n)*c%D,l=ae(s,80n)*c%D,d=ae(l,10n)*i%D;return ae(d,2n)*e%D}function vi(e,t){let r=Y(t*t*t),n=Y(r*r*t),o=Si(e*n),i=Y(e*r*o),a=Y(t*i*i),u=i,c=Y(i*Ut),s=a===e,l=a===Y(-e),d=a===Y(-e*Ut);return s&&(i=u),(l||d)&&(i=c),(Y(i)&1n)===1n&&(i=Y(-i)),!s&&!l?null:i}function ki(e){if(!e||e.length!==32)return!1;let t=0n;for(let o=31;o>=0;o--)t=(t<<8n)+BigInt(o===31?e[o]&127:e[o]);let r=Y(t*t),n=vi(Y(r-1n),Y(Ei*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function Ti(e,t){let r=Buffer.concat([...e,mr(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=Wr("sha256").update(r).digest();if(ki(n))throw new Error("envelope: derived Solana program address is on curve");return zt.encode(n)}function Jr(e,t,r=Gt){let n=[mr(e,"owner"),mr(r,"token program"),mr(t,"mint")];for(let o=255;o>=0;o--)try{return Ti([...n,Buffer.from([o])],Vt)}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,t){return(t.accountIndices||[]).map(r=>ee(e.staticAccounts[r]))}function er(e){return Buffer.from(e.data||[])}function Oi(e,t){return ee(e.staticAccounts[t.programAddressIndex])}function Kt(e,t){return Number(t)<e.header.numSignerAccounts}function Ni(e,t){let r=e.header.numSignerAccounts,n=e.header.numReadonlySignerAccounts,o=e.header.numReadonlyNonSignerAccounts,i=e.staticAccounts.length;return Number(t)<r?Number(t)<r-n:Number(t)<i-o}function rr(e){return e.accountIndices||[]}function jr(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function Wt(e,t){let r=rr(t).map(n=>{let o=Kt(e,n)?"s":"n",i=Ni(e,n)?"w":"r";return`${n}:${ee(e.staticAccounts[n])}:${o}:${i}`});return wr(Buffer.from(r.join(`
2
+ `)))}function Ht(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function Ci(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function Li(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function Bi(e,t,r){let n=r.maxJupiterRoutePlanSteps===void 0?1:Number(r.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(t<1||t>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(r.jupiterRouteVariants)?r.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=r.jupiterRouteVariantPayloadBytes||{},a=0,u=0,c=[];for(let s=0;s<t;s++){if(a>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let l=e[a++];if(!o.includes(l))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(l)))throw new Error("policy: Jupiter route variant payload size required");let d=Number(i[String(l)]);if(!Number.isSafeInteger(d)||d<0||d>16)throw new Error("policy: Jupiter route variant payload size invalid");if(a+d+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e.subarray(a,a+d);a+=d;let p=f.toString("hex"),m=r.jupiterRouteVariantPayloads?.[String(l)];if(!Array.isArray(m)||!m.map(String).includes(p))throw new Error("policy: Jupiter route variant payload not allowed");let g=e[a++],h=e[a++],w=e[a++];if(g<1||g>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(h!==s||w!==s+1)throw new Error("envelope: unsupported Jupiter route-plan token index");u+=g,c.push(Object.freeze({swapVariant:l,variantPayloadHex:p,percent:g,inputIndex:h,outputIndex:w}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(u!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function Pi(e,t){let r=er({data:e}),n=r.subarray(0,8).toString("hex"),o=bi.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,a=o.prefixBytes===1?r[8]:null;if(o.prefixBytes===1&&r.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let u=8+o.prefixBytes,c=u+4,s=r.length-i;if(s<=c)throw new Error("envelope: malformed Jupiter route payload");let l=Li(r,u,"route plan length"),d=r.subarray(c,s),f=Bi(d,l,t);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:l,routePlan:f,routePlanHash:wr(d),inAmount:Ht(r,s,"in_amount"),quotedOutAmount:Ht(r,s+8,"quoted_out_amount"),slippageBps:Ci(r,s+16,"slippage_bps"),platformFeeBps:r[s+18],instructionHash:wr(r)})}function Ri(e,t,r){let n=Ii(e,t),o=(i,a)=>{let u=n[i];if(!u)throw new Error(`envelope: Jupiter ${a} account missing`);return u};if(r.instruction==="route"){if(n.length<9)throw new Error("envelope: Jupiter route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),userTransferAuthority:o(1,"userTransferAuthority"),userSourceTokenAccount:o(2,"userSourceTokenAccount"),userDestinationTokenAccount:o(3,"userDestinationTokenAccount"),destinationTokenAccount:o(4,"destinationTokenAccount"),destinationMint:o(5,"destinationMint"),platformFeeAccount:o(6,"platformFeeAccount"),eventAuthority:o(7,"eventAuthority"),program:o(8,"program")}}if(r.instruction==="shared_accounts_route"){if(n.length<13)throw new Error("envelope: Jupiter shared route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),programAuthority:o(1,"programAuthority"),userTransferAuthority:o(2,"userTransferAuthority"),userSourceTokenAccount:o(3,"sourceTokenAccount"),programSourceTokenAccount:o(4,"programSourceTokenAccount"),programDestinationTokenAccount:o(5,"programDestinationTokenAccount"),userDestinationTokenAccount:o(6,"destinationTokenAccount"),sourceMint:o(7,"sourceMint"),destinationMint:o(8,"destinationMint"),platformFeeAccount:o(9,"platformFeeAccount"),token2022Program:o(10,"token2022Program"),eventAuthority:o(11,"eventAuthority"),program:o(12,"program")}}throw new Error("envelope: unsupported Jupiter account layout")}function Jt(e,t){return e&&e!==t?e:null}function Q(e,t,r){let n=ee(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function _i(e,t){let r=er(e);if(r.length===5&&r[0]===2){let n=r.readUInt32LE(1),o=t.maxComputeUnits===void 0?14e5:Number(t.maxComputeUnits);if(!Number.isSafeInteger(o)||o<=0)throw new Error("policy: maxComputeUnits must be positive");if(n>o)throw new Error("policy: Jupiter compute unit limit exceeds cap");return 0n}throw r.length===9&&r[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function $i(e,t,r,n,o,i){let a=er(t);if(a.length!==1||a[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let u=rr(t);if(u.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=Q(e,u[0],"ATA payer"),s=Q(e,u[1],"ATA account"),l=Q(e,u[2],"ATA owner"),d=Q(e,u[3],"ATA mint"),f=Q(e,u[4],"ATA system program"),p=Q(e,u[5],"ATA token program");if(c!==r.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(l!==r.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(f!==Hr)throw new Error("envelope: Jupiter ATA system program mismatch");if(p!==o)throw new Error("envelope: Jupiter ATA token program mismatch");if(d!==n.inputMint&&d!==n.outputMint)throw new Error("envelope: Jupiter ATA mint mismatch");if(s!==Jr(r.owner,d,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:s,debit:i}}function Fi(e,t,r,n,o){let i=rr(t),a=er(t);if(i.length!==2||a.length!==12||a.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let u=Q(e,i[0],"wrap payer"),c=Q(e,i[1],"wrap target"),s=a.readBigUInt64LE(4);if(u!==r.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(s!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return s}function Mi(e,t,r,n){let o=rr(t),i=er(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||Q(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=Q(e,o[0],"closeAccount source"),u=Q(e,o[1],"closeAccount destination"),c=Q(e,o[2],"closeAccount authority");if(a!==n||u!==r.owner||c!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function Di(e,t,r,n,o,i,a){let u=Jr(t.owner,t.artifact.inputMint,a);if(o.userSourceTokenAccount!==u)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=X(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<yi)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let s=new Map,l=0n,d=!1,f=!1;for(let p of e.instructions){if(p===n)continue;let m=Oi(e,p);if(m===wi)_i(p,r);else if(m===Vt){let{ata:g,debit:h}=$i(e,p,t,t.artifact,a,c);s.set(g,h)}else if(m===Hr)l+=Fi(e,p,t,u,i);else if(m===a){let g=Mi(e,p,t,u);g.kind==="syncNative"&&(d=!0),g.kind==="closeAccount"&&(f=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(l>0n&&(!d||!f))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(l!==0n&&l!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...s.values()].reduce((p,m)=>p+m,0n)}function qi(e){let t;try{t=mi().decode(xi(e.messageBase64,"Solana message"))}catch(r){throw new Error(`envelope: invalid Solana message: ${r?.message||r}`)}if(t.version!=="legacy"&&Array.isArray(t.addressTableLookups)&&t.addressTableLookups.length)throw new Error("envelope: unresolved Solana address tables refused");return t}function Ui(e,t,r){if(e.header.numSignerAccounts!==1||ee(e.staticAccounts[0])!==t.owner||!fe(t.owner,r.owners))throw new Error("envelope: Solana owner mismatch");if(!Array.isArray(e.instructions)||e.instructions.length===0)throw new Error("envelope: Solana instructions required");let n=[];for(let o of e.instructions){let i=ee(e.staticAccounts[o.programAddressIndex]);if(!i||!fe(i,r.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function ji(e,t,r){let n=X(r.lamportsPerSignature,"lamportsPerSignature");if(n<gi)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:X(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),a=i*n,u=i*o;if(t.exactFeeLamports!==void 0){let s=X(t.exactFeeLamports,"exactFeeLamports");if(s<a)throw new Error("policy: Solana exact fee below the base signature fee");if(s>u)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=u;if(c>X(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function Wi(e,t,r,n){let o=0n,i=!1;for(let a of e.instructions){if(ee(e.staticAccounts[a.programAddressIndex])!==Hr)throw new Error("envelope: unsupported Solana program decoder");let c=a.accountIndices||[];if(c.length!==2||ee(e.staticAccounts[c[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let s=ee(e.staticAccounts[c[1]]);if(s!==t.destination||!fe(s,r.destinations))throw new Error("envelope: Solana destination mismatch");let l=Buffer.from(a.data||[]);if(l.length!==12||l.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=l.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>X(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function Hi(e,t,r,n){let o=t.artifact;if(o.provider!=="jupiter")throw new Error("envelope: Solana swap provider must be jupiter");if(o.inputMint!==hi)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!fe(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Ai(r);if(!fe(o.inputMint,i)||!fe(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=X(o.inAmount,"inAmount"),u=X(o.outAmount,"outAmount"),c=X(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>X(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>X(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(u<=0n||c<=0n||c>u)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let s=ee(o.jupiterProgram);if(!s||!fe(s,r.programs)||!n.includes(s))throw new Error("policy: Jupiter program not allowed or absent");let l=e.instructions.filter(A=>ee(e.staticAccounts[A.programAddressIndex])===s);if(l.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let d=l[0],f=Pi(d.data,r);if(f.instruction==="shared_accounts_route"){let A=Array.isArray(r.jupiterSharedRouteIds)?r.jupiterSharedRouteIds.map(Number):[];if(!A.length)throw new Error("policy: Jupiter shared route id allowlist required");if(!A.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(!jr(r.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!==u)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(c!==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 m=Ri(e,d,f),g=rr(d),h=f.instruction==="shared_accounts_route"?2:1;if(!Kt(e,g[h]))throw new Error("envelope: Jupiter transfer authority must be signer");if(m.program!==s)throw new Error("envelope: Jupiter program account mismatch");if(m.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(m.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(m.sourceMint!==void 0&&m.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let w=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[Gt];if(!fe(m.tokenProgram,w))throw new Error("policy: Solana token program not allowed");let b=Jr(t.owner,o.outputMint,m.tokenProgram);if(m.userDestinationTokenAccount!==b)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=Jt(m.destinationTokenAccount,s);if(E&&E!==b)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(Jt(m.platformFeeAccount,s))throw new Error("policy: Jupiter platform fee account not allowed");if(!jr(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(Wt(e,d)))throw new Error("policy: Jupiter route account hash not allowed");let S=wr(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,Wt(e,d)].join(`
3
+ `)));if(!jr(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(S))throw new Error("policy: Jupiter route review hash not allowed");let k=Di(e,t,r,d,m,a,m.tokenProgram),T=a+k;if(T>X(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:T,programs:n}}function zr(e,t){if(e.action!=="transfer"&&e.action!=="swap")throw new Error("envelope: Solana decoder requires transfer or swap action");let r=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(r||{}).some(c=>!n.includes(c)))throw new Error("envelope: unexpected Solana artifact field");if(!fe(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=qi(r),i=Ui(o,e,t),a=e.action==="transfer"?Wi(o,e,t,i):Hi(o,e,t,i),u=ji(o,r,t);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+u).toString(),fee:u.toString(),programs:Object.freeze(a.programs)})}function Gr(e,t){let{unit:r,value:n,notional:o,fee:i}=zr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}var Bu=64*1024;var zi=1e8;function Vr(e){if(typeof e!="string"||!/^#(?:0|[1-9]\d*)$/.test(e))return null;let t=Number(e.slice(1));if(!Number.isSafeInteger(t)||t<0)return null;let r=t%10;if(r!==0&&r!==1)return null;let n=Math.floor(t/10),o=zi+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var Gi=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),Vi=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"}),Yi=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"}),ge=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function Xi(e,t){let r=e.toString().padStart(t+1,"0");if(t===0)return r;let n=r.slice(0,-t),o=r.slice(-t).replace(/0+$/,"");return o?`${n}.${o}`:n}function Yt(e,t){let r=R(e,`hl: ${t}`);if(!/^\d+(?:\.\d+)?$/.test(r))throw new Error(`hl: ${t} must be a positive decimal`);let[n,o=""]=r.split("."),i=BigInt(n+o);if(i<=0n)throw new Error(`hl: ${t} must be positive`);return{raw:i,decimals:o.length}}function se(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`hl: ${t} must be finite JSON`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(n=>se(n,t)).join(",")}]`;if(!e||typeof e!="object")throw new Error(`hl: ${t} must be structured JSON`);return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${se(e[n],t)}`).join(",")}}`}function Qi(e){if(typeof e.orderType!="string"||!e.orderType)throw new Error("hl: order type must be a string");let t=e.orderType,r=e.orderWire;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: declared order wire required");if(t==="limit"){let i=r.limit?.tif;if(!["Gtc","Ioc","Alo"].includes(i)||se(r,"declared order type")!==se({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(se(r,"declared order type")!==se({limit:{tif:"Ioc"}},"expected order type"))throw new Error("hl: market order type must match its IOC wire shape");return}let n={stopMarket:{isMarket:!0,tpsl:"sl"},stopLimit:{isMarket:!1,tpsl:"sl"},takeProfitMarket:{isMarket:!0,tpsl:"tp"},takeProfitLimit:{isMarket:!1,tpsl:"tp"}}[t];if(!n)throw new Error("hl: unsupported declared order type");let o=r.trigger?.triggerPx;if(o==null||se(r,"declared order type")!==se({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 Zi(e,t,r){let n=Yt(e.s,"signed size"),o=Yt(e.p,"signed price"),i=n.decimals+o.decimals,a=n.raw*o.raw,u=P(t.notionalUsd,i,"hl: notionalUsd");if(u<=0n||a!==u)throw new Error("hl: signed notional must match");let c=P(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(a>c)throw new Error("hl: notional exceeds cap")}function ea(e,t){let r=e.action.builder;if(r==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: signed order builder must be structured");let n=ge(r.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(t.hlBuilders)?t.hlBuilders.map(u=>String(u).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=Z(r.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let a=P(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>a)throw new Error("hl: order builder fee exceeds cap")}function Xt(e,t,r){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(t.side==="buy"))throw new Error("hl: signed side must match exactly");if(R(e.s,"hl: signed size")!==R(t.size,"hl: size"))throw new Error("hl: signed size must match");if(R(e.p,"hl: signed price")!==R(t.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof t.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==t.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(se(e.t,"signed order type")!==se(t.orderWire,"declared order type"))throw new Error("hl: signed order type must match declared order type");let n=Object.prototype.hasOwnProperty.call(e,"c");if(t.clientOrderId==null){if(n)throw new Error("hl: undeclared signed client order id")}else if(!n||typeof e.c!="string"||e.c!==t.clientOrderId)throw new Error("hl: signed client order id must match")}function Qt(e,t,r,n,o){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(t.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(R(e.s,"hl: bracket protection size")!==R(t.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 ra(e){let t=String(e||"").replace(/\/$/,"");if(!Gi.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function Kr(e){return Vr(e)!=null}function ta(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(Kr(r)){if(t.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(n.includes(r)||n.includes("#*")||n.includes("*")||n.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(n.length&&!n.includes(r)&&!n.includes("*"))throw new Error("hl: coin not allowed");return!0}function na(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(a=>{if(typeof a=="string"){let[u,c]=String(a).split(":");return u===e&&Number(c)===t}return String(a?.coin)===e&&Number(a?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(Kr(e)){let i=Array.isArray(r.coins)?r.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0)return!0;throw new Error("hl: restricted coin policy requires hlMarkets pairs")}let o=Array.isArray(r.coins)?r.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function ye(e,t){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: structured artifact required");let n=ge(r.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=ra(r.submitTo);if(Object.prototype.hasOwnProperty.call(r,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let a=Number(r.nonce);if(!Number.isSafeInteger(a)||a<=0)throw new Error("hl: nonce must be a positive integer");if(!r.action||typeof r.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(r.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(r.action.type!==Yi[n])throw new Error("hl: action type must match kind");let u=r.notionalUsd??0;if(Vi.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let c=ge(r.coin,"coin",64),s=r.assetId??r.assetIndex;if(!Number.isSafeInteger(s)||s<0)throw new Error("hl: assetId required");if(n==="hip4-order"||s>=1e8){let l=Vr(c);if(!l||l.coin!==c)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(l.assetId!==s)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(ta(c,t),na(c,s,t),n==="hip4-order"&&!Kr(c))throw new Error("hl: HIP-4 orders must use an outcome coin");if(n==="perp-order"||n==="hip3-order"||n==="hip4-order"||n==="perp-bracket"){if(r.side!=="buy"&&r.side!=="sell")throw new Error("hl: side must be buy or sell");if(r.action.type!=="order"||!Array.isArray(r.action.orders))throw new Error("hl: signed orders are required");Qi(r);let l=r.action.orders;if(n==="perp-bracket"){let d=r.takeProfitPx,f=r.stopLossPx,p=1+(d==null?0:1)+(f==null?0:1);if(p<2||l.length!==p||r.grouping!=="normalTpsl"||r.action.grouping!==r.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");Xt(l[0],r,s);let m=1;d!=null&&Qt(l[m++],r,s,d,"tp"),f!=null&&Qt(l[m],r,s,f,"sl")}else{if(l.length!==1)throw new Error("hl: exactly one signed order is required");if(r.grouping!=="na"||r.action.grouping!==r.grouping)throw new Error("hl: signed grouping must match declared grouping");Xt(l[0],r,s)}Zi(l[0],r,t),ea(r,t),u=R(r.notionalUsd,"hl: notionalUsd")}if(n==="perp-leverage"){let l=r.leverage;if(!Number.isSafeInteger(l)||l<1)throw new Error("hl: leverage must be a positive integer");let d=t.maxLeverage==null?50:t.maxLeverage;if(typeof d!="number"||!Number.isSafeInteger(d)||d<1)throw new Error("hl: maxLeverage must be a positive integer");if(l>d)throw new Error("hl: leverage exceeds cap")}if(n==="perp-cancel"){let l=r.action.cancels;if(!Array.isArray(l)||l.length!==1)throw new Error("hl: exactly one cancel is required");if(!Number.isSafeInteger(l[0].a)||l[0].a!==s)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(r.orderId)||r.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(l[0].o)||l[0].o!==r.orderId)throw new Error("hl: signed cancel order id must match")}if(n==="perp-leverage"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==s)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(r.action.leverage)||r.action.leverage!==r.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(r.marginMode))throw new Error("hl: declared margin mode required");let l=r.marginMode==="cross";if(typeof r.action.isCross!="boolean"||r.action.isCross!==l)throw new Error("hl: signed isCross must match declared margin mode")}if(n==="perp-isolated-margin"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==s)throw new Error("hl: signed margin asset must match assetId");let l=ge(r.usd,"margin usd",64),d=P(l,6,"hl: margin usd");if(Z(r.action.ntli,"hl: signed margin ntli")!==d)throw new Error("hl: signed margin amount must match usd");if(typeof r.isBuy!="boolean"||r.action.isBuy!==r.isBuy)throw new Error("hl: signed margin isBuy must match");let p=P(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),m=d<0n?-d:d;if(m>p)throw new Error("hl: margin notional exceeds cap");u=Xi(m,6)}}if(n==="builder-fee-approval"){let c=ge(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(ge(r.action.builder,"signed builder",42).toLowerCase()!==c)throw new Error("hl: signed builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(m=>String(m).toLowerCase()):[]).includes(c))throw new Error("hl: builder not allowed");let l=ge(r.maxFeeRate,"maxFeeRate",32);if(ge(r.action.maxFeeRate,"signed maxFeeRate",32)!==l)throw new Error("hl: signed builder fee must match");if(!/^\d+(?:\.\d+)?%$/.test(l))throw new Error("hl: builder fee rate must be a percent");let d=P(l.slice(0,-1),12,"hl: builder fee percent"),f=P(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(f<0n||d*100n>f)throw new Error("hl: builder fee exceeds cap");if(Number(r.action.nonce)!==a)throw new Error("hl: signed builder nonce must match");let p=i.includes("testnet")?"Testnet":"Mainnet";if(r.hyperliquidChain!==p||r.action.hyperliquidChain!==r.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(r.signatureChainId!=="0x66eee"||r.action.signatureChainId!==r.signatureChainId)throw new Error("hl: signed signature chain id must match")}if(n.startsWith("hype-stake")||n==="hype-delegate"||n==="hype-undelegate"){if(n==="hype-delegate"||n==="hype-undelegate"){let c=n==="hype-undelegate";if(typeof r.action.isUndelegate!="boolean"||r.action.isUndelegate!==c)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(t.maxHypeWei!=null&&BigInt(String(r.action.wei??r.caps?.amountHype??"0"))>BigInt(t.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(u??r.action.wei??0),notional:String(u??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??u??0),coin:r.coin||null,submitTo:i})}import{createHmac as oa}from"node:crypto";var $e="0x"+"00".repeat(32);function Yr(e={}){let t=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,r=e.polyApiSecret||process.env.POLYMARKET_API_SECRET||process.env.POLY_API_SECRET,n=e.polyPassphrase||process.env.POLYMARKET_API_PASSPHRASE||process.env.POLY_API_PASSPHRASE;if(!t||!r||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(t),secret:String(r),passphrase:String(n)}}function Zt({creds:e,address:t,method:r,path:n,body:o="",nowSec:i}={}){if(!e?.key||!e?.secret||!e?.passphrase)throw new Error("poly: L2 credentials required");if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("poly: L2 address required");let a=String(i??Math.floor(Date.now()/1e3)),u=String(r||"").toUpperCase(),c=String(n||"");if(u!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let s=a+u+c+String(o||""),l=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),d=Buffer.from(l,"base64"),f=oa("sha256",d).update(s).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:f,POLY_TIMESTAMP:a,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function ia(e,t){if(e.side!==0&&e.side!==1)throw new Error("poly: side must be BUY or SELL");let r=e.side===0?"BUY":"SELL";if(t&&t!==r)throw new Error("poly: side mismatch");return r}function aa(e){let t=typeof e=="bigint"?e:V(e,"poly: atomicUsdc");if(t<=0n)throw new Error("poly: order amounts must be positive integer micro-units");let r=t/1000000n,n=(t%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return n?`${r.toString()}.${n}`:r.toString()}function en(e,t){let r=V(e.makerAmount,"poly: makerAmount"),n=V(e.takerAmount,"poly: takerAmount");return aa(t==="BUY"?r:n)}function sa(e){let t=typeof e=="bigint"?e.toString(10):R(e,"poly: salt");if(!/^[1-9][0-9]*$/.test(t))throw new Error("poly: salt must be a positive integer");let r=BigInt(t);if(r>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("poly: salt exceeds safe integer");return Number(r)}function rn({message:e,side:t,signature:r,orderType:n="GTC",apiKey:o}={}){if(!e||typeof e!="object")throw new Error("poly: CLOB v2 message required");if(!String(r||"").startsWith("0x"))throw new Error("poly: EIP-712 signature required");if(n!=="GTC")throw new Error("poly: only GTC is public");if(!o)throw new Error("poly: CLOB owner must be the L2 API key");let i=ia(e,t);if(W(e.metadata||$e,"poly: metadata").toLowerCase()!==$e)throw new Error("poly: metadata must be zero");if(W(e.builder||$e,"poly: builder").toLowerCase()!==$e)throw new Error("poly: builder must be zero");let a=sa(e.salt);return{deferExec:!1,order:{builder:$e,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:$e,salt:String(a),side:i,signature:r,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var ca=new Set(["https://clob.polymarket.com/order"]),tr=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Vu=Object.freeze(tr.map(e=>e[0])),ua=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),la="0xe111180000d2663c0091e4f400237545b87b996b",da="0xe2222d279d744050d28e00520010520000310f59",tn=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function nn(e){let t=String(e||"").replace(/\/$/,"");if(!ca.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function on(e){let t=W(e,"poly: exchange").toLowerCase();if(!ua.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function Ee(e,t){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("poly: structured artifact required");let n=tn(r.kind,"kind",48);if(n!=="poly-order")throw new Error("poly: unsupported Polymarket kind");if(e.action!=="order")throw new Error("poly: surface/action/kind mismatch");if(W(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(nn(r.submitTo),r.chainId!==137)throw new Error("poly: chainId must be Polygon 137");let o=r.domain;if(!o||typeof o!="object")throw new Error("poly: EIP-712 domain required");if(o.name!=="Polymarket CTF Exchange"||o.version!=="2"||o.chainId!==137)throw new Error("poly: EIP-712 domain must be official CTF Exchange v2 on Polygon");if(on(o.verifyingContract),on(r.exchange),W(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==W(r.exchange,"poly: exchange").toLowerCase())throw new Error("poly: exchange/domain mismatch");if(typeof r.negRisk!="boolean")throw new Error("poly: negRisk must be a boolean");let i=r.negRisk?da:la;if(W(r.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let a=r.message||r.value;if(!a||typeof a!="object")throw new Error("poly: signed order message required");let u=r.types?.Order;if(!Array.isArray(u)||u.length!==tr.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let A=0;A<tr.length;A+=1)if(u[A]?.name!==tr[A][0]||u[A]?.type!==tr[A][1])throw new Error("poly: EIP-712 Order type must be official CLOB v2");if((r.orderType||"GTC")!=="GTC")throw new Error("poly: only GTC is public");let c=String(e.owner||"").toLowerCase();if(W(a.maker,"poly: maker").toLowerCase()!==c)throw new Error("poly: maker must equal owner");if(W(a.signer,"poly: signer").toLowerCase()!==c)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=tn(r.tokenId,"tokenId",80);if(W(a.tokenId,"poly: tokenId")!==s)throw new Error("poly: tokenId mismatch");let l=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(l.length&&!l.includes(s)&&!l.includes("*"))throw new Error("poly: tokenId not allowed");let d=Number(a.side)===0?"BUY":"SELL";if(r.side&&r.side!==d)throw new Error("poly: side mismatch");let f=V(a.makerAmount,"poly: makerAmount"),p=V(a.takerAmount,"poly: takerAmount"),m=V(r.makerAmount,"poly: prepared makerAmount"),g=V(r.takerAmount,"poly: prepared takerAmount");if(f!==m)throw new Error("poly: signed makerAmount differs from prepared envelope");if(p!==g)throw new Error("poly: signed takerAmount differs from prepared envelope");let h=d==="BUY"?f:p,w=d==="BUY"?p:f,b=P(r.quantity,6,"poly: quantity");if(b<=0n||b!==w)throw new Error("poly: quantity must match CLOB v2 amounts");let E=P(r.price,6,"poly: price");if(E<=0n||E>=1000000n)throw new Error("poly: price must be within (0,1)");if(w*E!==h*1000000n)throw new Error("poly: price must match CLOB v2 amounts");if(P(r.notionalUsdc,6,"poly: notionalUsdc")!==h)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let k=en(a,d);if(P(k,6,"poly: displayed notionalUsdc")!==h)throw new Error("poly: displayed notionalUsdc must match CLOB v2 amounts");let T=t.maxNotionalUsd??t.maxNotionalUsdc;if(T!=null){let A=P(T,6,"poly: maxNotionalUsd");if(h>A)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:h.toString(),notional:h.toString(),fee:"0",kind:n,tokenId:s,side:d,makerAmount:f.toString(),takerAmount:p.toString(),price:String(r.price),quantity:String(r.quantity),notionalUsdc:k,submitTo:nn(r.submitTo)})}var fa=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),Xr=14,an=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function Fe(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function Qr(e){let t=String(e||"").replace(/\/$/,"");if(!fa.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function be(e,t={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("lighter: structured artifact required");let n=an(r.kind,"kind",48);if(n!=="lighter-order")throw new Error("lighter: unsupported Lighter kind");if(e.action!=="order")throw new Error("lighter: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="lighter")throw new Error("lighter: destination must be lighter");let o=Qr(r.submitTo),i=r.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=Number(Z(r.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: accountIndex required");let u=Number(Z(r.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(u)||u<0)throw new Error("lighter: clientOrderIndex required");Fe(r.orderType,0,"orderType"),Fe(r.timeInForce,1,"timeInForce"),Fe(r.reduceOnly,0,"reduceOnly"),Fe(r.triggerPrice,0,"triggerPrice"),Fe(r.orderExpiry,-1,"orderExpiry");let c=an(r.symbol||r.coin,"symbol",32),s=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(s.length&&!s.includes(c)&&!s.includes(String(i))&&!s.includes("*"))throw new Error("lighter: market not allowed");if(r.side!=="buy"&&r.side!=="sell")throw new Error("lighter: side must be buy or sell");let l=V(r.baseAmount,"lighter: baseAmount"),d=V(r.price,"lighter: price");if(l>BigInt(Number.MAX_SAFE_INTEGER)||d>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("lighter: baseAmount and price must be safe integers");let f=Number(l),p=Number(d),m=Number(r.sizeDecimals??0),g=Number(r.priceDecimals??0);if(!Number.isInteger(m)||m<0||m>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(g)||g<0||g>12)throw new Error("lighter: priceDecimals required");let h=m+g,w=l*d,b=P(r.notionalUsd,h,"lighter: notionalUsd");if(b<=0n)throw new Error("lighter: notionalUsd required");if(w!==b)throw new Error("lighter: notionalUsd must match size and price");let E=P(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,h,"lighter: maxNotionalUsd");if(w>E)throw new Error("lighter: notional exceeds cap");let S=R(r.notionalUsd,"lighter: notionalUsd");return Fe(r.txType,Xr,"txType"),Object.freeze({unit:"usd",value:String(S),notional:String(S),fee:"0",kind:n,symbol:c,marketIndex:i,side:r.side,baseAmount:f,price:p,submitTo:o,actionType:"create-order",amount:String(S)})}import{TypedDataEncoder as un,getAddress as re}from"ethers";import{TypedDataEncoder as Zu,getAddress as el,isAddress as rl}from"ethers";var sn=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),Zr=Object.freeze({Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"receiver",type:"address"},{name:"makerAsset",type:"address"},{name:"takerAsset",type:"address"},{name:"makingAmount",type:"uint256"},{name:"takingAmount",type:"uint256"},{name:"makerTraits",type:"uint256"}]});import{TypedDataEncoder as fl,getAddress as pl,isAddress as ml}from"ethers";var ol=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});var cn=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),xl=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var et=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),Al=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});var ma=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"]),wa="0x0000000000000000000000000000000000000000";function rt(e,t,r=256){if(typeof e!="string"||!e||e.length>r)throw new Error(`evm-order: bounded ${t} required`);return e}function ln(e,t){let r=String(e||"").replace(/\/$/,"");if(!ma.some(o=>r===`${o}/v4.0/${t}`||r===`${o}/v4.1/${t}`))throw new Error("evm-order: submitTo must be the official 1inch orderbook");return r}function dn(e,t){let r={1:"https://api.cow.fi/mainnet/api/v1/orders",100:"https://api.cow.fi/xdai/api/v1/orders",42161:"https://api.cow.fi/arbitrum_one/api/v1/orders",8453:"https://api.cow.fi/base/api/v1/orders"}[Number(t)],n=String(e||"").replace(/\/$/,"");if(!r||n!==r)throw new Error("evm-order: cow submitTo must be official api.cow.fi");return n}function fn(e,t){let r=e?.Order,n=t.Order;return!Array.isArray(r)||r.length!==n.length?!1:r.every((o,i)=>o?.name===n[i].name&&o?.type===n[i].type)}function pn(e,...t){let r=Array.isArray(e.tokens)?e.tokens.map(n=>String(n).toLowerCase()):[];if(!r.length)throw new Error("evm-order: tokens allowlist is empty");if(!r.includes("*")){for(let n of t)if(!r.includes(String(n).toLowerCase()))throw new Error("evm-order: token not allowed")}}function mn(e,t,{allowZero:r=!1}={}){let n=String(t||"").toLowerCase();if(!n)throw new Error("evm-order: receiver required");if(n===wa){if(!r)throw new Error("evm-order: receiver must equal owner");return}if(n!==e)throw new Error("evm-order: receiver must equal owner")}function Te(e,t){if(e?.surface!=="evm-order")throw new Error("evm-order: surface evm-order required");if(e.action!=="order")throw new Error("evm-order: action must be order");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("evm-order: structured artifact required");let n=rt(r.kind,"kind",32);if(n==="option")throw new Error("evm-order: option kind refused until official Derive/Lyra domain is pinned");if(n==="cow"){let d=Number(r.chainId??e.chainId);if(dn(r.submitTo,d),rt(e.destination,"destination",32)!=="cowswap")throw new Error("evm-order: cow destination must be cowswap");let f=cn[d];if(!f)throw new Error(`evm-order: unsupported cow chainId ${d}`);let p=r.domain||r.typedData?.domain,m=r.types||r.typedData?.types,g=r.message||r.typedData?.message;if(!p||!m?.Order||!g)throw new Error("evm-order: CoW EIP-712 Order required");if(!fn(m,et))throw new Error("evm-order: cow types must be official GPv2 Order");if(Number(p.chainId)!==d)throw new Error("evm-order: cow domain chain mismatch");if(String(p.name)!=="Gnosis Protocol"||String(p.version)!=="v2")throw new Error("evm-order: cow domain must be official GPv2");if(re(p.verifyingContract)!==re(f))throw new Error("evm-order: cow verifyingContract must be official GPv2 settlement");let h=String(e.owner||"").toLowerCase();mn(h,g.receiver),pn(t,g.sellToken,g.buyToken);let w=re(g.sellToken),b=String(g.feeAmount||"0"),E=(BigInt(g.sellAmount)+BigInt(b)).toString();return Object.freeze({unit:`erc20:${w.toLowerCase()}`,value:E,notional:E,fee:b,submitTo:dn(r.submitTo,d),digest:un.hash(p,{Order:et.Order},g),chainId:d,kind:"cow",receiver:re(g.receiver),sellAmount:String(g.sellAmount),buyAmount:String(g.buyAmount)})}if(n!=="1inch-limit")throw new Error("evm-order: unsupported kind");if(rt(e.destination,"destination",32)!=="1inch-lop")throw new Error("evm-order: destination must be 1inch-lop");let o=Number(r.chainId??e.chainId),i=sn[o];if(!i)throw new Error(`evm-order: unsupported chainId ${o}`);ln(r.submitTo,o);let a=r.domain||r.typedData?.domain,u=r.types||r.typedData?.types,c=r.message||r.typedData?.message;if(!a||!u?.Order||!c)throw new Error("evm-order: EIP-712 Order required");if(!fn(u,Zr))throw new Error("evm-order: types must be official LOP v4 Order");if(Number(a.chainId)!==o)throw new Error("evm-order: domain chain mismatch");if(re(a.verifyingContract)!==re(i))throw new Error("evm-order: verifyingContract must be official LOP v4");if(a.name!=="1inch Limit Order Protocol"||String(a.version)!=="4")throw new Error("evm-order: EIP-712 domain must be official LOP v4");let s=String(e.owner||"").toLowerCase();if(re(c.maker).toLowerCase()!==s)throw new Error("evm-order: maker must equal owner");mn(s,c.receiver,{allowZero:!0}),pn(t,c.makerAsset,c.takerAsset);let l=un.hash(a,{Order:Zr.Order},c);return Object.freeze({unit:`erc20:${re(c.makerAsset).toLowerCase()}`,value:String(c.makingAmount),notional:String(c.makingAmount),fee:"0",submitTo:ln(r.submitTo,o),digest:l,chainId:o,kind:"1inch-limit",receiver:re(c.receiver),makerAsset:re(c.makerAsset),takerAsset:re(c.takerAsset),makingAmount:String(c.makingAmount),takingAmount:String(c.takingAmount)})}var bn=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]);var tt=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,delegate:0,identity:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0}),ha=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),xn=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"}}),ga=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),hr=new En(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),wn=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"]),ya=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 or=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},v=(e,t)=>{try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`envelope: ${t} must be a non-negative integer`)}},hn=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ea=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},M=(e,t,r)=>{if(!Ea(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},nr=(e,t,r)=>{Array.isArray(t)&&t.length&&M(e,t,r)},N=(e,t)=>{let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`envelope: ${t} must be a 20-byte address`);return r},Ie=e=>String(e||"0x").slice(0,10).toLowerCase(),An=e=>v(e.gasLimit,"gasLimit")*v(e.maxFeePerGas??e.gasPrice,"feePerGas")+v(e.l1FeeWei??0,"l1FeeWei")+v(e.operatorFeeWei??0,"operatorFeeWei");function Me(e,t,r,{dynamicTail:n=!1}={}){let o=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(o)||o.length<10+t*64)throw new Error(`envelope: malformed ${r} calldata`);if(!n&&o.length!==10+t*64)throw new Error(`envelope: malformed ${r} calldata`);return{hex:o,word:i=>o.slice(10+i*64,10+(i+1)*64)}}function q(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function te(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function ba(e){if(Ie(e)!=="0x095ea7b3")return null;let t=Me(e,2,"approval");return{kind:"approval",spender:q(t.word(0),"approval spender"),amount:te(t.word(1),"approval amount")}}function Sn(e,t){let r=t==="router02-exact-input-single"?7:8,n=Me(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:q(n.word(0),"input token"),outputToken:q(n.word(1),"output token"),recipient:q(n.word(3),"recipient"),amountIn:te(n.word(o),"amountIn"),minimumOut:te(n.word(o+1),"amountOutMinimum")}}function xa(e){let t=Me(e,12,"Across depositV3",{dynamicTail:!0}),r=te(t.word(11),"message offset");if(r!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let n=10+Number(r)*2;if(t.hex.length<n+64)throw new Error("envelope: malformed Across depositV3 message");let o=Number(BigInt(`0x${t.hex.slice(n,n+64)}`));if(!Number.isSafeInteger(o))throw new Error("envelope: malformed Across depositV3 message length");let i=Math.ceil(o/32)*64;if(t.hex.length!==n+64+i)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:q(t.word(0),"depositor"),recipient:q(t.word(1),"recipient"),inputToken:q(t.word(2),"input token"),outputToken:q(t.word(3),"output token"),amountIn:te(t.word(4),"inputAmount"),minimumOut:te(t.word(5),"outputAmount"),destinationChainId:te(t.word(6),"destinationChainId")}}function Aa(e){let t=String(e||"").replace(/^0x/i,"").toLowerCase();if(t.length<86||t.length%2!==0)throw new Error("envelope: malformed Uniswap path");let r=`0x${t.slice(0,40)}`,n=`0x${t.slice(t.length-40)}`;if(!/^0x[0-9a-f]{40}$/.test(r)||!/^0x[0-9a-f]{40}$/.test(n))throw new Error("envelope: malformed Uniswap path tokens");return{inputToken:r,outputToken:n}}function gn(e,{hasDeadline:t}){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<74)throw new Error("envelope: malformed exactInput calldata");let n=[];for(let h=10;h+64<=r.length;h+=64)n.push(r.slice(h,h+64));let o=(h,w)=>{if(!n[h])throw new Error(`envelope: malformed ${w}`);return BigInt(`0x${n[h]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let a=i/32,u=Number(o(a,"path offset")),c=n[a+1],s=o(a+(t?3:2),"amountIn"),l=o(a+(t?4:3),"amountOutMinimum"),d=a+u/32;if(!Number.isInteger(d)||!n[d])throw new Error("envelope: malformed exactInput path");let f=Number(o(d,"path length")),p=r.slice(10+(d+1)*64,10+(d+1)*64+f*2),{inputToken:m,outputToken:g}=Aa(`0x${p}`);return{kind:"action",action:"swap",inputToken:m,outputToken:g,recipient:q(c,"recipient"),amountIn:s,minimumOut:l}}function Sa(e){let t=Me(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:q(t.word(0),"input token"),outputToken:q(t.word(1),"output token"),recipient:q(t.word(3),"recipient"),amountIn:te(t.word(5),"amountIn"),minimumOut:te(t.word(6),"amountOutMinimum")}}function va(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let f=10;f+64<=t.length;f+=64)r.push(t.slice(f,f+64));let n=Number(BigInt(`0x${r[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${r[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let a=Number(BigInt(`0x${r[o+1]}`)),u=o+1+a/32,c=Number(BigInt(`0x${r[u]}`)),l=`0x${t.slice(10+(u+1)*64,10+(u+1)*64+c*2)}`,d=Ie(l);if(d!=="0x04e45aaf"&&d!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Sn(l,d==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function ka(e,t){let r=Ie(e),n=xn[r];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed selector");if(n.layout==="router02-exact-input-single"||n.layout==="swap-router-exact-input-single")return{...Sn(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...gn(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...gn(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...va(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Sa(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...xa(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Ta(e){let t=Me(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:q(t.word(0),"mint NFT contract"),feeRecipient:q(t.word(1),"mint fee recipient"),recipient:q(t.word(2),"mint recipient"),quantity:te(t.word(3),"mint quantity")}}function Ia(e){let t;try{t=wn.decodeFunctionData("mintAllowList",e)}catch{throw new Error("envelope: malformed SeaDrop mintAllowList calldata")}let r=t[4],n=[...t[5]].map(String);if(n.length<1||n.length>64||n.some(c=>!/^0x[0-9a-fA-F]{64}$/.test(c)))throw new Error("envelope: bounded canonical SeaDrop allowlist proof required");if(wn.encodeFunctionData("mintAllowList",[t[0],t[1],t[2],t[3],r,n]).toLowerCase()!==String(e).toLowerCase())throw new Error("envelope: SeaDrop allowlist calldata must be canonical");let i=BigInt(r.startTime),a=BigInt(r.endTime);if(a<=i)throw new Error("envelope: SeaDrop allowlist stage time range is invalid");let u=BigInt(t[3]);if(BigInt(r.maxTotalMintableByWallet)<u)throw new Error("envelope: SeaDrop allowlist wallet cap is below quantity");return{kind:"mint",action:"mint",mintType:"allowlist",contract:N(t[0],"mint NFT contract"),feeRecipient:N(t[1],"mint fee recipient"),recipient:N(t[2],"mint recipient"),quantity:u,mintPrice:BigInt(r.mintPrice),startTime:i,endTime:a,dropStageIndex:BigInt(r.dropStageIndex),proof:n}}function Oa(e,t){let r=Ie(e);if(String(t).toLowerCase()==="nft-mint")return Na(e);let n=ga[r];if(!n)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed NFT selector");if(n.layout==="seadrop-mint-public")return{...Ta(e),selector:r,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...Ia(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function Na(e){let t=Ie(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=ya[t];if(!r)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(r.layout==="mint-no-args")return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:1n};if(r.layout==="mint-quantity"){let n=Me(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:te(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function gr(e){let t=e?.artifact;if(Array.isArray(t?.transactions))return t.transactions;if(t?.transaction&&typeof t.transaction=="object")return[t.transaction];if(t?.data)return[t];throw new Error("envelope: ordered EVM transaction batch required")}function vn(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=N(e.owner,"owner"),u=e.artifact,c=Number(u?.chainId??gr(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(M(c,t.chains,"chain"),u?.owner!==void 0&&N(u.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let s=gr(e);if(!s.length||s.length>8)throw new Error("envelope: bounded EVM transaction batch required");let l=0n,d=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)!==c)throw new Error("envelope: every batch leg must use the same chain");if(N(p.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(M(Ie(p.data),t.selectors,"selector"),l+=v(p.value??0,"value"),d+=v(p.gasLimit,"gasLimit"),f+=An(p),ie(c)&&(p.l1FeeWei===void 0||p.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(l>v(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(d>v(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(f>v(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:s,chainId:c,owner:a,totalValue:l,totalGas:d,totalFee:f}}function kn(e,t,{nowMs:r=Date.now(),routeAttestationSecret:n}={}){let o=String(e?.surface||"");if(o!=="evm-swap"&&o!=="evm-bridge")throw new Error("envelope: strict EVM swap/bridge surface required");let i=or(e.provider,"provider",64).toLowerCase();M(i,t.providers,"provider");let a=vn(e,t,o,{nowMs:r}),u=[],c=-1;for(let m=0;m<a.transactions.length;m++){let g=a.transactions[m],h=ba(g.data),w;if(h){if(c!==-1)throw new Error("envelope: approval must be before action");if(v(g.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let S=N(g.to,"approval token");if(M(S,t.tokens,"token"),M(h.spender,t.spenders,"spender"),h.amount>v(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");w={...h,token:S,index:m}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");M(g.to,t.destinations,"destination"),w={...ka(g.data,i),target:N(g.to,"action target"),index:m},c=m}let b=v(g.value??0,"value"),E=v(g.gasLimit,"gasLimit");u.push({...w,value:b,gas:E,fee:An(g)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let s=u[c],l=o==="evm-swap"?"swap":"bridge";if(s.action!==l||e.action!==l)throw new Error("envelope: surface/action/calldata mismatch");if(N(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(M(s.inputToken,t.tokens,"input token"),M(s.outputToken,t.tokens,"output token"),s.amountIn<=0n||s.amountIn>v(t.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($r(e.autoSlippage,{nowMs:r,chainId:a.chainId,venue:i,tx:a.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(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 d=u.filter(m=>m.kind==="approval");if(!new Set([...ha,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(m=>String(m).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(d.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:u,action:s,provider:i,authenticatedQuote:p}}function Ca(e,t,{nowMs:r}){let n=e.anvilAttestation,o=e.artifact?.anvilAttestation;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("envelope: Anvil attestation is required");if(!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: Anvil attestation artifact mismatch");if(Number(n.version)!==1||n.source!=="anvil-snapshot-rpc-reviewed-runtime")throw new Error("envelope: unsupported Anvil attestation");if(Number(n.chainId)!==4663)throw new Error("envelope: Anvil attestation chain mismatch");let i=N(e.destination,"Anvil market"),a=N(e.contract,"NFT contract"),u=N(e.paymentToken,"payment token");if(N(n.market,"attested Anvil market")!==i)throw new Error("envelope: Anvil attestation market mismatch");if(N(n.collection,"attested NFT collection")!==a)throw new Error("envelope: Anvil attestation collection mismatch");if(N(n.paymentToken,"attested payment token")!==u)throw new Error("envelope: Anvil attestation payment token mismatch");let c=Number(e.paymentTokenDecimals??e.artifact?.paymentTokenDecimals);if(!Number.isSafeInteger(c)||c<0||c>255||Number(n.paymentTokenDecimals)!==c)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 l=Number(n.snapshotFetchedAtMs),d=Number(n.snapshotExpiresAtMs);if(!Number.isFinite(l)||!Number.isFinite(d)||l>r||d<=r||d<=l)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 m=Object.entries(t.anvilRuntimeCodeHashes||{}).find(([h])=>h.toLowerCase()===i)?.[1];if(!m||String(m).toLowerCase()!==p)throw new Error("policy: Anvil runtime code hash is not reviewed");let g=Object.entries(t.nftPaymentTokenCaps||{}).find(([h])=>h.toLowerCase()===u)?.[1];if(!g||Number(g.decimals)!==c)throw new Error("policy: Anvil payment token decimals are not reviewed");return Object.freeze({...n,market:i,collection:a,paymentToken:u,paymentTokenDecimals:c,runtimeCodeHash:p,blockNumber:f})}function yn(e,t){let r=e.artifact,n=e.anvilQuote,o=r?.anvilQuote;if(!n||typeof n!="object"||Array.isArray(n)||!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: exact Anvil quote artifact mismatch");if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("envelope: exact Anvil quote confirmation required");let i=t==="buy"?[[n.totalCostRaw,"anvilQuote.totalCostRaw"],[e.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw"],[r?.maxPaymentTokenAmountRaw,"artifact maxPaymentTokenAmountRaw"],[e.exactQuoteTotalCostRaw,"exactQuoteTotalCostRaw"],[r?.exactQuoteTotalCostRaw,"artifact exactQuoteTotalCostRaw"],[e.preconditions?.confirmedTotalCostRaw,"confirmedTotalCostRaw"]]:[[n.netPayoutRaw,"anvilQuote.netPayoutRaw"],[e.minPayoutRaw,"minPayoutRaw"],[r?.minPayoutRaw,"artifact minPayoutRaw"],[e.exactQuoteNetPayoutRaw,"exactQuoteNetPayoutRaw"],[r?.exactQuoteNetPayoutRaw,"artifact exactQuoteNetPayoutRaw"],[e.preconditions?.confirmedNetPayoutRaw,"confirmedNetPayoutRaw"]],a=v(i[0][0],i[0][1]);for(let[u,c]of i.slice(1))if(v(u,c)!==a)throw new Error(`envelope: Anvil ${t} exact settlement limit mismatch`);return a}function Tn(e,t,{nowMs:r=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint or NFT action");let n=or(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();nr(n,t.providers,"provider");let o=vn(e,t,"evm-nft",{nowMs:r});if(n==="anvil-nft"){if(e.action!=="nft")throw new Error("envelope: Anvil requires NFT action");if(o.chainId!==4663)throw new Error("envelope: Anvil requires chain 4663");if(t.confirmationMode!=="exact-human")throw new Error("policy: Anvil requires exact-human confirmation");if(o.transactions.length!==1)throw new Error("envelope: Anvil requires one atomic action with pre-existing approval");if(Number(e.slippageBps)!==0)throw new Error("envelope: Anvil exact limit requires zero slippageBps");let[p]=o.transactions,m=N(e.destination,"Anvil market");if(N(p.to,"Anvil action target")!==m)throw new Error("envelope: Anvil action target mismatch");M(m,t.destinations,"destination");let g=N(e.contract??e.artifact?.contract,"NFT contract");if(nr(g,t.nftContracts,"NFT contract"),N(e.marketCollection??e.artifact?.marketCollection,"Anvil market collection")!==g)throw new Error("envelope: Anvil market collection mismatch");let w=N(e.paymentToken??e.artifact?.paymentToken,"payment token");nr(w,t.erc20Tokens,"ERC20 token");let b=Ca(e,t,{nowMs:r}),E=v(e.tokenId??e.artifact?.tokenId,"tokenId"),S=v(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei");if(o.totalValue!==S||v(p.value??0,"Anvil action value")!==S)throw new Error("envelope: Anvil native swap fee mismatch");if(S>v(t.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"))throw new Error("policy: Anvil native swap fee exceeds cap");let k=or(e.nftAction,"nftAction",8).toLowerCase(),T;if(k==="buy"){let A=yn(e,k),B=Object.entries(t.nftPaymentTokenCaps||{}).find(([we])=>we.toLowerCase()===w)?.[1];if(!B)throw new Error("policy: Anvil payment-token cap required");if(A>v(B.maxPerTradeRaw,"maxPerTradeRaw"))throw new Error("policy: Anvil payment amount exceeds cap");if(e.preconditions?.allowanceVerified!==!0||v(e.preconditions?.allowanceRaw,"allowanceRaw")<A)throw new Error("envelope: Anvil pre-existing allowance proof required");let F=hr.decodeFunctionData("buySpecificNFT",p.data);if(hr.encodeFunctionData("buySpecificNFT",[F[0],F[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil buy calldata");if(BigInt(F[0])!==E)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(F[1])!==A)throw new Error("envelope: Anvil maxCost mismatch");T={kind:"nft",action:"buy",tokenId:E,maxPaymentTokenAmountRaw:A,target:m}}else if(k==="sell"){let A=e.preconditions||{},B=N(A.approvedAddress,"NFT approval address");if(A.nftApprovalVerified!==!0||B!==m&&A.approvedForAll!==!0)throw new Error("envelope: Anvil pre-existing NFT approval proof required");let F=yn(e,k),G=hr.decodeFunctionData("sellNFT",p.data);if(hr.encodeFunctionData("sellNFT",[G[0],G[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil sell calldata");if(BigInt(G[0])!==E)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(G[1])!==F)throw new Error("envelope: Anvil minPayout mismatch");T={kind:"nft",action:"sell",tokenId:E,minPayoutRaw:F,target:m}}else throw new Error("envelope: unsupported Anvil NFT action");return{...o,provider:n,nftAction:k,tokenId:E,paymentToken:w,paymentTokenDecimals:b.paymentTokenDecimals,anvilAttestation:b,decoded:[T]}}let i=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;if(i?.oraclePrepared===!0&&_t(i,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"}),o.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let a=o.transactions[0],u=Ie(a.data);M(u,t.selectors,"selector"),M(a.to,t.destinations,"destination");let c=Oa(a.data,n),s=N(e.contract??e.artifact?.contract,"NFT contract");if(nr(s,t.nftContracts,"NFT contract"),(c.contract||N(a.to,"NFT contract"))!==s)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==o.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&nr(c.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let d=v(e.quantity??e.artifact?.quantity,"quantity");if(d<=0n||d>v(t.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(c.quantity!==d)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(c.mintType==="allowlist"){let p=BigInt(Math.floor(r/1e3));if(c.startTime>p||c.endTime<=p)throw new Error("policy: SeaDrop allowlist stage is not open");if(c.mintPrice*d!==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")*d!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>v(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...o,provider:n,decoded:[{...c,target:N(a.to,"mint target"),value:o.totalValue,gas:o.totalGas,fee:o.totalFee}]}}function La(e,{localsWaiver:t=!1}={}){if(!(e in tt))throw new Error("fee: unknown action");return t?0:tt[e]}function ir(e,t,{nowMs:r=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:a=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let u=or(e.surface,"surface",16);if(!bn.has(u))throw new Error("envelope: unsupported public surface");let c=or(e.action,"action",32);M(u,t.surfaces,"surface"),M(c,t.actions,"action"),M(e.owner,t.owners,"owner"),M(e.destination,t.destinations,"destination");let s=hn(t.maxTtlMs,"maxTtlMs"),l=hn(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>s)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>l)throw new Error("policy: slippage exceeds cap");let d=e.artifact;if(!d||typeof d!="object"||Array.isArray(d))throw new Error("envelope: structured artifact required");if(u==="evm-swap"||u==="evm-bridge")kn(e,t,{nowMs:r,routeAttestationSecret:o});else if(u==="evm-nft")Tn(e,t,{nowMs:r});else if(u==="evm"){if(!["transfer","approve","delegate","identity"].includes(c))throw new Error(c==="mint"?"envelope: generic evm requires transfer or approve; use strict evm-nft for mint action":"envelope: generic evm requires transfer, approve, delegate, or identity");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(Number(d.type)===4&&c!=="delegate")throw new Error("envelope: type-4 requires delegate");if(String(d.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(String(d.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: artifact from mismatch with owner");pr({...d,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:a});let m=String(d.data||"0x").toLowerCase(),g=v(d.value,"EVM value");if(c==="delegate"){if(Number(d.type)!==4)throw new Error("envelope: delegate requires type-4");if(m!=="0x")throw new Error("envelope: 7702 delegate calldata must be empty");if(g!==0n)throw new Error("envelope: 7702 delegate cannot transfer native value")}else if(c==="identity"){if(g!==0n)throw new Error("envelope: ERC-8004 identity cannot transfer native value");let h=m.slice(0,10);if(h!=="0xf2c298be"&&h!=="0x0af28bd3")throw new Error("envelope: ERC-8004 selector not allowed")}else if(m==="0x"){if(g===0n)throw new Error("envelope: native EVM transfer value required")}else if(oe(m)){if(g!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else u==="btc"?Ur(e,t):u==="sol"?Gr(e,t):u==="hl"?ye(e,t):u==="poly"?Ee(e,t):u==="lighter"?be(e,t):u==="evm-order"&&Te(e,t);let f=Number(e.fee?.oracleFeeBps)===0&&tt[c]!==0;if(e.fee?.waiver||f&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(f&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let p=La(c,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==p)throw new Error("fee: final artifact fee mismatch");return!0}var nt=Object.freeze([...bn]),Dl=Object.freeze({...xn});function ot(e,t){if(e.surface==="hl")return ye(e,t);if(e.surface==="poly")return Ee(e,t);if(e.surface==="lighter")return be(e,t);if(e.surface==="evm-order")return Te(e,t);if(e.surface==="btc")return Ur(e,t);if(e.surface==="sol")return Gr(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=kn(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1),routeAttestationSecret:t.routeAttestationSecret}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(e.surface==="evm-nft"){let r=Tn(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalFee.toString();if(r.provider==="anvil-nft"&&r.nftAction==="buy"){let i=v(e.maxPaymentTokenAmountRaw??e.artifact?.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw").toString(),a=r.totalValue.toString(),u=r.totalFee,c=[{unit:`erc20:${r.paymentToken}`,value:i,notional:i,fee:"0"},{unit:"wei",value:a,notional:(r.totalValue+u).toString(),fee:u.toString()}].sort((s,l)=>s.unit<l.unit?-1:s.unit>l.unit?1:0);return Object.freeze({units:c})}let o=r.totalValue.toString();return Object.freeze({unit:"wei",value:o,notional:(r.totalValue+r.totalFee).toString(),fee:n})}if(String(e.surface).startsWith("evm")){let r=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:r.toString(),notional:(r+i).toString(),fee:i.toString()})}throw new Error("envelope: unsupported public surface")}function In(e={}){let t={};for(let r of nt){let n=e[r];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${r} requires simulate, sign, and broadcast functions`);t[r]=Object.freeze({simulate:(o,i)=>n.simulate(structuredClone(o),structuredClone(i)),sign:(o,i)=>n.sign(structuredClone(o),structuredClone(i)),broadcast:(o,i,a)=>n.broadcast(o,structuredClone(i),structuredClone(a))})}}return Object.freeze(t)}function yr(e,t){let r=e?.surface||"evm",n=t?.[r];if(!n)throw new Error(`adapter: ${r} is not configured on this self-host`);return n}import{createHash as Rn}from"node:crypto";import{ed25519 as ja}from"@noble/curves/ed25519.js";import{base58 as $n}from"@scure/base";import{RawTx as lt,SigHash as Oe,Transaction as dt}from"@scure/btc-signer";import{Transaction as ft,keccak256 as ct,verifyTypedData as ut}from"ethers";import{encode as Ba}from"@msgpack/msgpack";import{keccak256 as Pa,verifyTypedData as Ra}from"ethers";var De=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),it=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function On(e){let t=BigInt(e);if(t<0n||t>=2n**64n)throw new Error("hl-l1: nonce must fit uint64");let r=Buffer.alloc(8);return r.writeBigUInt64BE(t),r}function _a(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Ba(e)),On(t)];if(r){let a=String(r).replace(/^0x/i,"");if(!/^[0-9a-fA-F]{40}$/.test(a))throw new Error("hl-l1: vaultAddress must be a 20-byte address");i.push(Buffer.from([1]),Buffer.from(a,"hex"))}else i.push(Buffer.from([0]));return n!=null&&i.push(Buffer.from([0]),On(n)),Pa(Buffer.concat(i))}function at(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:_a(e,t,{vaultAddress:n,expiresAfter:o})}}function Nn(e){let t=e?.typedData;if(t==null)return null;if(typeof t!="object")throw new Error("hl-l1: typedData must match the validated action");if(Object.prototype.hasOwnProperty.call(e,"vaultAddress"))throw new Error("hl-l1: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(e,"expiresAfter"))throw new Error("hl-l1: expiresAfter is not public");let r=at(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==De.name||String(t.domain?.version)!==De.version||Number(t.domain?.chainId)!==De.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(De.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(it.Agent))throw new Error("hl-l1: typedData types must be Hyperliquid Agent");if(t.message?.source!==r.source||String(t.message?.connectionId||"").toLowerCase()!==String(r.connectionId).toLowerCase())throw new Error("hl-l1: typedData message must hash the validated action");return r}async function Cn({wallet:e,action:t,nonce:r,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let a=at(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(De,it,a)}function Ln({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:a=null}){try{let u=at(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:a}),c=Ra(De,it,u,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var $a=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function st(e){if(e!=null){if(typeof e=="function")throw new Error("lighter: signed tx_info cannot include functions");if(typeof e=="object"){if(typeof e.toJSON=="function")throw new Error("lighter: signed tx_info cannot define toJSON");if(Array.isArray(e)){for(let t of e)st(t);return}for(let t of Object.values(e))st(t)}}}function Fa(e){if(typeof e=="string"){if(!e.startsWith("{"))throw new Error("lighter: official signed tx_info JSON required");let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("lighter: official signed tx_info JSON required");return t}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("lighter: official signed tx_info JSON required");return st(e),JSON.parse(JSON.stringify(e))}function Er(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function Ma(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^-?(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function Bn(e,t,{signed:r=!1}={}){if(typeof e!="number"||!Number.isSafeInteger(e)||!r&&e<0)throw new Error(`lighter: signed ${t} must be an exact numeric integer`);return e}function Ue(e,t,r,n={}){let o=t.filter(a=>e[a]!==void 0&&e[a]!==null);if(o.length===0)throw new Error(`lighter: ${r} required`);let i=o.map(a=>Bn(e[a],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function Da(e,t,r){let n=t.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length===0)throw new Error(`lighter: ${r} required`);let o=n.map(i=>String(e[i]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${r}`);return e[n[0]]}function qe(e,t,r,n){let o=Ue(e,t,n);if(BigInt(o)!==Er(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function qa(e,t,r,n){let o=Ue(e,t,n,{signed:!0});if(BigInt(o)!==Ma(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Ua(e){let t={};for(let[r,n]of $a.entries()){let o=n.filter(a=>e[a]!==void 0&&e[a]!==null);if(!o.length)continue;let i=o.map(a=>{let u=e[a];if(r<3)return Bn(u,n[0]);if(typeof u!="string"||u.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return u});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);t[n[0]]=i[0]}return t}function ar(e,t){let r=Fa(t),n=qe(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=qe(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=qe(r,["Type","type"],e.orderType,"Type"),a=qe(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),u=qe(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),c=qe(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),s=qa(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),l=Ue(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),d=Ue(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),f=Ue(r,["Price","price"],"Price");if(BigInt(l)!==Er(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(d)!==Er(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==Er(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let p=Da(r,["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 m=p===1,g=e.side==="sell";if(m!==g)throw new Error("lighter: signed IsAsk must match the prepared side");let h=Ue(r,["txType","tx_type","TxType"],"txType");if(h!==Xr)throw new Error("lighter: signed txType must be official create-order");let w={...Ua(r),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:a,ReduceOnly:u,TriggerPrice:c,OrderExpiry:s,MarketIndex:Number(l),BaseAmount:Number(d),Price:Number(f),IsAsk:m?1:0,txType:h},b=JSON.stringify(w),E=JSON.parse(b);if(E.MarketIndex!==Number(l)||E.BaseAmount!==Number(d)||E.Price!==Number(f)||E.IsAsk!==(m?1:0)||E.txType!==h)throw new Error("lighter: canonical tx_info mutated");return{txType:h,txInfo:b,submitTo:Qr(e.submitTo)}}function Pn(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var je=e=>{if(typeof e!="string"||e.length===0||e.length>262144||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return null;let t=Buffer.from(e,"base64");return t.toString("base64")===e?t:null},br=e=>String(e||"").toLowerCase();function Wa(e,t){if(typeof e!="string")return!1;let r,n;try{r=ft.from(e),n=ft.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce,type:t.type,accessList:t.accessList,authorizationList:t.authorizationList})}catch{return!1}return br(r.from)!==br(t.from)||br(r.to)!==br(t.to)?!1:r.unsignedHash===n.unsignedHash}function Ha(e){let t=Buffer.from(lt.encode(e)),r=Rn("sha256").update(t).digest();return Buffer.from(Rn("sha256").update(r).digest()).reverse().toString("hex")}function _n(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Ha(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))return!1;let t=e.nonWitnessUtxo.outputs?.[e.index];return t?BigInt(e.witnessUtxo.amount)===BigInt(t.amount)&&Buffer.from(e.witnessUtxo.script||[]).equals(Buffer.from(t.script||[])):!1}function Ja(e,t){let r=je(e),n=je(t.psbt);if(!r||!n)return!1;try{let o=dt.fromPSBT(n),i=dt.fromPSBT(r);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let a=0;a<i.inputsLength;a++){let u=i.getInput(a),c=o.getInput(a);if(!_n(c)||!_n(u))return!1;let s=(w,b)=>{if(w==null&&b==null)return!0;if(w==null||b==null)return!1;try{return Buffer.from(w).equals(Buffer.from(b))}catch{return!1}},l=(w,b)=>{if(w==null&&b==null)return!0;if(w==null||b==null)return!1;try{return Buffer.from(lt.encode(w)).equals(Buffer.from(lt.encode(b)))}catch{return s(w,b)}};if(!!u.witnessUtxo!=!!c.witnessUtxo||u.witnessUtxo&&(BigInt(u.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!s(u.witnessUtxo.script,c.witnessUtxo.script))||!l(u.nonWitnessUtxo,c.nonWitnessUtxo)||!s(u.redeemScript,c.redeemScript)||!s(u.witnessScript,c.witnessScript)||u.sighashType!==void 0&&u.sighashType!==Oe.DEFAULT&&u.sighashType!==Oe.ALL)return!1;let d=w=>!(w instanceof Uint8Array)||w.length<9?!1:w[w.length-1]===Oe.ALL,f=w=>w instanceof Uint8Array?w.length===64?!0:w.length===65&&w[64]===Oe.ALL:!1;for(let w of u.partialSig||[]){let b=Array.isArray(w)?w[1]:w;if(!d(b))return!1}if(u.tapKeySig&&!f(u.tapKeySig))return!1;for(let w of u.tapScriptSig||[]){let b=Array.isArray(w)?w[1]:w;if(!f(b))return!1}let p=w=>w[w.length-1]===Oe.ALL,m=w=>w.length>=9&&w.length<=73&&w[1]===w.length-3&&w[2]===2,g=w=>{let b=!1;for(let E of w)if(E instanceof Uint8Array){if(E[0]===48){if(!m(E)||!p(E))return!1;b=!0;continue}if(E.length===64){b=!0;continue}if(E.length===65){if(E[64]!==Oe.ALL&&E[64]!==Oe.DEFAULT)return!1;b=!0}}return b};if(u.finalScriptWitness){let w;if(Array.isArray(u.finalScriptWitness))w=u.finalScriptWitness;else if(u.finalScriptWitness instanceof Uint8Array){let b=u.finalScriptWitness,E=T=>{let A=b[T];return A===void 0?null:A<253?{value:A,next:T+1}:A===253?{value:b[T+1]|b[T+2]<<8,next:T+3}:null},S=E(0);if(!S)return!1;w=[];let k=S.next;for(let T=0;T<S.value;T++){let A=E(k);if(!A||k+A.value>b.length)return!1;w.push(b.slice(A.next,A.next+A.value)),k=A.next+A.value}if(k!==b.length)return!1}else return!1;if(!w.length||!g(w))return!1}if(u.finalScriptSig instanceof Uint8Array&&u.finalScriptSig.length){let w=u.finalScriptSig,b=[],E=0;for(;E<w.length;){let S=w[E];if(S>=1&&S<=75){if(E+1+S>w.length)return!1;b.push(w.slice(E+1,E+1+S)),E+=1+S;continue}if(S===76){let k=w[E+1];if(k===void 0||E+2+k>w.length)return!1;b.push(w.slice(E+2,E+2+k)),E+=2+k;continue}return!1}if(!b.length||!g(b))return!1}if(![u.partialSig,u.tapKeySig,u.tapScriptSig,u.finalScriptSig,u.finalScriptWitness].some(w=>Array.isArray(w)||w instanceof Uint8Array?w.length>0:w!=null))return!1}return!0}catch{return!1}}function Fn(e){let t=0,r=0,n=0;for(;n<e.length&&n<3;){let o=e[n++];if(t|=(o&127)<<r,(o&128)===0)return{value:t,offset:n};r+=7}return null}function za(e,t,r){let n=je(e),o=je(t.messageBase64);if(!n||!o)return!1;let i=Fn(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let u=n.subarray(i.offset,a),c=n.subarray(a);if(!c.equals(o))return!1;try{let s=$n.decode(String(r));return s.length===32&&ja.verify(u,c,s)}catch{return!1}}function Mn(e,t,r,n){if(e==="evm-order"){let o=r?.domain||r?.typedData?.domain,i=r?.types||r?.typedData?.types,a=r?.message||r?.typedData?.message;if(!o||!i||!a)return!1;try{return String(ut(o,i,a,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}}if(String(e).startsWith("evm"))return Wa(t,r);if(e==="btc")return Ja(t,r);if(e==="sol")return za(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String(ut(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return Ln({signature:t,action:r?.action,nonce:r?.nonce,isMainnet:!String(r?.submitTo||"").includes("testnet"),owner:n?.owner})}if(e==="poly"&&r?.domain&&r.types&&r.message)try{return String(ut(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return ar(r,t),!0}catch{return!1}return!1}function Dn(e,t){try{if(e==="evm-order")return ct(t);if(String(e).startsWith("evm"))return ft.from(t).hash;if(e==="btc"){let r=je(t);if(!r)return null;let n=dt.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=je(t);if(!r)return null;let n=Fn(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?$n.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return ct(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return ct(t)}catch{}return null}var Ya=e=>String(e||"").toLowerCase();function J(e){return Ga("sha256").update(JSON.stringify(e)).digest("hex")}function Sr(e,t,r={}){return pr(e,t,r)}async function Xa(e,t={}){if(!ie(e?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(typeof t.estimateNetworkFees!="function")throw new Error("policy: rollup fee estimate required");let r=await t.estimateNetworkFees(e);if(!r||r.l1FeeWei===void 0||r.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");return{l1FeeWei:String(r.l1FeeWei),operatorFeeWei:String(r.operatorFeeWei)}}function Un(e,t,r=!1){if(!ie(e?.chainId))return!0;if(e.l1FeeWei===void 0||e.operatorFeeWei===void 0)throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei");if(r||t!=null){if(!t||t.l1FeeWei===void 0||t.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let n=BigInt(e.l1FeeWei)+BigInt(e.operatorFeeWei),o=BigInt(t.l1FeeWei)+BigInt(t.operatorFeeWei);if(n<o)throw new Error("policy: rollup fee attestation understates estimate")}return!0}var xr=class{#e=new Map;constructor({now:t=Date.now}={}){this.now=t}issue({artifact:t,owner:r,ttlMs:n=6e4}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=Va(32).toString("hex");return this.#e.set(o,{digest:J(t),owner:Ya(r),expiresAtMs:this.now()+n}),o}consume(t,r){let n=this.#e.get(String(t));if(!n)throw new Error("confirmation: used or unknown nonce");if(n.expiresAtMs<=this.now())throw this.#e.delete(String(t)),new Error("confirmation: expired nonce");let o=Buffer.from(n.digest,"hex"),i=Buffer.from(J(r),"hex");if(!Ka(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(t)),n}clear(){this.#e.clear()}};function Qa(e){let t=String(e?.data||"0x").toLowerCase(),r=BigInt(e?.value??0);if(t==="0x"){if(r<=0n)throw new Error("signer: native EVM transfer value required");return!0}if(oe(t)){if(r!==0n)throw new Error("signer: EVM approval cannot transfer native value");return!0}throw new Error("signer: unsupported EVM calldata; use a versioned envelope")}function Za(e={},t={}){let r={};for(let n of new Set([...Object.keys(e||{}),...Object.keys(t||{})]))r[n]=(BigInt(t?.[n]??0)-BigInt(e?.[n]??0)).toString();return r}function es(e){return e==="evm"||e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Ar(e,t){let r=String(t||"");if(e==="evm-order"||String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(r);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(r);if(e==="sol")try{let n=qn.decode(r);return n.length===64&&qn.encode(n)===r}catch{return!1}return e==="hl"?/^0x[0-9a-fA-F]{64}$/.test(r):e==="poly"?/^0x[0-9a-fA-F]{64}$/.test(r):!1}function jn(e,t,r){return!Ar(e,t)||!Ar(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function rs(e){let t=e?.confirmationMode;if(t!=="exact-human"&&t!=="auto-within-rails")throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");return t}async function pt({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:u}){let c=rs(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(t?.triggerAttestation,e,u())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(a)return n.confirmations.consume(r,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=u())throw new Error("confirmation: expired nonce");return i}function ts(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function ns(e,t){return e&&ts(e.surface)?gr(e):[t]}function os(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!jn(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function is(e,t){let r=e?.verifiedBefore??e?.before,n=e?.verifiedAfter??e?.after;return{transactionHash:t,status:e?.status,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:Za(r,n)}}async function mt(e,t,r){if(!r.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:h,...w}=e||{};return w})(),i=ns(n,o),a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,u=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),c=await pt({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:null,consumeNonce:!0,nowMs:u}),s=J(e),l=(h={})=>{n?ir(n,a,h):(Sr(o,a,{nowMs:h.nowMs,networkFees:h.networkFees,requireNetworkFees:h.requireNetworkFees}),Qa(o))},d=async h=>{let w=!n||es(n.surface),b=w?await Xa(h,r):void 0;return{nowMs:u(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:b,requireNetworkFees:w&&ie(h?.chainId)}};l({nowMs:u(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let h of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[h]!="function")throw new Error(`signer: ${h} is required`);let f=r.reserveLedger(n||e,a);if(!f)throw new Error("signer: ledger reservation required");let p=!1,m=[];try{for(let h of i){if(typeof r.simulate!="function"||await r.simulate(h,n)!==!0)throw new Error("signer: strict affirmative simulation required");let w=await d(h);if((w.requireNetworkFees||w.networkFees!=null)&&Un(h,w.networkFees,w.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await pt({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:u}),l(w),r.validateReservation(f,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0),p=!0;let b=await r.sign(h,n);if(typeof r.verifySigned!="function"||await r.verifySigned(b,h,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!r.isArmed())throw new Error("signer: disarmed before broadcast");if(J(e)!==s)throw new Error("signer: artifact mutated after signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await pt({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:u});let E=await d(h);(E.requireNetworkFees||E.networkFees!=null)&&Un(h,E.networkFees,E.requireNetworkFees),l(E),r.validateReservation(f,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0);let S=await r.broadcast(b,h,n),k=S?.status,T=n?.surface||"evm",A=os(S,T),B=Dn(T,b);if(!jn(T,A,B))throw new Error("signer: receipt transaction hash does not match signed bytes");if(k===0||k==="0x0")throw Ar(T,A)?(r.settleFailedLedger(f),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(k!==1&&k!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Ar(T,A))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(is(S,A))}}catch(h){throw p||r.releaseLedger(f),h}if(r.commitLedger(f),m.length===1){let h={receipt:m[0]};return n?.surface==="evm-bridge"&&(h.originStatus="success",h.destinationStatus="unverified",h.destinationSuccess=!1,h.note="Origin-chain receipts do not prove destination-chain settlement."),h}let g={receipts:m,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 Wn=new Set(["127.0.0.1","::1","localhost"]),cs=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&ss(r,n)},O=(e,t,r)=>{let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function us(e){let t=String(e||"");if(t.startsWith("[")){let r=t.indexOf("]");if(r>1)return t.slice(1,r)}return t.split(":")[0]}var sr=e=>new Promise((t,r)=>{let n=0,o=[],i=!1;e.on("data",a=>{n+=a.length,n>64*1024&&!i?(i=!0,r(new Error("request refused")),e.resume()):i||o.push(a)}),e.on("end",()=>{if(!i)try{t(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{r(new Error("request refused"))}}),e.on("error",r)});function Hn(e={}){let t=e.host||"127.0.0.1";if(!Wn.has(t))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let c of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[c]!="function")throw new Error(`signer: ${c} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new xr,n=e.pending||new Map;function o(c){let s=c.artifact?.version===1&&c.artifact?.surface?c.artifact:null,l=s?.artifact||c.artifact||{};return{id:c.digest.slice(0,8),digest:c.digest,surface:s?.surface||"evm",action:s?.action||"evm",chain:l.chainId??l.network??null,to:l.to||s?.destination||null,value:l.value??l.message?.sellAmount??l.message?.makingAmount??null,receiver:l.message?.receiver||l.typedData?.message?.receiver||null,maker:l.message?.maker||l.typedData?.message?.maker||null,makingAmount:l.message?.makingAmount||l.typedData?.message?.makingAmount||null,takingAmount:l.message?.takingAmount||l.typedData?.message?.takingAmount||null,sellAmount:l.message?.sellAmount||l.typedData?.message?.sellAmount||null,buyAmount:l.message?.buyAmount||l.typedData?.message?.buyAmount||null,kind:l.kind||null,type:l.type??null,authorizationList:l.authorizationList||null,feeAmount:l.message?.feeAmount||l.typedData?.message?.feeAmount||null,createdAtMs:c.createdAtMs}}function i(c){let s=String(c||"").trim().toLowerCase().replace(/^0x/,"");return s?[...n.values()].filter(l=>l.digest.toLowerCase().startsWith(s)||l.digest.slice(0,8)===s):[...n.values()]}let a=e.origin||`http://${t}`;return as.createServer(async(c,s)=>{try{let l=String(c.headers.authorization||"").replace(/^Bearer /i,"");if(!cs(l,e.token))return O(s,401,{error:"unauthorized"});let d=us(c.headers.host);if(!Wn.has(d))return O(s,403,{error:"host refused"});if(c.headers.origin&&c.headers.origin!==a)return O(s,403,{error:"origin refused"});if(c.method==="GET"&&c.url==="/status"){let f=typeof e.readPolicy=="function"?e.readPolicy():e.policy,p=new Set(nt),m=Array.isArray(f?.surfaces)?f.surfaces.filter(g=>typeof g=="string"&&p.has(g)):[];return O(s,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:m,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(c.method==="POST"&&c.url==="/disarm")return e.disarm(),r.clear(),n.clear(),O(s,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(c.method))return O(s,405,{error:"request refused"});if(c.method==="POST"&&String(c.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return O(s,415,{error:"request refused"});if(c.method==="GET"&&c.url==="/pending"){let f=[...n.values()].map(o);return O(s,200,{ok:!0,armed:e.isArmed?.()===!0,count:f.length,items:f})}if(c.method==="POST"&&c.url==="/pending"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not queue human approvals"});let p=(await sr(c)).artifact;if(!p||typeof p!="object")return O(s,400,{error:"artifact required"});let m=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(m?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});let g=typeof e.nowMs=="function"?e.nowMs():Date.now();if(p?.version===1&&p?.surface)ir(p,m,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:w,...b}=p||{};Sr(b,m,{nowMs:g})}let h=J(p);return n.set(h,{artifact:p,digest:h,createdAtMs:g}),O(s,200,{ok:!0,...o(n.get(h))})}if(c.method==="POST"&&c.url==="/ack"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not accept messaging acks"});let f=await sr(c),p=i(f.digest||f.id);if(p.length===0)return O(s,404,{error:"no pending artifact"});if(p.length>1)return O(s,409,{error:"ambiguous digest; pass more hex"});let m=p[0];if((typeof e.readPolicy=="function"?e.readPolicy():e.policy)?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});if(e.isArmed?.()!==!0)return O(s,403,{error:"signer is disarmed"});n.delete(m.digest);let h=r.issue({artifact:m.artifact,owner:m.artifact?.owner??m.artifact?.from,ttlMs:f.ttlMs}),w=await mt(m.artifact,h,{...e,confirmations:r});return O(s,200,{ok:!0,executed:!0,confirmationNonce:h,digest:m.digest,id:m.digest.slice(0,8),result:w})}if(c.method==="POST"&&c.url==="/deny"){let f=await sr(c),p=i(f.digest||f.id);return p.length===0?O(s,404,{error:"no pending artifact"}):p.length>1?O(s,409,{error:"ambiguous digest; pass more hex"}):(n.delete(p[0].digest),O(s,200,{ok:!0,denied:!0,id:p[0].digest.slice(0,8)}))}if(c.method==="POST"&&c.url==="/confirm"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not issue human confirmation nonces"});let f=await sr(c),p=J(f.artifact),m=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(m?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});let g=typeof e.nowMs=="function"?e.nowMs():Date.now();if(f.artifact?.version===1&&f.artifact?.surface)ir(f.artifact,m,{nowMs:g,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:h,...w}=f.artifact||{};Sr(w,m,{nowMs:g})}return typeof e.confirmArtifact!="function"?O(s,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(f.artifact,p,m)!==!0?O(s,400,{error:"exact human confirmation refused"}):O(s,200,{confirmationNonce:r.issue({artifact:f.artifact,owner:f.artifact?.owner??f.artifact?.from,ttlMs:f.ttlMs})})}if(c.method==="POST"&&c.url==="/execute"){let f=await sr(c),p=await mt(f.artifact,f.confirmationNonce,{...e,confirmations:r});return O(s,200,p)}return O(s,404,{error:"not found"})}catch(l){e.onError?.(String(l?.message||l));let d=String(c.url||"");return d==="/pending"||d==="/ack"||d==="/deny"?O(s,400,{error:String(l?.message||"request refused").slice(0,300)}):O(s,400,{error:"request refused"})}})}import{createCipheriv as pd,createDecipheriv as ls,randomBytes as ds,scryptSync as fs}from"node:crypto";import C from"node:fs";import We from"node:path";var ps="ORACLE-LOCAL-VAULT",ms=1,kr=Object.freeze({N:1<<17,r:8,p:1}),ws=256*1024*1024,hs=16*1024;function vr(e,t,r,{max:n=t}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${r} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<t||o.length>n)throw new Error(`local-vault: invalid ${r} length`);return o}function gs(e,t,r=kr){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return fs(n,t,32,{...r,maxmem:ws})}function Jn(e,t){if(e?.magic!==ps||e?.version!==ms)throw new Error("local-vault: unsupported vault file");if(e?.kdf?.name!=="scrypt"||e?.cipher?.name!=="aes-256-gcm")throw new Error("local-vault: unsupported cryptography");if(e.kdf.N!==kr.N||e.kdf.r!==kr.r||e.kdf.p!==kr.p)throw new Error("local-vault: unsupported KDF parameters");if(Object.keys(e.kdf).sort().join(",")!=="N,name,p,r,salt"||Object.keys(e.cipher).sort().join(",")!=="iv,name")throw new Error("local-vault: unexpected cryptography field");if(!e.meta||Object.keys(e.meta).some(d=>!["address","addresses","kind","createdAt"].includes(d))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||JSON.stringify(e.meta.addresses||{}).length>1024||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let r=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(d=>!r.includes(d)))throw new Error("local-vault: unexpected vault field");let n=vr(e.kdf.salt,32,"salt"),o=vr(e.cipher.iv,12,"iv"),i=vr(e.tag,16,"tag"),a=vr(e.ciphertext,1,"ciphertext",{max:hs}),{ciphertext:u,tag:c,...s}=e,l=gs(t,n);try{let d=ls("aes-256-gcm",l,o);return d.setAAD(Buffer.from(JSON.stringify(s))),d.setAuthTag(i),Buffer.concat([d.update(a),d.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{l.fill(0)}}function ys(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 Es(e){let t=We.dirname(e),r=C.lstatSync(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(r.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((r.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=C.lstatSync(e);if(n.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!n.isFile()||n.uid!==process.getuid?.()||n.nlink!==1)throw new Error("local-vault: unsafe destination file");if(n.dev!==r.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function _(e){let t;try{t=C.openSync(e,C.constants.O_RDONLY|C.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=C.fstatSync(t);if(ys(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=C.lstatSync(e);if(n.isSymbolicLink()||n.dev!==r.dev||n.ino!==r.ino)throw new Error("local-vault: secret source changed or is too large");return C.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{C.closeSync(t)}}function zn(e){return JSON.parse(_(e))}function xe(e,t){C.mkdirSync(We.dirname(e),{recursive:!0,mode:448}),Es(e);let r=We.join(We.dirname(e),`.${We.basename(e)}.${process.pid}.${ds(6).toString("hex")}.tmp`);try{let n=C.openSync(r,C.constants.O_CREAT|C.constants.O_EXCL|C.constants.O_WRONLY|C.constants.O_NOFOLLOW,384);try{C.writeFileSync(n,String(t)),C.fsyncSync(n)}finally{C.closeSync(n)}C.renameSync(r,e),C.chmodSync(e,384);let o=C.openSync(We.dirname(e),"r");try{C.fsyncSync(o)}finally{C.closeSync(o)}}catch(n){try{C.unlinkSync(r)}catch{}throw n}}var Gn=/^0x[0-9a-fA-F]+$/,bs=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});function xs(e){let t=process.env[`ORACLE_PRIVATE_RELAY_${Number(e)}`];if(!t)return null;let r=t.split(",").map(n=>n.trim()).filter(Boolean);return r.length?r:null}function As(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=bs[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=xs(r),i=o||n.endpoints,a=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&a!=="public-only";if(t&&!u)throw new Error(`private relay: no keyless private endpoint for chain ${r} (${n.name}); set ORACLE_PRIVATE_RELAY_${r} to force one, or allow public fallback`);return{chainId:r,name:n.name,mode:a,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function Vn(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!Gn.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let a=As(t,{requirePrivate:r}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let c=[];for(let s of a.endpoints){let l=new AbortController,d=setTimeout(()=>l.abort(),i);try{let f=await u(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendRawTransaction",params:[e]}),signal:l.signal}),p=await f.text(),m=null;try{m=JSON.parse(p)}catch{}if(m&&m.result&&Gn.test(m.result))return{hash:m.result,endpoint:s,mode:a.mode,chainId:a.chainId,fellBack:!1};c.push({endpoint:s,error:m&&m.error&&m.error.message||`http ${f.status}`})}catch(f){c.push({endpoint:s,error:String(f&&f.message||f).slice(0,160)})}finally{clearTimeout(d)}}if(n&&!r)return{fellBack:!0,mode:a.mode,chainId:a.chainId,attempts:c};throw new Error(`submitPrivate: all private endpoints failed for chain ${a.chainId} (${c.map(s=>`${s.endpoint}:${s.error}`).join("; ")||"none configured"})`)}import{createHmac as vs,randomBytes as ks,timingSafeEqual as Ts}from"node:crypto";import U from"node:fs";import Ne from"node:path";import{homedir as wt}from"node:os";import{join as ht}from"node:path";var Kn=process.env.ORACLE_PUBLIC_DESKTOP==="1",Ss=Kn?process.env.ORACLE_CONFIG_DIR||ht(wt(),".config","oracle"):ht(wt(),".config","oracle"),bd=Kn?Ss:ht(wt(),".config","mad-desk");var kd="0".repeat(64),Td=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 Tr(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Tr).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Tr(e[r])).join(",")+"}"}var Id=Promise.resolve();function Je(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=a=>{try{return U.realpathSync(a)}catch{return Ne.resolve(a)}},n=r(Ne.dirname(Ne.resolve(e))),o=r(Ne.dirname(Ne.resolve(t))),i=(a,u)=>u===a||u.startsWith(a+Ne.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var Is=864e5,z=(e,t)=>vs("sha256",t).update(Tr(e)).digest("hex"),ce=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Ts(r,n)},Os=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Ns(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!ce(e.integrity.mac,z(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Or(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=_(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!ce(n?.integrity?.mac,z(n?.marker,t)))throw new Error("policy: sequence anchor integrity failed");return{sequence:Number(n?.marker?.policySequence||0),policyMac:n?.marker?.policyMac??null,present:!0,ledgerInitialized:n?.marker?.ledgerInitialized===!0}}function Cs(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let u=Or(e,r);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(t),policyMac:String(n)};i&&(a.ledgerInitialized=!0),xe(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:z(a,r)}})+`
4
+ `)}function Ls(e,t){let r=Or(e,t);if(!r.present)throw new Error("policy: sequence anchor required");if(r.ledgerInitialized)return!0;if(r.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");return Cs(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function Yn(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=_(t),o;try{o=JSON.parse(_(e))}catch(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=Ns(o,n);Je(r,e);let a=Or(r,n),u=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(u!==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(!ce(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function cr(e,t,r,n,o){let i=`${e}.continuity`,a;try{let u=JSON.parse(_(e));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!ce(u?.integrity?.mac,z(u.ledger,t)))throw new Error("integrity verification failed");if(a=u.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(u){if(u?.code==="ENOENT"){if(U.existsSync(i)||U.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=Or(o,t);if(c.present&&c.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:r,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}try{let u=JSON.parse(_(i));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!ce(u?.integrity?.mac,z(u.marker,t)))throw new Error("continuity verification failed");if(u.marker?.version===2&&(u.marker.sequence!==a.sequence||!ce(u.marker.ledgerMac,z(a,t))))throw new Error("continuity rollback detected");if(u.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(U.existsSync(n)&&(u.marker?.version!==2||a.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(u.marker?.version===2){let c=JSON.parse(_(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!ce(c?.integrity?.mac,z(c.marker,t))||c.marker?.version!==1||c.marker.sequence!==a.sequence||!ce(c.marker.ledgerMac,z(a,t)))throw new Error("checkpoint rollback detected")}}catch(u){throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}if(r-a.windowStartMs>=Is){let u=a.entries.map(c=>c.state==="reserved"?c:Array.isArray(c.units)?{...c,state:"consumed",units:c.units.map(s=>({...s,value:"0",notional:"0"}))}:{...c,state:"consumed",value:"0",notional:"0"});return{windowStartMs:r,entries:u,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function Bs(e){return Array.isArray(e.units)?e.units:[{unit:e.unit||"wei",value:e.value,notional:e.notional,fee:e.fee}]}function Ae(e,t,r){return e.reduce((n,o)=>{let i=Bs(o).find(a=>a.unit===r);return i?n+BigInt(i[t]??0):n},0n)}function gt(e){if(!Array.isArray(e)||e.length===0)throw new Error("ledger: units array required");let t=new Set,r=e.map(n=>{let o=String(n?.unit||"");if(!o)throw new Error("ledger: unit required");if(t.has(o))throw new Error("ledger: duplicate unit in units array");t.add(o);let i=BigInt(n.value??0),a=BigInt(n.notional??0);if(i<0n||a<0n)throw new Error("ledger: unit value/notional must be non-negative");let u=n.fee===void 0?0n:BigInt(n.fee);if(u<0n)throw new Error("ledger: unit fee must be non-negative");return{unit:o,value:i.toString(),notional:a.toString(),fee:u.toString()}});return r.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),r}function Ps(e,t){let r=e[t];if(r==null||r==="")throw new Error(`ledger: ${t} required`);return Z(r,`ledger: ${t}`)}function Ir(e,t){if(String(t).startsWith("erc20:")){let n=String(t).slice(6).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("ledger: invalid ERC20 accounting unit");let o=Object.entries(e.tokenCaps||e.nftPaymentTokenCaps||{}).find(([a])=>String(a).toLowerCase()===n)?.[1];if(!o)throw new Error("ledger: ERC-20 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 r=t==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:t==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:t==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:t==="usdc"?["maxDailyValueUsdc","maxDailyNotionalUsdc","maxPerTradeUsdc"]:null;if(!r)throw new Error("ledger: unsupported accounting unit");if(t==="usdc"){let n=r.filter(c=>e[c]!==void 0&&e[c]!==null&&e[c]!=="");if(n.length===r.length)return r.map(c=>Ps(e,c));if(n.length>0){let c=r.filter(s=>!n.includes(s));throw new Error(`ledger: ${c[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"),u=P(i,6,"ledger: maxPerTradeUsdc");return[a,a,u]}for(let n of r)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return r.map(n=>BigInt(e[n]))}function ur(e,t){let r=`${e}.lock`,n=ks(16).toString("hex"),o;try{o=U.openSync(r,U.constants.O_CREAT|U.constants.O_EXCL|U.constants.O_WRONLY|(U.constants.O_NOFOLLOW||0),384),U.writeFileSync(o,n),U.fsyncSync(o)}catch(i){throw o!==void 0&&U.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return t()}finally{U.closeSync(o);try{_(r)===n&&U.unlinkSync(r)}catch{}}}function He(e,t,r,n,o){let i=`${e}.continuity`,a={...t,sequence:(t.sequence??0)+1},u=z(a,r);xe(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:u}})+`
5
+ `);let c={version:2,sequence:a.sequence,ledgerMac:u};xe(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:z(c,r)}})+`
6
+ `);let s={version:1,sequence:a.sequence,ledgerMac:u};U.mkdirSync(Ne.dirname(n),{recursive:!0,mode:448}),xe(n,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:z(s,r)}})+`
7
+ `),o&&Ls(o,r)}function yt({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:u=0,fee:c,units:s,policy:l,nowMs:d=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");Je(r,e);let p=_(t);return ur(e,()=>{let m=cr(e,p,d,r,n);if(m.entries.some(h=>String(h.tradeId)===f))throw new Error("ledger: replayed tradeId");let g;if(s!==void 0){let h=gt(s);for(let w of h){let[b,E,S]=Ir(l,w.unit),k=BigInt(w.value),T=BigInt(w.notional);if(T>S)throw new Error("ledger: per-trade cap exceeded");if(Ae(m.entries,"value",w.unit)+k>b||Ae(m.entries,"notional",w.unit)+T>E)throw new Error("ledger: daily cap exceeded")}g={tradeId:f,units:h,state:"reserved",atMs:d}}else{let h=BigInt(a),w=BigInt(u),[b,E,S]=Ir(l,i);if(h<0n||w<0n||w>S)throw new Error("ledger: per-trade cap exceeded");if(Ae(m.entries,"value",i)+h>b||Ae(m.entries,"notional",i)+w>E)throw new Error("ledger: daily cap exceeded");g={tradeId:f,unit:i,value:h.toString(),notional:w.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:d}}return m.entries.push(g),He(e,m,p,r,n),structuredClone(g)})}function Xn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:u=Date.now()}){Je(r,e);let c=_(t);return ur(e,()=>{let s=cr(e,c,u,r,n),l=s.entries.find(g=>String(g.tradeId)===String(o?.tradeId??"")&&g.state==="reserved");if(!l)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(l.units)){if(!Array.isArray(o?.units)||!Array.isArray(l.units))throw new Error("ledger: reservation unavailable");let g=gt(o.units);if(JSON.stringify(g)!==JSON.stringify(l.units))throw new Error("ledger: reservation unavailable");if(a){if(!Array.isArray(a.units))throw new Error("ledger: reserved units no longer match decoded economics");let h=gt(a.units);if(h.length!==l.units.length||h.some((w,b)=>w.unit!==l.units[b].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let w=0;w<h.length;w++)if(BigInt(h[w].value)>BigInt(l.units[w].value)||BigInt(h[w].notional)>BigInt(l.units[w].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let h of l.units){let[w,b,E]=Ir(i,h.unit);if(BigInt(h.notional)>E)throw new Error("ledger: per-trade cap exceeded");if(Ae(s.entries,"value",h.unit)>w||Ae(s.entries,"notional",h.unit)>b)throw new Error("ledger: daily cap exceeded")}return structuredClone(l)}if(l.unit!==o.unit||l.value!==o.value||l.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==l.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(l.value)||BigInt(a.notional)>BigInt(l.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let d=l.unit||"wei",[f,p,m]=Ir(i,d);if(BigInt(l.notional)>m)throw new Error("ledger: per-trade cap exceeded");if(Ae(s.entries,"value",d)>f||Ae(s.entries,"notional",d)>p)throw new Error("ledger: daily cap exceeded");return structuredClone(l)})}function Qn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Je(r,e);let a=_(t);return ur(e,()=>{let u=cr(e,a,i,r,n),c=u.entries.find(s=>String(s.tradeId)===String(o??"")&&s.state==="reserved");if(!c||c.state!=="reserved")throw new Error("ledger: reservation unavailable");return c.state="committed",c.committedAtMs=i,He(e,u,a,r,n),structuredClone(c)})}function Zn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Je(r,e);let a=_(t);return ur(e,()=>{let u=cr(e,a,i,r,n),c=u.entries.findIndex(l=>String(l.tradeId)===String(o??"")&&l.state==="reserved");if(c<0)throw new Error("ledger: reservation unavailable");let[s]=u.entries.splice(c,1);return He(e,u,a,r,n),structuredClone(s)})}function eo({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Je(r,e);let a=_(t);return ur(e,()=>{let u=cr(e,a,i,r,n),c=u.entries.find(l=>String(l.tradeId)===String(o??"")&&l.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");if(Array.isArray(c.units))return c.state="committed",c.committedAtMs=i,c.units=c.units.map(l=>{let d=BigInt(l.fee??0);return{...l,value:"0",notional:d.toString()}}),c.settledAs=c.units.some(l=>BigInt(l.notional)>0n)?"fee-only":"no-fee",He(e,u,a,r,n),structuredClone(c);let s=BigInt(c.fee??0);return s<=0n?(c.state="committed",c.committedAtMs=i,c.value="0",c.notional="0",c.settledAs="no-fee",He(e,u,a,r,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=s.toString(),c.settledAs="fee-only",He(e,u,a,r,n),structuredClone(c))})}function ro(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:J(Os(t))};return ce(e.mac,z(o,_(r)))}function Rs(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function to(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(t.owner).toLowerCase(),action:String(t.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:J(Rs(t))};return ce(e.mac,z(o,_(r)))}import{spawnSync as _s}from"node:child_process";function no(e="oracle-local-signer",t=process.env.USER||process.env.USERNAME||"oracle"){let r,n;if(process.platform==="darwin")r="/usr/bin/security",n=["find-generic-password","-s",e,"-a",t,"-w"];else if(process.platform==="linux")r="secret-tool",n=["lookup","service",e,"account",t];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let o=_s(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}import{Wallet as Et}from"ethers";import{base58 as bt}from"@scure/base";import{ed25519 as co}from"@noble/curves/ed25519.js";import{NETWORK as uo,TEST_NETWORK as lo,WIF as $s,p2wpkh as oo}from"@scure/btc-signer";import{pubECDSA as Fs}from"@scure/btc-signer/utils.js";var Nr=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Ms=e=>{let t=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return null;let r=Buffer.from(t,"base64");return r.toString("base64")===t?r:null},io=e=>{let t=String(e||"").trim();try{let r=Buffer.from(bt.decode(t));return bt.encode(r)===t?r:null}catch{return null}},xt=e=>{if(!(e instanceof Uint8Array))throw new Error("sol: key bytes required");if(e.length!==32&&e.length!==64)throw new Error("sol: expected 32-byte private key material");let t=Buffer.from(e.subarray(0,32));if(e.length===64){let r=Buffer.from(e.subarray(32,64)),n=Buffer.from(co.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},ao=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),pe=(e,t)=>{if(t==="sol")return xt(e);if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)},Ds=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return pe(r,t)};function At(e,t){let r=String(t||"").trim();if(e==="evm")return new Et(r).privateKey;if(e==="btc")for(let i of[uo,lo])try{return Buffer.from($s(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let s=Nr(r.slice(4));if(!s)throw new Error("sol: invalid explicit hex private key");return pe(s,"sol")}if(/^base58:/i.test(r)){let s=io(r.slice(7));if(!ao(s))throw new Error("sol: invalid explicit base58 private key");return xt(s)}if(/^0x/i.test(r)){let s=Nr(r);if(!s)throw new Error("sol: invalid explicit hex private key");return pe(s,"sol")}let i=Nr(r),a=i&&(i.length===32||i.length===64)?pe(i,"sol"):null,u=io(r),c=ao(u);if(a&&c&&!a.equals(c))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(c)return xt(u);if(i)return pe(i,"sol")}let n=Nr(r);if(n)return e==="evm"?new Et(`0x${n.toString("hex")}`).privateKey:pe(n,e);let o=Ms(r);if(o)return pe(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Ds(i,e);let a=i.privateKey??i.secretKey??i.key;if(a)return At(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function so(e,t){if(e==="evm"){let r=new Et(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=pe(t,"btc"),n=Fs(r);return{kind:e,secret:r.toString("hex"),addresses:[oo(n,uo).address,oo(n,lo).address]}}if(e==="sol"){let r=pe(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[bt.encode(co.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function fo(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:so(t.kind||"evm",At(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=so(i,At(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function St(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var le=new It(["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"]),mo=new It(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),kt=new It(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function Gs(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||ne.join(process.env.XDG_STATE_HOME||ne.join(qs.homedir(),".local","state"),"oracle"),r=Us("sha256").update(ne.resolve(e)).digest("hex").slice(0,16);return{vault:ne.join(e,"vault.json"),policy:ne.join(e,"signer-policy.json"),policyKey:ne.join(e,"policy-integrity-key"),policyAnchor:ne.join(t,`signer-policy-${r}.high-water`),ledger:ne.join(e,"signer-ledger.json"),ledgerAnchor:ne.join(t,`signer-ledger-${r}.high-water`),token:ne.join(e,"signer-token"),lock:ne.join(t,`signer-${r}.lock`)}}function Vs(e){try{return _(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=js(32).toString("hex");return xe(e,t+`
8
+ `),t}function Tt(e,t,r){if(!t)throw new Error(`signer: ${e} key is required by policy`);let n=new Set((r||[]).map(o=>String(o).toLowerCase()));if(!t.addresses.some(o=>n.has(String(o).toLowerCase())))throw new Error(`signer: ${e} vault address is not an allowed policy owner`);return!0}function wo(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function j(e,t){return e.surfaces.includes(t)}function ue(e,t){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`signer: invalid ${t}`);return r}function ho(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function Ks(e,t){let r=e?.anvilQuote;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("signer: exact prepared Anvil quote is required");if(!e?.artifact?.anvilQuote||JSON.stringify(e.artifact.anvilQuote)!==JSON.stringify(r))throw new Error("signer: exact prepared Anvil quote artifact mismatch");return Object.freeze(t==="buy"?{totalCostRaw:BigInt(r.totalCostRaw).toString(),baseCostRaw:BigInt(r.baseCostRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString(),available:r.available===!0}:{netPayoutRaw:BigInt(r.netPayoutRaw).toString(),grossPayoutRaw:BigInt(r.grossPayoutRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString()})}function Ys(e,t,r){if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("signer: exact prepared Anvil quote confirmation required");let n=e.artifact,o=t==="buy"?[r.totalCostRaw,e.maxPaymentTokenAmountRaw,n?.maxPaymentTokenAmountRaw,e.exactQuoteTotalCostRaw,n?.exactQuoteTotalCostRaw,e.preconditions?.confirmedTotalCostRaw]:[r.netPayoutRaw,e.minPayoutRaw,n?.minPayoutRaw,e.exactQuoteNetPayoutRaw,n?.exactQuoteNetPayoutRaw,e.preconditions?.confirmedNetPayoutRaw],i;try{i=BigInt(o[0]);for(let s of o.slice(1))if(BigInt(s)!==i)throw new Error("mismatch")}catch{throw new Error(`signer: exact Anvil ${t} settlement limit mismatch`)}let a=n?.transactions;if(!Array.isArray(a)||a.length!==1)throw new Error("signer: exact Anvil action transaction required");let u=t==="buy"?"buySpecificNFT":"sellNFT",c;try{if(c=le.decodeFunctionData(u,a[0].data),le.encodeFunctionData(u,[c[0],c[1]]).toLowerCase()!==String(a[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${t} calldata required`)}if(BigInt(c[0])!==BigInt(e.tokenId)||BigInt(c[1])!==i)throw new Error(`signer: exact Anvil ${t} calldata limit mismatch`);return i}async function me(e,t,r,n,o,i=[]){let a=await e.send("eth_call",[{to:t,data:r.encodeFunctionData(n,i)},o]);return r.decodeFunctionResult(n,a)[0]}async function Xs(e,t,r,{nowMs:n=Date.now(),signerAddress:o}={}){if(t?.surface!=="evm-nft"||String(t?.provider).toLowerCase()!=="anvil-nft")return null;if(!e||typeof e.send!="function")throw new Error("signer: trusted RPC cannot attest Anvil market");let i=ue(t.destination,"Anvil market"),a=ue(t.contract,"Anvil collection"),u=ue(t.paymentToken,"Anvil payment token"),c=BigInt(t.nativeSwapFeeWei),s=Number(t.paymentTokenDecimals),l=ue(o,"Anvil signer identity"),d=ue(t.owner,"Anvil envelope owner");if(l!==d)throw new Error("signer: Anvil signer identity mismatch");let f=BigInt(t.tokenId);if(f<0n)throw new Error("signer: invalid Anvil tokenId");let p=String(t.nftAction||"").toLowerCase();if(p!=="buy"&&p!=="sell")throw new Error("signer: unsupported Anvil NFT action");let m=Ks(t,p),g=Ys(t,p,m),h=t.anvilAttestation;if(!h||typeof h!="object"||Number(h.snapshotExpiresAtMs)<=Number(n))throw new Error("signer: fresh provider Anvil attestation required");let w=String(ho(r.anvilRuntimeCodeHashes,i)||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(w)||w!==String(h.runtimeCodeHash||"").toLowerCase())throw new Error("signer: Anvil runtime is not reviewed by policy");let b=ho(r.nftPaymentTokenCaps,u);if(!b||Number(b.decimals)!==s)throw new Error("signer: Anvil payment token decimals are not reviewed by policy");let E=String(await e.send("eth_chainId",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(E)||BigInt(E)!==4663n)throw new Error("signer: trusted RPC Anvil chain mismatch");let S=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(S))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let k=BigInt(S),T=await e.send("eth_getBlockByNumber",[S,!1]),A=String(T?.hash||"").toLowerCase();if(String(T?.number||"").toLowerCase()!==S||!/^0x[0-9a-f]{64}$/.test(A))throw new Error("signer: trusted RPC returned an invalid Anvil block attestation");let B=Object.freeze({blockHash:A,requireCanonical:!0}),F=String(await e.send("eth_getCode",[i,B])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(F)||F==="0x")throw new Error("signer: Anvil market runtime is empty");let G=Js(F).toLowerCase();if(G!==w)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[we,Pr,Rr]=await Promise.all([me(e,i,le,"collection",B),me(e,i,le,"token",B),me(e,i,le,"robinhoodSwapFeeWei",B)]),he=ue(we,"live Anvil collection"),Ce=ue(Pr,"live Anvil payment token"),ze=BigInt(Rr).toString();if(he!==a)throw new Error("signer: live Anvil collection mismatch");if(Ce!==u)throw new Error("signer: live Anvil payment token mismatch");if(ze!==c.toString())throw new Error("signer: live Anvil native swap fee mismatch");let Se=Number(await me(e,Ce,mo,"decimals",B));if(!Number.isSafeInteger(Se)||Se!==s)throw new Error("signer: live Anvil payment token decimals mismatch");let Ge=ue(await me(e,he,kt,"ownerOf",B,[f]),"live Anvil token owner"),Ve=null,de=null,ve=null,y=null,x;if(p==="buy"){let[I,L,H]=await Promise.all([me(e,i,le,"inventory",B,[f]),me(e,Ce,mo,"allowance",B,[l,i]),e.send("eth_call",[{to:i,data:le.encodeFunctionData("quoteSpecificBuy",[f])},B])]);Ve=!!I,de=BigInt(L).toString();let $=le.decodeFunctionResult("quoteSpecificBuy",H);if(x=Object.freeze({totalCostRaw:BigInt($[0]).toString(),baseCostRaw:BigInt($[1]).toString(),feeRaw:BigInt($[2]).toString(),protocolFeeRaw:BigInt($[3]).toString(),available:!!$[4]}),JSON.stringify(x)!==JSON.stringify(m))throw new Error("signer: exact Anvil buy quote changed after preparation");if(Ge!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!Ve)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt(de)!==BigInt(t.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(de)<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[I,L,H]=await Promise.all([me(e,he,kt,"getApproved",B,[f]),me(e,he,kt,"isApprovedForAll",B,[l,i]),e.send("eth_call",[{to:i,data:le.encodeFunctionData("quoteSellNFT")},B])]);ve=ue(I,"live Anvil token approval"),y=!!L;let $=le.decodeFunctionResult("quoteSellNFT",H);if(x=Object.freeze({netPayoutRaw:BigInt($[0]).toString(),grossPayoutRaw:BigInt($[1]).toString(),feeRaw:BigInt($[2]).toString(),protocolFeeRaw:BigInt($[3]).toString()}),JSON.stringify(x)!==JSON.stringify(m))throw new Error("signer: exact Anvil sell quote changed after preparation");if(Ge!==l)throw new Error("signer: exact Anvil token owner does not match signer");if(ve!==i&&!y)throw new Error("signer: live Anvil NFT approval is insufficient");if(ve!==ue(t.preconditions?.approvedAddress,"prepared Anvil token approval")||y!==!!t.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:he,paymentToken:Ce,paymentTokenDecimals:Se,nativeSwapFeeWei:ze,signerAddress:l,nftAction:p,tokenId:f.toString(),tokenOwner:Ge,inventoryMember:Ve,allowanceRaw:de,approvedAddress:ve,approvedForAll:y,quote:x,blockNumber:k.toString(),blockHash:A,runtimeCodeHash:G,verifiedAtMs:Number(n)})}function go(e,t,r="execution"){if(!e||!t)throw new Error("signer: complete Anvil revalidation evidence required");for(let n of["runtimeCodeHash","market","collection","paymentToken","paymentTokenDecimals","nativeSwapFeeWei","signerAddress","nftAction","tokenId","tokenOwner","inventoryMember","allowanceRaw","approvedAddress","approvedForAll"])if(String(t[n]).toLowerCase()!==String(e[n]).toLowerCase())throw new Error(`signer: Anvil ${n} changed after simulation at ${r}`);if(JSON.stringify(t.quote)!==JSON.stringify(e.quote))throw new Error(`signer: Anvil quote changed after simulation at ${r}`);return!0}function Qs(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:a}={}){let u=Hs(new URL("./anvil-attestation-worker.mjs",import.meta.url)),c={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},s;try{s=Ws(process.execPath,[u],{input:JSON.stringify({rpcUrl:e,chainId:t,envelope:r,policy:c,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 l;try{l=JSON.parse(s)}catch{throw new Error("signer: invalid Anvil reservation attestation result")}if(!l||l.source!=="local-signer-trusted-rpc"||!/^0x[0-9a-f]{64}$/.test(String(l.blockHash||"")))throw new Error("signer: invalid Anvil reservation attestation result");return Object.freeze(l)}function Zs(e,t,r,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"}`],u=(s,l)=>{if(a.push(`LEG ${l} chain=${s.chainId??"n/a"} from=${s.from??"n/a"} to=${s.to??"n/a"}`),a.push(`LEG ${l} calldata=${String(s.data||"0x")} value=${s.value??"n/a"}`),a.push(`LEG ${l} gas=${s.gasLimit??"n/a"} maxFeePerGas=${s.maxFeePerGas??s.gasPrice??"n/a"} maxPriorityFeePerGas=${s.maxPriorityFeePerGas??"n/a"}`),a.push(`LEG ${l} l1FeeWei=${s.l1FeeWei??"n/a"} operatorFeeWei=${s.operatorFeeWei??"n/a"} nonce=${s.nonce??"n/a"} type=${s.type??"n/a"}`),oe(String(s.data||"0x")))try{let d=Qe(String(s.data||"0x"));a.push(`LEG ${l} APPROVAL token=${d.token||s.to||"n/a"} spender=${d.spender} amount=${d.amount}`)}catch{a.push(`LEG ${l} APPROVAL spender=undecodable amount=undecodable`)}},c=String(i.data||"0x");if(oe(c))try{let s=Qe(c);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,l)=>u(s,l))),o?.surface==="btc"){let s=qr(o,r);a.push(`amount=${s.value} sats fee=${s.fee} sats outputs=${s.outputs.join(",")}`)}if(o?.surface==="sol"){let s=zr(o,r);a.push(`amount=${s.value} lamports fee=${s.fee} lamports programs=${s.programs.join(",")}`)}if(o?.surface==="hl"){let s=ye(o,r);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=Ee(o,r);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=be(o,r);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 Nt(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 no(e,r){return Buffer.concat([Buffer.from([1]),Buffer.from(r),Buffer.from(e)]).toString("base64")}async function io(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 Nt(n,{jsonrpc:"1.0",id:"oracle",method:r,params:t})}async function Rs(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 u=await a.json();if(u?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(u?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await io(e,"gettxout",[r,Number(t),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function _s(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 $s(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?(pn(t),r.signTypedData(t.typedData.domain,t.typedData.types,t.typedData.message)):mn({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"),u=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:u.r,s:u.s,v:u.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(t),status:1}}}}function Fs(e){return{simulate:async(r,t)=>(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 nt(r,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(r,t,n)=>{let o=Ee(n,e()),i=nt(t,r),a=gn(i),u=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),c=await u.json().catch(()=>({}));if(!u.ok||Number(c?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(c?.tx_hash||c?.txHash||"lighter"),status:1}}}}function Ms(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),u=Gt(i),{keccak256:c}=await import("ethers"),s=Vr({message:n.message,side:n.side,signature:t,orderType:n.orderType||"GTC",apiKey:u.key}),d=JSON.stringify(s),l=Jr({creds:u,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:c(t),status:1}}}}function qs(e,r){let t=wr(r);return{simulate:async n=>{let o=e(),i=gr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let a=0;a<i.inputsLength;a++){let u=i.getInput(a),c=Buffer.from(u.txid||[]).toString("hex");await Rs(o,c,u.index)}return!0},sign:n=>{let o=gr.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=gr.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let u;try{let s=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(u=(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;u=await io(o,"sendrawtransaction",[a.hex])}if(u&&String(u).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let s=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${s}/tx/${a.id}/status`);d.ok&&(c=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:c}}}}function Ds(e,r){let t=wr(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"),u=no(a,new Uint8Array(64)),c=await Nt(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[u,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return _s(c)},sign:n=>no(Buffer.from(n.messageBase64,"base64"),ks.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 Nt(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await Nt(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:a,status:0};let s=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:a,status:s?1:null}}}}function Us(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 js(e,r,t,n,{submitPrivate:o}={}){if((await e.getNetwork()).chainId!==BigInt(t.chainId))throw new Error("signer: RPC chain mismatch");let a={native:(await e.getBalance(t.from)).toString()},u=n&&n.privateRelay;if(u&&typeof o=="function"){let l=u==="require"||u?.mode==="require";try{let f=await o(r,{chainId:Number(t.chainId),requirePrivate:l,allowPublicFallback:!l});if(!f.fellBack&&f.hash){let p=await e.waitForTransaction(f.hash),m={native:(await e.getBalance(t.from)).toString()};return{hash:f.hash,status:p?.status??null,verifiedBefore:a,verifiedAfter:m,submission:{path:"private",mode:f.mode,endpoint:f.endpoint}}}}catch(f){if(l)throw f}}let c=await e.broadcastTransaction(r),s=await c.wait(),d={native:(await e.getBalance(t.from)).toString()};return{hash:s?.hash??c.hash,status:s?.status??null,verifiedBefore:a,verifiedAfter:d,submission:{path:"public"}}}async function ao({configDir:e,passphraseFile:r,credentialService:t,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:u,Wallet:c}=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=Ts(e),d=()=>Object.freeze($n(s.policy,s.policyKey,{sequenceAnchorFile:s.policyAnchor})),l=d();if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let f=["surfaces","actions","destinations","owners"];l.surfaces.some(y=>String(y).startsWith("evm"))&&f.push("chains","spenders");for(let y of f)if(!Array.isArray(l[y])||l[y].length===0)throw new Error(`signer: ${y} allowlist is empty`);if(l.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge"||y==="evm-nft")){for(let y of["providers"])if(!Array.isArray(l[y])||l[y].length===0)throw new Error(`signer: ${y} allowlist is empty`)}if(l.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(y=>String(y).startsWith("evm"))&&(!Array.isArray(l.selectors)||l.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(l.surfaces.includes("sol")&&(!Array.isArray(l.programs)||l.programs.length===0))throw new Error("signer: programs allowlist is empty");if(W(l,"poly")&&(Gt(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(W(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(W(l,"hl")){let y=Array.isArray(l.coins)?l.coins.map(String):[],x=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(y.filter(C=>C!=="*"&&C!=="#*").length&&!y.includes("*")&&x.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let p=t?Wn(t):_(r),m=Pn(s.vault),g=Cn(m,p),w;try{w=Xn(g,m.meta)}finally{g.fill(0)}(eo(l)||W(l,"hl")||W(l,"poly"))&&Er("evm",w.evm,l.owners),W(l,"btc")&&Er("btc",w.btc,l.owners),W(l,"sol")&&Er("sol",w.sol,l.owners);let h=Array.isArray(l.chains)?l.chains.filter(y=>Number.isInteger(Number(y))&&String(y).trim()!==""):[],b=eo(l);if(b&&(h.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(W(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(W(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=b?new u(l.rpcUrl,Number(h[0])):null,A=w.evm&&(b||W(l,"hl")||W(l,"poly"))?E?new c(w.evm.secret).connect(E):new c(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=>A.signTransaction(y),broadcast:(y,x,T)=>js(E,y,x,T,{submitPrivate:Rn})}:null,k=E?async y=>Ws(E,y):void 0,S=new Map,P=y=>y?.surface==="evm-nft"&&String(y?.provider).toLowerCase()==="anvil-nft",F=async(y,x=d(),T="execution")=>{if(!P(y))return null;let C=await Cs(E,y,x,{nowMs:Date.now(),signerAddress:A.address}),H=S.get(J(y));return H&&ro(H,C,T),C},V={...I?{evm:I,"evm-swap":I,"evm-bridge":I,"evm-nft":I}:{},...w.btc?{btc:qs(d,w.btc)}:{},...w.sol?{sol:Ds(d,w.sol)}:{},...A&&W(l,"hl")?{hl:$s(d,A)}:{},...A&&W(l,"poly")?{poly:Ms(d,A)}:{},...W(l,"lighter")?{lighter:Fs(d)}:{}};Us(V,n);let me=dn({...V,...n}),Ct=new Set(Object.keys(V)),Pt=new Set(Object.keys(n||{})),he=l.surfaces.filter(y=>!Ct.has(y)&&!Pt.has(y));if(he.length)throw new Error(`signer: ${he.join(",")} require local keys or injected surface transports`);let Ne=Date.now(),We=Ne+a,Se=!1,He=()=>Se?!1:Qn.existsSync(s.lock)?(Se=!0,!1):Qn.existsSync(s.vault)&&Date.now()<We,Je=()=>(Se=!0,be(s.lock,`disarmed ${new Date().toISOString()}
13
- `),!0),le=Ln({host:o,port:i,token:Ns(s.token),policy:l,readPolicy:d,isArmed:He,disarm:Je,sessionExpiresAtMs:We,nowMs:Date.now,simulate:async(y,x)=>(await F(x,d(),"before simulation"),wt(x,me).simulate(y,x)),estimateNetworkFees:k,sign:async(y,x)=>(await F(x,d(),"before signing"),wt(x,me).sign(y,x)),verifySigned:(y,x,T)=>vn(T?.surface||"evm",y,x,T),broadcast:async(y,x,T)=>(await F(T,d(),"before broadcast"),wt(T,me).broadcast(y,x,T)),confirmArtifact:async(y,x,T)=>{let C=await F(y,T),H=await Js(y,x,T,C);return H===!0&&C&&S.set(x,C),H},decodeEconomics:(y,x)=>Zt(y,x),reserveLedger:(y,x)=>{let T=y?.version===1&&y?.surface?y:null,C=T?.artifact||y;if(P(T)){let ze=J(T),Oe=S.get(ze);if(!Oe||Date.now()-Number(Oe.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let Ve=Ps(x.rpcUrl,C.chainId,T,x,{nowMs:Date.now(),signerAddress:A.address});ro(Oe,Ve,"before reservation"),S.set(ze,Ve)}let H=T?.tradeId||C?.tradeId;if(!H)throw new Error("ledger: executable artifact requires a tradeId");let $;if(T)$=Zt(T,x);else{if(C?.value===void 0)throw new Error("ledger: executable artifact value required");let ze=BigInt(C.value),Oe=BigInt(C.gasLimit??0),Ve=BigInt(C.maxFeePerGas??C.gasPrice??0);if(Oe<=0n||Ve<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let xr=Oe*Ve+BigInt(C.l1FeeWei??0)+BigInt(C.operatorFeeWei??0);$={unit:"wei",value:ze.toString(),notional:(ze+xr).toString(),fee:xr.toString()}}if(Array.isArray($.units))return dr({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:H,units:$.units,policy:x});if($.value===void 0||$.notional===void 0)throw new Error("ledger: decoded value and notional required");return dr({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:H,...$,policy:x})},commitLedger:y=>Mn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),releaseLedger:y=>qn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),settleFailedLedger:y=>Dn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),validateReservation:(y,x,T)=>Fn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,reservation:y,policy:x,economics:T}),verifyFeeWaiver:(y,x)=>jn(y,x,s.policyKey),verifyTriggerAttestation:(y,x,T)=>Un(y,x,s.policyKey,T),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),Ae=setTimeout(()=>le.close(),a);return Ae.unref(),le.on("close",()=>{clearTimeout(Ae)}),le.listen(i,o),le}var Ot="0x420000000000000000000000000000000000000F";function oo(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 Ws(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 u=await e.call({to:Ot,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",u)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await Hs(e,o,r.gasLimit)}}async function Hs(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:Ot,data:r.encodeFunctionData("getOperatorFee",[n])});return r.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!oo(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:Ot,data:r.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:Ot,data:r.encodeFunctionData("operatorFeeConstant")}),a=BigInt(r.decodeFunctionResult("operatorFeeScalar",o)[0]),u=BigInt(r.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+u).toString()}catch(o){if(!oo(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function Js(e,r,t,n=null){return process.stdin.isTTY?(process.stderr.write(Bs(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 so=`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.`,Lt=(e,r,t)=>{let n=e.indexOf(r);return n>=0?e[n+1]:t};async function Vs(e=[],r={}){if(e.includes("--help"))return(r.out||process.stdout).write(so+`
15
- `),0;let t=Lt(e,"--passphrase-file"),n=await ao({configDir:zs.join(r.configDir||ct(),"signer"),passphraseFile:t,credentialService:Lt(e,"--credential-service"),port:Number(Lt(e,"--port",9462)),sessionMs:Number(Lt(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 Td={name:"signer",summary:"run the short-lived loopback signer",usage:so,run:e=>Vs(e.argv||[])};export{Td as default,Vs as run};
12
+ Type digest ${t}: `}async function Cr(e,t){let r=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),n=await r.text();if(!r.ok)throw new Error(`rpc: HTTP ${r.status}`);let o=JSON.parse(n||"{}");if(o.error)throw new Error(`rpc: ${o.error.message||"request failed"}`);return o.result}function yo(e,t){return Buffer.concat([Buffer.from([1]),Buffer.from(t),Buffer.from(e)]).toString("base64")}async function bo(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation and broadcast");return Cr(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function ec(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let a=await fetch(`${o}/tx/${t}/outspend/${r}`);if(a.ok){let u=await a.json();if(u?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(u?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await bo(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function rc(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 tc(e,t){return{simulate:async(r,n)=>(ye(n,e()),!0),sign:async(r,n)=>{ye(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return r?.typedData?(Nn(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Cn({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{ye(o,e());let{Signature:i,keccak256:a}=await import("ethers"),u=i.from(r);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:u.r,s:u.s,v:u.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(r),status:1}}}}function nc(e){return{simulate:async(t,r)=>(be(r,e()),!0),sign:async(t,r)=>{be(r,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(t,r);return ar(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=be(n,e()),i=ar(r,t),a=Pn(i),u=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),c=await u.json().catch(()=>({}));if(!u.ok||Number(c?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(c?.tx_hash||c?.txHash||"lighter"),status:1}}}}function oc(e,t){return{simulate:async(r,n)=>(Te(n,e()),!0),sign:async(r,n)=>{Te(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: order wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: order wallet must match envelope owner");let a=r.domain||r.typedData.domain,u=r.types||r.typedData.types,c=r.message||r.typedData.message;return t.signTypedData(a,u,c)},broadcast:async(r,n,o)=>{let i=Te(o,e()),{keccak256:a}=await import("ethers"),u=n.message||n.typedData.message,c=i.kind==="cow"?{sellToken:u.sellToken,buyToken:u.buyToken,receiver:u.receiver,sellAmount:u.sellAmount,buyAmount:u.buyAmount,validTo:u.validTo,appData:u.appData,feeAmount:u.feeAmount,kind:u.kind,partiallyFillable:u.partiallyFillable,sellTokenBalance:u.sellTokenBalance,buyTokenBalance:u.buyTokenBalance,from:o.owner,signature:r,signingScheme:"eip712",quoteId:n.quoteId??void 0}:{orderHash:i.digest,signature:r,data:u},s=await fetch(i.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(c)}),l=await s.json().catch(()=>({}));if(!s.ok||l?.error||l?.success===!1)throw new Error(i.kind==="cow"?"signer: CoW orderbook rejected the order":"signer: 1inch orderbook rejected the order");return{hash:a(r),status:1,orderHash:i.digest,uid:typeof l=="string"?l:l?.uid||null}}}}function ic(e,t){return{simulate:async(r,n)=>(Ee(n,e()),!0),sign:async(r,n)=>{Ee(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),a=Ee(o,i),u=Yr(i),{keccak256:c}=await import("ethers"),s=rn({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:u.key}),l=JSON.stringify(s),d=Zt({creds:u,address:o.owner,method:"POST",path:"/order",body:l}),f=await fetch(a.submitTo,{method:"POST",headers:d,body:l}),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:c(r),status:1}}}}function ac(e,t){let r=St(t);return{simulate:async n=>{let o=e(),i=vt.fromPSBT(Buffer.from(n.psbt,"base64"));for(let a=0;a<i.inputsLength;a++){let u=i.getInput(a),c=Buffer.from(u.txid||[]).toString("hex");await ec(o,c,u.index)}return!0},sign:n=>{let o=vt.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(r),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let a=vt.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let u;try{let s=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(u=(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;u=await bo(o,"sendrawtransaction",[a.hex])}if(u&&String(u).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let s=i.endsWith("/tx")?i.slice(0,-3):i,l=await fetch(`${s}/tx/${a.id}/status`);l.ok&&(c=(await l.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:c}}}}function sc(e,t){let r=St(t);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let a=Buffer.from(n.messageBase64,"base64"),u=yo(a,new Uint8Array(64)),c=await Cr(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[u,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return rc(c)},sign:n=>yo(Buffer.from(n.messageBase64,"base64"),zs.sign(Buffer.from(n.messageBase64,"base64"),r)),broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let a=await Cr(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await Cr(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:a,status:0};let s=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:a,status:s?1:null}}}}function cc(e,t={}){for(let r of Object.keys(t||{}))if(Object.prototype.hasOwnProperty.call(e,r))throw new Error(`signer: cannot replace built-in ${r} transport`)}async function uc(e,t,r,n,{submitPrivate:o}={}){if((await e.getNetwork()).chainId!==BigInt(r.chainId))throw new Error("signer: RPC chain mismatch");let a={native:(await e.getBalance(r.from)).toString()},u=n&&n.privateRelay;if(u&&typeof o=="function"){let d=u==="require"||u?.mode==="require";try{let f=await o(t,{chainId:Number(r.chainId),requirePrivate:d,allowPublicFallback:!d});if(!f.fellBack&&f.hash){let p=await e.waitForTransaction(f.hash),m={native:(await e.getBalance(r.from)).toString()};return{hash:f.hash,status:p?.status??null,verifiedBefore:a,verifiedAfter:m,submission:{path:"private",mode:f.mode,endpoint:f.endpoint}}}}catch(f){if(d)throw f}}let c=await e.broadcastTransaction(t),s=await c.wait(),l={native:(await e.getBalance(r.from)).toString()};return{hash:s?.hash??c.hash,status:s?.status??null,verifiedBefore:a,verifiedAfter:l,submission:{path:"public"}}}async function xo({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:u,Wallet:c}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(a<1e3||a>12e4)throw new Error("signer: session must be at most 120 seconds");let s=Gs(e),l=()=>Object.freeze(Yn(s.policy,s.policyKey,{sequenceAnchorFile:s.policyAnchor})),d=l();if(!["exact-human","auto-within-rails"].includes(d.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(d.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"];d.surfaces.some(y=>String(y).startsWith("evm"))&&f.push("chains","spenders");for(let y of f)if(!Array.isArray(d[y])||d[y].length===0)throw new Error(`signer: ${y} allowlist is empty`);if(d.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge"||y==="evm-nft"||y==="evm-order")){for(let y of["providers"])if(!Array.isArray(d[y])||d[y].length===0)throw new Error(`signer: ${y} allowlist is empty`)}if(d.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge"||y==="evm-order")&&(!Array.isArray(d.tokens)||d.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(d.surfaces.some(y=>String(y).startsWith("evm")&&y!=="evm-order")&&(!Array.isArray(d.selectors)||d.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(d.surfaces.includes("sol")&&(!Array.isArray(d.programs)||d.programs.length===0))throw new Error("signer: programs allowlist is empty");if(j(d,"poly")&&(Yr(d),!Array.isArray(d.polyTokens)||d.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(j(d,"lighter")&&(!Array.isArray(d.lighterMarkets)||d.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(j(d,"hl")){let y=Array.isArray(d.coins)?d.coins.map(String):[],x=Array.isArray(d.hlMarkets)?d.hlMarkets:[];if(y.filter(L=>L!=="*"&&L!=="#*").length&&!y.includes("*")&&x.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let p=r?no(r):_(t),m=zn(s.vault),g=Jn(m,p),h;try{h=fo(g,m.meta)}finally{g.fill(0)}(wo(d)||j(d,"hl")||j(d,"poly"))&&Tt("evm",h.evm,d.owners),j(d,"btc")&&Tt("btc",h.btc,d.owners),j(d,"sol")&&Tt("sol",h.sol,d.owners);let w=Array.isArray(d.chains)?d.chains.filter(y=>Number.isInteger(Number(y))&&String(y).trim()!==""):[],b=wo(d);if(b&&(w.length!==1||!d.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(j(d,"btc")&&!(d.btcRpcUrl||d.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(j(d,"sol")&&!(d.solRpcUrl||d.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=b?new u(d.rpcUrl,Number(w[0])):null,S=h.evm&&(b||j(d,"hl")||j(d,"poly"))?E?new c(h.evm.secret).connect(E):new c(h.evm.secret):null,k=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:(y,x,I)=>uc(E,y,x,I,{submitPrivate:Vn})}:null,T=E?async y=>lc(E,y):void 0,A=new Map,B=y=>y?.surface==="evm-nft"&&String(y?.provider).toLowerCase()==="anvil-nft",F=async(y,x=l(),I="execution")=>{if(!B(y))return null;let L=await Xs(E,y,x,{nowMs:Date.now(),signerAddress:S.address}),H=A.get(J(y));return H&&go(H,L,I),L},G={...k?{evm:k,"evm-swap":k,"evm-bridge":k,"evm-nft":k}:{},...S&&j(d,"evm-order")?{"evm-order":oc(l,S)}:{},...h.btc?{btc:ac(l,h.btc)}:{},...h.sol?{sol:sc(l,h.sol)}:{},...S&&j(d,"hl")?{hl:tc(l,S)}:{},...S&&j(d,"poly")?{poly:ic(l,S)}:{},...j(d,"lighter")?{lighter:nc(l)}:{}};cc(G,n);let we=In({...G,...n}),Pr=new Set(Object.keys(G)),Rr=new Set(Object.keys(n||{})),he=d.surfaces.filter(y=>!Pr.has(y)&&!Rr.has(y));if(he.length)throw new Error(`signer: ${he.join(",")} require local keys or injected surface transports`);let Ce=Date.now(),ze=Ce+a,Se=!1,Ge=()=>Se?!1:po.existsSync(s.lock)?(Se=!0,!1):po.existsSync(s.vault)&&Date.now()<ze,Ve=()=>(Se=!0,xe(s.lock,`disarmed ${new Date().toISOString()}
13
+ `),!0),de=Hn({host:o,port:i,token:Vs(s.token),policy:d,readPolicy:l,isArmed:Ge,disarm:Ve,sessionExpiresAtMs:ze,nowMs:Date.now,simulate:async(y,x)=>(await F(x,l(),"before simulation"),yr(x,we).simulate(y,x)),estimateNetworkFees:T,sign:async(y,x)=>(await F(x,l(),"before signing"),yr(x,we).sign(y,x)),verifySigned:(y,x,I)=>Mn(I?.surface||"evm",y,x,I),broadcast:async(y,x,I)=>(await F(I,l(),"before broadcast"),yr(I,we).broadcast(y,x,I)),confirmArtifact:async(y,x,I)=>{let L=await F(y,I),H=await fc(y,x,I,L);return H===!0&&L&&A.set(x,L),H},decodeEconomics:(y,x)=>ot(y,x),reserveLedger:(y,x)=>{let I=y?.version===1&&y?.surface?y:null,L=I?.artifact||y;if(B(I)){let Ke=J(I),Le=A.get(Ke);if(!Le||Date.now()-Number(Le.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let Ye=Qs(x.rpcUrl,L.chainId,I,x,{nowMs:Date.now(),signerAddress:S.address});go(Le,Ye,"before reservation"),A.set(Ke,Ye)}let H=I?.tradeId||L?.tradeId;if(!H)throw new Error("ledger: executable artifact requires a tradeId");let $;if(I)$=ot(I,x);else{if(L?.value===void 0)throw new Error("ledger: executable artifact value required");let Ke=BigInt(L.value),Le=BigInt(L.gasLimit??0),Ye=BigInt(L.maxFeePerGas??L.gasPrice??0);if(Le<=0n||Ye<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let Ot=Le*Ye+BigInt(L.l1FeeWei??0)+BigInt(L.operatorFeeWei??0);$={unit:"wei",value:Ke.toString(),notional:(Ke+Ot).toString(),fee:Ot.toString()}}if(Array.isArray($.units))return yt({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:H,units:$.units,policy:x});if($.value===void 0||$.notional===void 0)throw new Error("ledger: decoded value and notional required");return yt({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:H,...$,policy:x})},commitLedger:y=>Qn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),releaseLedger:y=>Zn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),settleFailedLedger:y=>eo({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),validateReservation:(y,x,I)=>Xn({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,reservation:y,policy:x,economics:I}),verifyFeeWaiver:(y,x)=>to(y,x,s.policyKey),verifyTriggerAttestation:(y,x,I)=>ro(y,x,s.policyKey,I),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),ve=setTimeout(()=>de.close(),a);return ve.unref(),de.on("close",()=>{clearTimeout(ve)}),de.listen(i,o),de}var Lr="0x420000000000000000000000000000000000000F";function Eo(e){let t=e?.code;if(t==="CALL_EXCEPTION"||t==="BAD_DATA")return!0;let r=String(e?.shortMessage||e?.message||e);return/network|timeout|ECONN|ENOTFOUND|EAI_AGAIN|server error|fetch failed|socket/i.test(r)?!1:/execution reverted|revert|invalid opcode|function selector|could not decode/i.test(r)}async function lc(e,t){if(!ie(t?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:r,Transaction:n}=await import("ethers"),o=new r(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce??0,type:t.type,accessList:t.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let a;try{let u=await e.call({to:Lr,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",u)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await dc(e,o,t.gasLimit)}}async function dc(e,t,r){let n;try{n=BigInt(r)}catch{throw new Error("policy: rollup fee estimate required")}if(n<0n)throw new Error("policy: rollup fee estimate required");try{let o=await e.call({to:Lr,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Eo(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:Lr,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:Lr,data:t.encodeFunctionData("operatorFeeConstant")}),a=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),u=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+u).toString()}catch(o){if(!Eo(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function fc(e,t,r,n=null){return process.stdin.isTTY?(process.stderr.write(Zs(e,t,r,n)),process.stdin.resume(),new Promise(o=>{let i=a=>{process.stdin.off("data",i),process.stdin.pause(),o(String(a).trim()===t)};process.stdin.once("data",i)})):!1}var Ao=`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.`,Br=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function mc(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(Ao+`
15
+ `),0;let r=Br(e,"--passphrase-file"),n=await xo({configDir:pc.join(t.configDir||dr(),"signer"),passphraseFile:r,credentialService:Br(e,"--credential-service"),port:Number(Br(e,"--port",9462)),sessionMs:Number(Br(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
16
+ `),await new Promise(o=>n.on("close",o)),0}var If={name:"signer",summary:"run the short-lived loopback signer",usage:Ao,run:e=>mc(e.argv||[])};export{If as default,mc as run};