@oracle-agent/oracle 0.25.2 → 0.25.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -1
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +53 -53
- package/dist/bin/oracle-data-mcp.mjs +12 -12
- package/dist/bin/oracle-public-server.mjs +15 -15
- package/dist/bin/oracle-route.mjs +14 -14
- package/dist/cli/commands/chat.mjs +96 -96
- package/dist/cli/commands/doctor.mjs +3 -3
- package/dist/cli/commands/eval.mjs +414 -85
- package/dist/cli/commands/farm.mjs +21 -21
- package/dist/cli/commands/model.mjs +101 -101
- package/dist/cli/commands/receipt.mjs +2 -2
- package/dist/cli/commands/sign.mjs +9 -9
- package/dist/cli/commands/signer.mjs +12 -12
- package/dist/cli/commands/strategy.mjs +11 -11
- package/dist/cli/commands/swap.mjs +10 -10
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +51 -51
- package/dist/data/providers/universal-evm-nft-transfer.mjs +1 -0
- package/dist/data/providers/universal-ordinals-transfer.mjs +1 -0
- package/dist/data/providers/universal-solana-nft-transfer.mjs +1 -0
- package/dist/index.mjs +53 -53
- package/dist/local-signer/index.mjs +3 -3
- package/dist/nft/index.mjs +1 -1
- package/dist/nft/universal-mint-router.mjs +47 -0
- package/dist/nft/universal-nft-lifecycle.mjs +1 -0
- package/dist/prepare-envelope.mjs +1 -1
- package/dist/router/index.mjs +9 -9
- package/dist/router/prepare-bridge.mjs +18 -18
- package/dist/strategy/index.mjs +11 -11
- package/package.json +6 -1
- package/public/oracle-splash/downloads/index.html +4 -4
- package/public/oracle-splash/index.html +1 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import ca from"node:path";import De from"node:fs";import qn from"node:os";import me from"node:path";import{fileURLToPath as Dn}from"node:url";var Un=me.dirname(Dn(import.meta.url)),ma=me.resolve(Un,"../..");function et(){return process.env.ORACLE_FAKE_HOME||qn.homedir()}function jn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function Ue(){return jn()?process.env.ORACLE_CONFIG_DIR||me.join(et(),".config","oracle"):me.join(et(),".config","oracle")}function Wn(){return me.join(Ue(),"desk.json")}function Hn(){return me.join(Ue(),"env")}function pe({force:e=!1}={}){if(pe._done&&!e)return pe._result||null;pe._done=!0;let t={},r=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=Hn();if(De.existsSync(o))for(let i of De.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let a=s[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(s[1],a)}}catch{}try{let o=Wn();if(De.existsSync(o)){let i=JSON.parse(De.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),pe._result=Object.keys(t).length?t:null,pe._result}try{pe()}catch{}import kn from"node:fs";import z from"node:path";import Hs from"node:os";import{createHash as Js,randomBytes as Gs}from"node:crypto";import{Transaction as Gr}from"@scure/btc-signer";import{ed25519 as zs}from"@noble/curves/ed25519.js";import ms from"node:http";import{timingSafeEqual as hs}from"node:crypto";import{createHash as ts,randomBytes as ns,timingSafeEqual as os}from"node:crypto";import{base58 as en}from"@scure/base";import{Interface as so,MaxUint256 as ao,isAddress as co,keccak256 as Za,toUtf8Bytes as Qa}from"ethers";import{Interface as oo,isAddress as Ca}from"ethers";import{isAddress as ka}from"ethers";import{createHash as Kn,createHmac as Yn,timingSafeEqual as Xn}from"node:crypto";import{readFileSync as Jn}from"node:fs";import{homedir as Gn}from"node:os";import{join as je}from"node:path";function zn(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let r=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return r?[r]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),t=Gn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||je(t,".config","oracle")).trim();return[e,je(r,"exec.env")].filter(Boolean)}return[e,je(t,".config","oracle","exec.env"),je(t,".config","mad-desk","exec.env")].filter(Boolean)}function Oe(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of zn())try{let i=Jn(o,"utf8"),s=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(s&&(n=s[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}function he(e,t,r="guard"){let n=Number(t);if(t==null||!Number.isFinite(n))throw new Error(`${r}: current time must be a finite number (got ${Vn(t)})`);let o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${r} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function Vn(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var rt=100;function lr(e){return Array.isArray(e)?`[${e.map(lr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${lr(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Zn(e,{required:t=!1}={}){try{return Oe(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Qn(e){let{signature:t,...r}=e;return r}function eo(e){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<10||t.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return Kn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function ro(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:Xn(r,n)}function to(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=t.length;i+=64)n.push(t.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(r){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function dr(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:i,requireSigned:s=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let a=Zn(o,{required:s});if(s&&!a)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(a){let p=Yn("sha256",a).update(lr(Qn(e))).digest("hex");if(!ro(e.signature,p))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>rt)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>rt||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{he({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},t,"auto-slippage quote")}catch(p){throw new Error(`${p.message}; re-quote before signing`)}if(r!=null&&Number(e.chainId)!==Number(r))throw new Error("auto-slippage guard chain mismatch");if(n&&String(e.venue).toLowerCase()!==String(n).toLowerCase())throw new Error("auto-slippage guard venue mismatch");let d=BigInt(e.quoteAmountOut??0),l=BigInt(e.minAmountOut??0);if(d<=0n||l<=0n)throw new Error("auto-slippage guard amounts must be positive");let f=d*BigInt(1e4-c),m=f/10000n;if(f%10000n!==0n&&(m+=1n),l<m)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let p=to(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==eo(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(p!=null&&p!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is hash-bound but the calldata encodes ${p}, not the guard floor ${e.minAmountOut}`)}else{if(p==null){let g=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${g}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(p!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${p}`)}}return!0}var Ra=new oo(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as io,isAddress as Da}from"ethers";var Ha=new io(["function approve(address spender,uint256 amount) returns (bool)"]),Ja=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function k(e,t="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${t} must be a number or decimal string`);return e}throw new Error(`${t} must be a number or decimal string`)}function R(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function Q(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let r=k(e,t);if(r==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(r)}`)}}function fr(e,t="amount"){let r=Q(e,t);if(r<=0n)throw new Error(`${t} must be positive`);return r}function _(e,t,r="amount"){let n=k(e,r);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${r} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[s="0",a=""]=i.split(".");if(a.length>t)throw new Error(`${r} has more than ${t} decimal places, which would lose precision`);let c=BigInt((s||"0")+a.padEnd(t,"0"));return o?-c:c}var ic=new so(["function approve(address spender,uint256 amount) returns (bool)"]);function tt(e,t){let r=String(e||"").trim();if(!co(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function uo(e,t="approval amount",{allowZero:r=!1}={}){let n=Q(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=ao)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var nt=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),lo=new Set(["0x39509351","0xf9255c1f"]);function V(e){let t=String(e||"").toLowerCase();return t.length<10?!1:nt.has(t.slice(0,10))}function Le(e){if(!V(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=u=>n[u]?"0x"+n[u].slice(24):null,i=u=>n[u]?BigInt("0x"+n[u]):null,s=null,a=null,c=null;switch(r){case"0x095ea7b3":case"0x39509351":s=o(0),a=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),s=o(1),a=i(2);break;case"0xd505accf":s=o(1),a=i(2);break;case"0x8fcbaf0c":{s=o(1),a=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),s=o(1),a=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(s==null||a==null)throw new Error("invalid approve calldata");return{spender:tt(s,"approval spender"),token:c==null?null:tt(c,"approval token"),amount:uo(a,"approval amount",{allowZero:!0}),selector:r,additive:lo.has(r)}}import{createHash as fo,createHmac as cc,timingSafeEqual as uc}from"node:crypto";var po=2,pr=300*1e3,ot=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function mo(e){let t=e==null||e===""?pr:Number(e);return!Number.isFinite(t)||t<0?pr:Math.min(t,ot)}function mr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(mr).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${mr(e[r])}`).join(",")}}`}function ho(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function wo(e){let t=ho(e);return fo("sha256").update(mr(t)).digest("hex")}function it(e,{maxAgeMs:t=pr,nowMs:r=Date.now(),providers:n=null,kinds:o=null,label:i="operator"}={}){if(!e||typeof e!="object")throw new Error(`${i}: prepared envelope object required`);if(e.oraclePrepared!==!0)throw new Error(`${i}: prepared integrity envelope missing \u2014 use an @oracle-agent/oracle prepare result`);if(Number(e.prepareVersion)!==po)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=wo(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let a=Number(e.preparedAt),c=Number(e.expiresAt),u=mo(t),d=r-a,l=c-a;if(!Number.isFinite(d)||!Number.isFinite(c)||!Number.isFinite(l)||d<0||l<=0||l>ot||d>u||r>c)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${u})`);if(n&&!new Set(n).has(e.provider))throw new Error(`${i}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${i}: kind ${e.kind} not allowed here`);return!0}var We=e=>String(e||"").toLowerCase(),go=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),yo=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function K(e){try{return yo.has(BigInt(e))}catch{return!1}}var H=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},st=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ne=(e,t,r,n=String)=>{if(!Array.isArray(t)||t.length===0)throw new Error(`policy: ${r} allowlist is empty`);if(!t.map(n).includes(n(e)))throw new Error(`policy: ${r} not allowed`)};function He(e,t,{nowMs:r=Date.now(),networkFees:n,requireNetworkFees:o=!1}={}){if(!e||!t)throw new Error("policy: artifact and policy required");if(Object.keys(e).some(m=>!go.has(m)))throw new Error("policy: unexpected EVM artifact field");if(e.gasPrice!=null&&(e.maxFeePerGas!=null||e.maxPriorityFeePerGas!=null))throw new Error("policy: ambiguous EVM fee fields");if(e.type!=null&&![0,1,2].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");let i=(m,p)=>{try{return BigInt(m)===BigInt(p)}catch{return String(m)===String(p)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(m=>i(m,e.chainId)))throw new Error("policy: chain not allowed");if(Ne(e.to,t.destinations,"destination",We),Ne(String(e.data||"0x").slice(0,10),t.selectors,"selector",m=>String(m).toLowerCase()),Ne(e.from,t.owners,"owner",We),V(e.data)){let m;try{m=Le(e.data)}catch(g){throw new Error(`policy: malformed approval calldata: ${g?.message||g}`)}Ne(m.spender,t.spenders,"spender",We),Ne(m.token||e.to,t.erc20Tokens,"ERC-20 token",We);let p=H(t.maxApproval,"maxApproval");if(BigInt(m.amount)>p)throw new Error("policy: approval exceeds cap");if(m.additive)throw new Error("policy: additive approval cannot be bounded; use approve() with an absolute amount")}if(H(e.value,"value")>H(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=H(e.gasLimit,"gasLimit");if(s>H(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let a=e.maxFeePerGas??e.gasPrice,c=H(a,"feePerGas")*s,u=0n;try{if(K(e.chainId)&&(e.l1FeeWei===void 0||e.operatorFeeWei===void 0))throw new Error("missing")}catch{throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(e.l1FeeWei!==void 0&&(u+=H(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(u+=H(e.operatorFeeWei,"operatorFeeWei")),K(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let m=H(n.l1FeeWei,"estimated l1FeeWei")+H(n.operatorFeeWei,"estimated operatorFeeWei");if(u<m)throw new Error("policy: rollup fee attestation understates estimate")}if(c+u>H(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=st(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>l)throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r)throw new Error("policy: artifact expired");let f=st(t.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-r>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as at}from"node:crypto";import{Address as Eo,NETWORK as xo,OutScript as ct,RawTx as bo,SigHash as ut,TEST_NETWORK as So,Transaction as Ao}from"@scure/btc-signer";var lt=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},vo=(e,t)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${t}`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`envelope: invalid ${t}`);return r},Io=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,To=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),ue=e=>To(e)?String(e).toLowerCase():String(e),hr=(e,t)=>Array.isArray(t)&&t.some(r=>ue(r)===ue(e)),ko=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function Oo(e){let t=Buffer.from(bo.encode(e)),r=at("sha256").update(t).digest();return Buffer.from(at("sha256").update(r).digest()).reverse().toString("hex")}function Lo(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(Oo(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))throw new Error("envelope: Bitcoin prevout txid mismatch");let t=e.nonWitnessUtxo.outputs?.[e.index];if(!t)throw new Error("envelope: Bitcoin prevout output missing");if(!e.witnessUtxo)throw new Error("envelope: PSBT input witness UTXO required");if(BigInt(e.witnessUtxo.amount)!==BigInt(t.amount)||!ko(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function wr(e,t){if(e.action!=="transfer")throw new Error("envelope: BTC decoder requires transfer action");let r=e?.artifact;if(Object.keys(r).some(l=>!["network","psbt"].includes(l)))throw new Error("envelope: unexpected BTC artifact field");if(!hr(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?xo:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?So:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Ao.fromPSBT(vo(r.psbt,"PSBT"))}catch(l){throw new Error(`envelope: invalid PSBT: ${l?.message||l}`)}if(o.inputsLength===0||o.outputsLength===0)throw new Error("envelope: PSBT inputs and outputs required");let i=Eo(n);for(let l=0;l<o.inputsLength;l++){let f=o.getInput(l);for(let g of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(Io(f[g]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==ut.DEFAULT&&f.sighashType!==ut.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let m=Lo(f),p;try{let g=ct.decode(m.script);if(!["wpkh"].includes(g.type))throw new Error("unsupported input");p=i.encode(g)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!hr(p,t.owners)||ue(p)!==ue(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let s=new Set([e.owner,...t.changeAddresses||[]].map(l=>ue(l))),a=0n,c=!1,u=[];for(let l=0;l<o.outputsLength;l++){let f=o.getOutput(l),m;try{m=i.encode(ct.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let p=ue(m);if(u.push(`${m}:${f.amount}`),p===ue(e.destination)){c=!0,a+=f.amount;continue}if(hr(m,t.destinations)){a+=f.amount;continue}if(!s.has(p))throw new Error("policy: Bitcoin output destination not allowed")}if(!c)throw new Error("envelope: Bitcoin destination mismatch");let d;try{d=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(d<0n||d>lt(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(a>lt(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:a.toString(),notional:(a+d).toString(),fee:d.toString(),outputs:Object.freeze(u)})}function gr(e,t){let{unit:r,value:n,notional:o,fee:i}=wr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as Er}from"node:crypto";import{base58 as wt}from"@scure/base";import{getCompiledTransactionMessageDecoder as No}from"@solana/transaction-messages";var xr="11111111111111111111111111111111",_o="ComputeBudget111111111111111111111111111111",Bo="So11111111111111111111111111111111111111112",gt="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var yt="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Co=5000n,Po=2039280n,$o=37095705934669439343138083508754565189542113879843219016388785533085940283555n,B=57896044618658097711785492504343953926634992332820282019728792003956564819949n,dt=19681161376707505956807079304988542015446066515923890162744021073123829784752n,ft=e=>Er("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Mo=new Map([[ft("route"),{name:"route",prefixBytes:0}],[ft("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),j=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},Ro=(e,t)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${t}`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`envelope: invalid ${t}`);return r},ee=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),J=e=>String(e||""),Fo=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,Ge=e=>Er("sha256").update(e).digest("hex");function Je(e,t){try{let r=Buffer.from(wt.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function U(e){let t=e%B;return t>=0n?t:B+t}function Y(e,t){let r=e;for(;t-- >0n;)r=r*r%B;return r}function qo(e){let r=e*e%B*e%B,n=Y(r,2n)*r%B,o=Y(n,1n)*e%B,i=Y(o,5n)*o%B,s=Y(i,10n)*i%B,a=Y(s,20n)*s%B,c=Y(a,40n)*a%B,u=Y(c,80n)*c%B,d=Y(u,80n)*c%B,l=Y(d,10n)*i%B;return Y(l,2n)*e%B}function Do(e,t){let r=U(t*t*t),n=U(r*r*t),o=qo(e*n),i=U(e*r*o),s=U(t*i*i),a=i,c=U(i*dt),u=s===e,d=s===U(-e),l=s===U(-e*dt);return u&&(i=a),(d||l)&&(i=c),(U(i)&1n)===1n&&(i=U(-i)),!u&&!d?null:i}function Uo(e){if(!e||e.length!==32)return!1;let t=0n;for(let o=31;o>=0;o--)t=(t<<8n)+BigInt(o===31?e[o]&127:e[o]);let r=U(t*t),n=Do(U(r-1n),U($o*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function jo(e,t){let r=Buffer.concat([...e,Je(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=Er("sha256").update(r).digest();if(Uo(n))throw new Error("envelope: derived Solana program address is on curve");return wt.encode(n)}function br(e,t,r=gt){let n=[Je(e,"owner"),Je(r,"token program"),Je(t,"mint")];for(let o=255;o>=0;o--)try{return jo([...n,Buffer.from([o])],yt)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function Wo(e,t){return(t.accountIndices||[]).map(r=>J(e.staticAccounts[r]))}function _e(e){return Buffer.from(e.data||[])}function Ho(e,t){return J(e.staticAccounts[t.programAddressIndex])}function Et(e,t){return Number(t)<e.header.numSignerAccounts}function Jo(e,t){let r=e.header.numSignerAccounts,n=e.header.numReadonlySignerAccounts,o=e.header.numReadonlyNonSignerAccounts,i=e.staticAccounts.length;return Number(t)<r?Number(t)<r-n:Number(t)<i-o}function Be(e){return e.accountIndices||[]}function yr(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function pt(e,t){let r=Be(t).map(n=>{let o=Et(e,n)?"s":"n",i=Jo(e,n)?"w":"r";return`${n}:${J(e.staticAccounts[n])}:${o}:${i}`});return Ge(Buffer.from(r.join(`
|
|
2
|
-
`)))}function mt(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function Go(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function zo(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function Vo(e,t,r){let n=r.maxJupiterRoutePlanSteps===void 0?1:Number(r.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(t<1||t>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(r.jupiterRouteVariants)?r.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=r.jupiterRouteVariantPayloadBytes||{},s=0,a=0,c=[];for(let u=0;u<t;u++){if(s>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e[s++];if(!o.includes(d))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(d)))throw new Error("policy: Jupiter route variant payload size required");let l=Number(i[String(d)]);if(!Number.isSafeInteger(l)||l<0||l>16)throw new Error("policy: Jupiter route variant payload size invalid");if(s+l+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e.subarray(s,s+l);s+=l;let m=f.toString("hex"),p=r.jupiterRouteVariantPayloads?.[String(d)];if(!Array.isArray(p)||!p.map(String).includes(m))throw new Error("policy: Jupiter route variant payload not allowed");let g=e[s++],w=e[s++],h=e[s++];if(g<1||g>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(w!==u||h!==u+1)throw new Error("envelope: unsupported Jupiter route-plan token index");a+=g,c.push(Object.freeze({swapVariant:d,variantPayloadHex:m,percent:g,inputIndex:w,outputIndex:h}))}if(s!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(a!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function Ko(e,t){let r=_e({data:e}),n=r.subarray(0,8).toString("hex"),o=Mo.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,s=o.prefixBytes===1?r[8]:null;if(o.prefixBytes===1&&r.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let a=8+o.prefixBytes,c=a+4,u=r.length-i;if(u<=c)throw new Error("envelope: malformed Jupiter route payload");let d=zo(r,a,"route plan length"),l=r.subarray(c,u),f=Vo(l,d,t);return Object.freeze({instruction:o.name,routeId:s,routePlanSteps:d,routePlan:f,routePlanHash:Ge(l),inAmount:mt(r,u,"in_amount"),quotedOutAmount:mt(r,u+8,"quoted_out_amount"),slippageBps:Go(r,u+16,"slippage_bps"),platformFeeBps:r[u+18],instructionHash:Ge(r)})}function Yo(e,t,r){let n=Wo(e,t),o=(i,s)=>{let a=n[i];if(!a)throw new Error(`envelope: Jupiter ${s} account missing`);return a};if(r.instruction==="route"){if(n.length<9)throw new Error("envelope: Jupiter route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),userTransferAuthority:o(1,"userTransferAuthority"),userSourceTokenAccount:o(2,"userSourceTokenAccount"),userDestinationTokenAccount:o(3,"userDestinationTokenAccount"),destinationTokenAccount:o(4,"destinationTokenAccount"),destinationMint:o(5,"destinationMint"),platformFeeAccount:o(6,"platformFeeAccount"),eventAuthority:o(7,"eventAuthority"),program:o(8,"program")}}if(r.instruction==="shared_accounts_route"){if(n.length<13)throw new Error("envelope: Jupiter shared route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),programAuthority:o(1,"programAuthority"),userTransferAuthority:o(2,"userTransferAuthority"),userSourceTokenAccount:o(3,"sourceTokenAccount"),programSourceTokenAccount:o(4,"programSourceTokenAccount"),programDestinationTokenAccount:o(5,"programDestinationTokenAccount"),userDestinationTokenAccount:o(6,"destinationTokenAccount"),sourceMint:o(7,"sourceMint"),destinationMint:o(8,"destinationMint"),platformFeeAccount:o(9,"platformFeeAccount"),token2022Program:o(10,"token2022Program"),eventAuthority:o(11,"eventAuthority"),program:o(12,"program")}}throw new Error("envelope: unsupported Jupiter account layout")}function ht(e,t){return e&&e!==t?e:null}function W(e,t,r){let n=J(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function Xo(e,t){let r=_e(e);if(r.length===5&&r[0]===2){let n=r.readUInt32LE(1),o=t.maxComputeUnits===void 0?14e5:Number(t.maxComputeUnits);if(!Number.isSafeInteger(o)||o<=0)throw new Error("policy: maxComputeUnits must be positive");if(n>o)throw new Error("policy: Jupiter compute unit limit exceeds cap");return 0n}throw r.length===9&&r[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function Zo(e,t,r,n,o,i){let s=_e(t);if(s.length!==1||s[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let a=Be(t);if(a.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=W(e,a[0],"ATA payer"),u=W(e,a[1],"ATA account"),d=W(e,a[2],"ATA owner"),l=W(e,a[3],"ATA mint"),f=W(e,a[4],"ATA system program"),m=W(e,a[5],"ATA token program");if(c!==r.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(d!==r.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(f!==xr)throw new Error("envelope: Jupiter ATA system program mismatch");if(m!==o)throw new Error("envelope: Jupiter ATA token program mismatch");if(l!==n.inputMint&&l!==n.outputMint)throw new Error("envelope: Jupiter ATA mint mismatch");if(u!==br(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:u,debit:i}}function Qo(e,t,r,n,o){let i=Be(t),s=_e(t);if(i.length!==2||s.length!==12||s.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let a=W(e,i[0],"wrap payer"),c=W(e,i[1],"wrap target"),u=s.readBigUInt64LE(4);if(a!==r.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(u!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return u}function ei(e,t,r,n){let o=Be(t),i=_e(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||W(e,o[0],"syncNative account")!==n)throw new Error("envelope: Jupiter syncNative account mismatch");return{kind:"syncNative"}}if(i[0]===9){if(o.length!==3)throw new Error("envelope: malformed Jupiter closeAccount helper");let s=W(e,o[0],"closeAccount source"),a=W(e,o[1],"closeAccount destination"),c=W(e,o[2],"closeAccount authority");if(s!==n||a!==r.owner||c!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function ri(e,t,r,n,o,i,s){let a=br(t.owner,t.artifact.inputMint,s);if(o.userSourceTokenAccount!==a)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=j(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<Po)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let u=new Map,d=0n,l=!1,f=!1;for(let m of e.instructions){if(m===n)continue;let p=Ho(e,m);if(p===_o)Xo(m,r);else if(p===yt){let{ata:g,debit:w}=Zo(e,m,t,t.artifact,s,c);u.set(g,w)}else if(p===xr)d+=Qo(e,m,t,a,i);else if(p===s){let g=ei(e,m,t,a);g.kind==="syncNative"&&(l=!0),g.kind==="closeAccount"&&(f=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(d>0n&&(!l||!f))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(d!==0n&&d!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...u.values()].reduce((m,p)=>m+p,0n)}function ti(e){let t;try{t=No().decode(Ro(e.messageBase64,"Solana message"))}catch(r){throw new Error(`envelope: invalid Solana message: ${r?.message||r}`)}if(t.version!=="legacy"&&Array.isArray(t.addressTableLookups)&&t.addressTableLookups.length)throw new Error("envelope: unresolved Solana address tables refused");return t}function ni(e,t,r){if(e.header.numSignerAccounts!==1||J(e.staticAccounts[0])!==t.owner||!ee(t.owner,r.owners))throw new Error("envelope: Solana owner mismatch");if(!Array.isArray(e.instructions)||e.instructions.length===0)throw new Error("envelope: Solana instructions required");let n=[];for(let o of e.instructions){let i=J(e.staticAccounts[o.programAddressIndex]);if(!i||!ee(i,r.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function oi(e,t,r){let n=j(r.lamportsPerSignature,"lamportsPerSignature");if(n<Co)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:j(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),s=i*n,a=i*o;if(t.exactFeeLamports!==void 0){let u=j(t.exactFeeLamports,"exactFeeLamports");if(u<s)throw new Error("policy: Solana exact fee below the base signature fee");if(u>a)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=a;if(c>j(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function ii(e,t,r,n){let o=0n,i=!1;for(let s of e.instructions){if(J(e.staticAccounts[s.programAddressIndex])!==xr)throw new Error("envelope: unsupported Solana program decoder");let c=s.accountIndices||[];if(c.length!==2||J(e.staticAccounts[c[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let u=J(e.staticAccounts[c[1]]);if(u!==t.destination||!ee(u,r.destinations))throw new Error("envelope: Solana destination mismatch");let d=Buffer.from(s.data||[]);if(d.length!==12||d.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=d.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function si(e,t,r,n){let o=t.artifact;if(o.provider!=="jupiter")throw new Error("envelope: Solana swap provider must be jupiter");if(o.inputMint!==Bo)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!ee(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Fo(r);if(!ee(o.inputMint,i)||!ee(o.outputMint,i))throw new Error("policy: Solana token not allowed");let s=j(o.inAmount,"inAmount"),a=j(o.outAmount,"outAmount"),c=j(o.otherAmountThreshold,"otherAmountThreshold");if(s<=0n||s>j(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(s>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(a<=0n||c<=0n||c>a)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let u=J(o.jupiterProgram);if(!u||!ee(u,r.programs)||!n.includes(u))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(v=>J(e.staticAccounts[v.programAddressIndex])===u);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=d[0],f=Ko(l.data,r);if(f.instruction==="shared_accounts_route"){let v=Array.isArray(r.jupiterSharedRouteIds)?r.jupiterSharedRouteIds.map(Number):[];if(!v.length)throw new Error("policy: Jupiter shared route id allowlist required");if(!v.includes(Number(f.routeId)))throw new Error("policy: Jupiter shared route id not allowed")}else if(f.routeId!=null)throw new Error("envelope: unexpected Jupiter shared route id");if(!yr(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(f.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(f.inAmount!==s)throw new Error("envelope: Jupiter route in_amount mismatch");if(f.quotedOutAmount!==a)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(f.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let m=f.quotedOutAmount-f.quotedOutAmount*BigInt(f.slippageBps)/10000n;if(c!==m)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(f.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let p=Yo(e,l,f),g=Be(l),w=f.instruction==="shared_accounts_route"?2:1;if(!Et(e,g[w]))throw new Error("envelope: Jupiter transfer authority must be signer");if(p.program!==u)throw new Error("envelope: Jupiter program account mismatch");if(p.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(p.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(p.sourceMint!==void 0&&p.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let h=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[gt];if(!ee(p.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let x=br(t.owner,o.outputMint,p.tokenProgram);if(p.userDestinationTokenAccount!==x)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=ht(p.destinationTokenAccount,u);if(E&&E!==x)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(ht(p.platformFeeAccount,u))throw new Error("policy: Jupiter platform fee account not allowed");if(!yr(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(pt(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let b=Ge(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,pt(e,l)].join(`
|
|
3
|
-
`)));if(!yr(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(b))throw new Error("policy: Jupiter route review hash not allowed");let T=ri(e,t,r,l,p,s,p.tokenProgram),O=s+T;if(O>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:O,programs:n}}function Sr(e,t){if(e.action!=="transfer"&&e.action!=="swap")throw new Error("envelope: Solana decoder requires transfer or swap action");let r=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(r||{}).some(c=>!n.includes(c)))throw new Error("envelope: unexpected Solana artifact field");if(!ee(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=ti(r),i=ni(o,e,t),s=e.action==="transfer"?ii(o,e,t,i):si(o,e,t,i),a=oi(o,r,t);return Object.freeze({unit:"lamports",value:s.value.toString(),notional:(s.value+a).toString(),fee:a.toString(),programs:Object.freeze(s.programs)})}function Ar(e,t){let{unit:r,value:n,notional:o,fee:i}=Sr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}var ai=1e8;function vr(e){if(typeof e!="string"||!/^#(?:0|[1-9]\d*)$/.test(e))return null;let t=Number(e.slice(1));if(!Number.isSafeInteger(t)||t<0)return null;let r=t%10;if(r!==0&&r!==1)return null;let n=Math.floor(t/10),o=ai+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var ci=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),ui=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),li=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),di=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"}),oe=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function fi(e,t){let r=e.toString().padStart(t+1,"0");if(t===0)return r;let n=r.slice(0,-t),o=r.slice(-t).replace(/0+$/,"");return o?`${n}.${o}`:n}function xt(e,t){let r=k(e,`hl: ${t}`);if(!/^\d+(?:\.\d+)?$/.test(r))throw new Error(`hl: ${t} must be a positive decimal`);let[n,o=""]=r.split("."),i=BigInt(n+o);if(i<=0n)throw new Error(`hl: ${t} must be positive`);return{raw:i,decimals:o.length}}function X(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`hl: ${t} must be finite JSON`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(n=>X(n,t)).join(",")}]`;if(!e||typeof e!="object")throw new Error(`hl: ${t} must be structured JSON`);return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${X(e[n],t)}`).join(",")}}`}function pi(e){if(typeof e.orderType!="string"||!e.orderType)throw new Error("hl: order type must be a string");let t=e.orderType,r=e.orderWire;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: declared order wire required");if(t==="limit"){let i=r.limit?.tif;if(!["Gtc","Ioc","Alo"].includes(i)||X(r,"declared order type")!==X({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(X(r,"declared order type")!==X({limit:{tif:"Ioc"}},"expected order type"))throw new Error("hl: market order type must match its IOC wire shape");return}let n={stopMarket:{isMarket:!0,tpsl:"sl"},stopLimit:{isMarket:!1,tpsl:"sl"},takeProfitMarket:{isMarket:!0,tpsl:"tp"},takeProfitLimit:{isMarket:!1,tpsl:"tp"}}[t];if(!n)throw new Error("hl: unsupported declared order type");let o=r.trigger?.triggerPx;if(o==null||X(r,"declared order type")!==X({trigger:{isMarket:n.isMarket,triggerPx:o,tpsl:n.tpsl}},"expected order type"))throw new Error("hl: trigger order type must match its wire shape")}function mi(e,t,r){let n=xt(e.s,"signed size"),o=xt(e.p,"signed price"),i=n.decimals+o.decimals,s=n.raw*o.raw,a=_(t.notionalUsd,i,"hl: notionalUsd");if(a<=0n||s!==a)throw new Error("hl: signed notional must match");let c=_(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>c)throw new Error("hl: notional exceeds cap")}function hi(e,t){let r=e.action.builder;if(r==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: signed order builder must be structured");let n=oe(r.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(R(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(a=>String(a).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=Q(r.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let s=_(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function bt(e,t,r){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(t.side==="buy"))throw new Error("hl: signed side must match exactly");if(k(e.s,"hl: signed size")!==k(t.size,"hl: size"))throw new Error("hl: signed size must match");if(k(e.p,"hl: signed price")!==k(t.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof t.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==t.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(X(e.t,"signed order type")!==X(t.orderWire,"declared order type"))throw new Error("hl: signed order type must match declared order type");let n=Object.prototype.hasOwnProperty.call(e,"c");if(t.clientOrderId==null){if(n)throw new Error("hl: undeclared signed client order id")}else if(!n||typeof e.c!="string"||e.c!==t.clientOrderId)throw new Error("hl: signed client order id must match")}function St(e,t,r,n,o){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(t.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(k(e.s,"hl: bracket protection size")!==k(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(k(e.p,"hl: bracket protection price")!==k(n,"hl: protection price"))throw new Error("hl: bracket protection price must match");if(e.r!==!0)throw new Error("hl: bracket protection must be reduce-only");let i=e.t?.trigger;if(!i||i.isMarket!==!0||i.tpsl!==o)throw new Error("hl: bracket protection trigger must match");if(k(i.triggerPx,"hl: triggerPx")!==k(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function wi(e){let t=String(e||"").replace(/\/$/,"");if(!ci.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function Ir(e){return vr(e)!=null}function gi(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(Ir(r)){if(t.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(n.includes(r)||n.includes("#*")||n.includes("*")||n.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(n.length&&!n.includes(r)&&!n.includes("*"))throw new Error("hl: coin not allowed");return!0}function yi(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(s=>{if(typeof s=="string"){let[a,c]=String(s).split(":");return a===e&&Number(c)===t}return String(s?.coin)===e&&Number(s?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(Ir(e)){let i=Array.isArray(r.coins)?r.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0)return!0;throw new Error("hl: restricted coin policy requires hlMarkets pairs")}let o=Array.isArray(r.coins)?r.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function ie(e,t){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: structured artifact required");let n=oe(r.kind,"kind",48),o=li[n];if(!o)throw new Error("hl: unsupported Hyperliquid kind");if(e.action!==o)throw new Error("hl: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="hyperliquid")throw new Error("hl: destination must be hyperliquid");if(!/^0x[0-9a-fA-F]{40}$/.test(String(e.owner||"")))throw new Error("hl: owner required");let i=wi(r.submitTo);if(Object.prototype.hasOwnProperty.call(r,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let s=Number(r.nonce);if(!Number.isSafeInteger(s)||s<=0)throw new Error("hl: nonce must be a positive integer");if(!r.action||typeof r.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(r.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(r.action.type!==di[n])throw new Error("hl: action type must match kind");let a=r.notionalUsd??0;if(ui.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let c=oe(r.coin,"coin",64),u=r.assetId??r.assetIndex;if(!Number.isSafeInteger(u)||u<0)throw new Error("hl: assetId required");if(n==="hip4-order"||u>=1e8){let d=vr(c);if(!d||d.coin!==c)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==u)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(gi(c,t),yi(c,u,t),n==="hip4-order"&&!Ir(c))throw new Error("hl: HIP-4 orders must use an outcome coin");if(n==="perp-order"||n==="hip3-order"||n==="hip4-order"||n==="perp-bracket"){if(r.side!=="buy"&&r.side!=="sell")throw new Error("hl: side must be buy or sell");if(r.action.type!=="order"||!Array.isArray(r.action.orders))throw new Error("hl: signed orders are required");pi(r);let d=r.action.orders;if(n==="perp-bracket"){let l=r.takeProfitPx,f=r.stopLossPx,m=1+(l==null?0:1)+(f==null?0:1);if(m<2||d.length!==m||r.grouping!=="normalTpsl"||r.action.grouping!==r.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");bt(d[0],r,u);let p=1;l!=null&&St(d[p++],r,u,l,"tp"),f!=null&&St(d[p],r,u,f,"sl")}else{if(d.length!==1)throw new Error("hl: exactly one signed order is required");if(r.grouping!=="na"||r.action.grouping!==r.grouping)throw new Error("hl: signed grouping must match declared grouping");bt(d[0],r,u)}mi(d[0],r,t),hi(r,t),a=k(r.notionalUsd,"hl: notionalUsd")}if(n==="perp-leverage"){let d=r.leverage;if(!Number.isSafeInteger(d)||d<1)throw new Error("hl: leverage must be a positive integer");let l=t.maxLeverage==null?50:t.maxLeverage;if(typeof l!="number"||!Number.isSafeInteger(l)||l<1)throw new Error("hl: maxLeverage must be a positive integer");if(d>l)throw new Error("hl: leverage exceeds cap")}if(n==="perp-cancel"){let d=r.action.cancels;if(!Array.isArray(d)||d.length!==1)throw new Error("hl: exactly one cancel is required");if(!Number.isSafeInteger(d[0].a)||d[0].a!==u)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(r.orderId)||r.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(d[0].o)||d[0].o!==r.orderId)throw new Error("hl: signed cancel order id must match")}if(n==="perp-leverage"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==u)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(r.action.leverage)||r.action.leverage!==r.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(r.marginMode))throw new Error("hl: declared margin mode required");let d=r.marginMode==="cross";if(typeof r.action.isCross!="boolean"||r.action.isCross!==d)throw new Error("hl: signed isCross must match declared margin mode")}if(n==="perp-isolated-margin"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==u)throw new Error("hl: signed margin asset must match assetId");let d=oe(r.usd,"margin usd",64),l=_(d,6,"hl: margin usd");if(Q(r.action.ntli,"hl: signed margin ntli")!==l)throw new Error("hl: signed margin amount must match usd");if(typeof r.isBuy!="boolean"||r.action.isBuy!==r.isBuy)throw new Error("hl: signed margin isBuy must match");let m=_(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),p=l<0n?-l:l;if(p>m)throw new Error("hl: margin notional exceeds cap");a=fi(p,6)}}if(n==="builder-fee-approval"){let c=oe(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(oe(r.action.builder,"signed builder",42).toLowerCase()!==c)throw new Error("hl: signed builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(p=>String(p).toLowerCase()):[]).includes(c))throw new Error("hl: builder not allowed");let d=oe(r.maxFeeRate,"maxFeeRate",32);if(oe(r.action.maxFeeRate,"signed maxFeeRate",32)!==d)throw new Error("hl: signed builder fee must match");if(!/^\d+(?:\.\d+)?%$/.test(d))throw new Error("hl: builder fee rate must be a percent");let l=_(d.slice(0,-1),12,"hl: builder fee percent"),f=_(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(f<0n||l*100n>f)throw new Error("hl: builder fee exceeds cap");if(Number(r.action.nonce)!==s)throw new Error("hl: signed builder nonce must match");let m=i.includes("testnet")?"Testnet":"Mainnet";if(r.hyperliquidChain!==m||r.action.hyperliquidChain!==r.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(r.signatureChainId!=="0x66eee"||r.action.signatureChainId!==r.signatureChainId)throw new Error("hl: signed signature chain id must match")}if(n.startsWith("hype-stake")||n==="hype-delegate"||n==="hype-undelegate"){if(n==="hype-delegate"||n==="hype-undelegate"){let c=n==="hype-undelegate";if(typeof r.action.isUndelegate!="boolean"||r.action.isUndelegate!==c)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(t.maxHypeWei!=null&&BigInt(String(r.action.wei??r.caps?.amountHype??"0"))>BigInt(t.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(a??r.action.wei??0),notional:String(a??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??a??0),coin:r.coin||null,submitTo:i})}import{createHmac as Ei}from"node:crypto";var we="0x"+"00".repeat(32);function Tr(e={}){let t=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,r=e.polyApiSecret||process.env.POLYMARKET_API_SECRET||process.env.POLY_API_SECRET,n=e.polyPassphrase||process.env.POLYMARKET_API_PASSPHRASE||process.env.POLY_API_PASSPHRASE;if(!t||!r||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(t),secret:String(r),passphrase:String(n)}}function At({creds:e,address:t,method:r,path:n,body:o="",nowSec:i}={}){if(!e?.key||!e?.secret||!e?.passphrase)throw new Error("poly: L2 credentials required");if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("poly: L2 address required");let s=String(i??Math.floor(Date.now()/1e3)),a=String(r||"").toUpperCase(),c=String(n||"");if(a!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let u=s+a+c+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),f=Ei("sha256",l).update(u).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:f,POLY_TIMESTAMP:s,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function xi(e,t){if(e.side!==0&&e.side!==1)throw new Error("poly: side must be BUY or SELL");let r=e.side===0?"BUY":"SELL";if(t&&t!==r)throw new Error("poly: side mismatch");return r}function vt(e,t){let r=BigInt(k(e.makerAmount,"poly: makerAmount")),n=BigInt(k(e.takerAmount,"poly: takerAmount"));if(r<=0n||n<=0n)throw new Error("poly: order amounts must be positive integer micro-units");return Number(t==="BUY"?r:n)/1e6}function bi(e){let t=typeof e=="bigint"?e.toString(10):k(e,"poly: salt");if(!/^[1-9][0-9]*$/.test(t))throw new Error("poly: salt must be a positive integer");let r=BigInt(t);if(r>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("poly: salt exceeds safe integer");return Number(r)}function It({message:e,side:t,signature:r,orderType:n="GTC",apiKey:o}={}){if(!e||typeof e!="object")throw new Error("poly: CLOB v2 message required");if(!String(r||"").startsWith("0x"))throw new Error("poly: EIP-712 signature required");if(n!=="GTC")throw new Error("poly: only GTC is public");if(!o)throw new Error("poly: CLOB owner must be the L2 API key");let i=xi(e,t);if(R(e.metadata||we,"poly: metadata").toLowerCase()!==we)throw new Error("poly: metadata must be zero");if(R(e.builder||we,"poly: builder").toLowerCase()!==we)throw new Error("poly: builder must be zero");let s=bi(e.salt);return{deferExec:!1,order:{builder:we,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:we,salt:String(s),side:i,signature:r,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var Si=new Set(["https://clob.polymarket.com/order"]),Ce=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Dc=Object.freeze(Ce.map(e=>e[0])),Ai=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),vi="0xe111180000d2663c0091e4f400237545b87b996b",Ii="0xe2222d279d744050d28e00520010520000310f59",Tt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function kt(e){let t=String(e||"").replace(/\/$/,"");if(!Si.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function Ot(e){let t=R(e,"poly: exchange").toLowerCase();if(!Ai.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function se(e,t){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("poly: structured artifact required");let n=Tt(r.kind,"kind",48);if(n!=="poly-order")throw new Error("poly: unsupported Polymarket kind");if(e.action!=="order")throw new Error("poly: surface/action/kind mismatch");if(R(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(kt(r.submitTo),r.chainId!==137)throw new Error("poly: chainId must be Polygon 137");let o=r.domain;if(!o||typeof o!="object")throw new Error("poly: EIP-712 domain required");if(o.name!=="Polymarket CTF Exchange"||o.version!=="2"||o.chainId!==137)throw new Error("poly: EIP-712 domain must be official CTF Exchange v2 on Polygon");if(Ot(o.verifyingContract),Ot(r.exchange),R(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==R(r.exchange,"poly: exchange").toLowerCase())throw new Error("poly: exchange/domain mismatch");if(typeof r.negRisk!="boolean")throw new Error("poly: negRisk must be a boolean");let i=r.negRisk?Ii:vi;if(R(r.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let s=r.message||r.value;if(!s||typeof s!="object")throw new Error("poly: signed order message required");let a=r.types?.Order;if(!Array.isArray(a)||a.length!==Ce.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let w=0;w<Ce.length;w+=1)if(a[w]?.name!==Ce[w][0]||a[w]?.type!==Ce[w][1])throw new Error("poly: EIP-712 Order type must be official CLOB v2");if((r.orderType||"GTC")!=="GTC")throw new Error("poly: only GTC is public");let c=String(e.owner||"").toLowerCase();if(R(s.maker,"poly: maker").toLowerCase()!==c)throw new Error("poly: maker must equal owner");if(R(s.signer,"poly: signer").toLowerCase()!==c)throw new Error("poly: signer must equal owner");if(s.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof s.builder!="string"||s.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(s.side!==0&&s.side!==1)throw new Error("poly: side must be BUY or SELL");let u=Tt(r.tokenId,"tokenId",80);if(R(s.tokenId,"poly: tokenId")!==u)throw new Error("poly: tokenId mismatch");let d=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(d.length&&!d.includes(u)&&!d.includes("*"))throw new Error("poly: tokenId not allowed");let l=Number(s.side)===0?"BUY":"SELL";if(r.side&&r.side!==l)throw new Error("poly: side mismatch");let f=vt(s,l),m=_(r.notionalUsdc,6,"poly: notionalUsdc"),p=_(f,6,"poly: computed notional");if(m!==p)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let g=t.maxNotionalUsd??t.maxNotionalUsdc;if(g!=null){let w=_(g,6,"poly: maxNotionalUsd");if(p>w)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:String(f),notional:String(f),fee:"0",kind:n,tokenId:u,side:l,submitTo:kt(r.submitTo)})}var Ti=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),kr=14,Lt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function ge(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function Or(e){let t=String(e||"").replace(/\/$/,"");if(!Ti.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function ae(e,t={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("lighter: structured artifact required");let n=Lt(r.kind,"kind",48);if(n!=="lighter-order")throw new Error("lighter: unsupported Lighter kind");if(e.action!=="order")throw new Error("lighter: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="lighter")throw new Error("lighter: destination must be lighter");let o=Or(r.submitTo),i=r.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let s=Number(Q(r.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(s)||s<0)throw new Error("lighter: accountIndex required");let a=Number(Q(r.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: clientOrderIndex required");ge(r.orderType,0,"orderType"),ge(r.timeInForce,1,"timeInForce"),ge(r.reduceOnly,0,"reduceOnly"),ge(r.triggerPrice,0,"triggerPrice"),ge(r.orderExpiry,-1,"orderExpiry");let c=Lt(r.symbol||r.coin,"symbol",32),u=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(u.length&&!u.includes(c)&&!u.includes(String(i))&&!u.includes("*"))throw new Error("lighter: market not allowed");if(r.side!=="buy"&&r.side!=="sell")throw new Error("lighter: side must be buy or sell");let d=fr(r.baseAmount,"lighter: baseAmount"),l=fr(r.price,"lighter: price");if(d>BigInt(Number.MAX_SAFE_INTEGER)||l>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("lighter: baseAmount and price must be safe integers");let f=Number(d),m=Number(l),p=Number(r.sizeDecimals??0),g=Number(r.priceDecimals??0);if(!Number.isInteger(p)||p<0||p>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(g)||g<0||g>12)throw new Error("lighter: priceDecimals required");let w=p+g,h=d*l,x=_(r.notionalUsd,w,"lighter: notionalUsd");if(x<=0n)throw new Error("lighter: notionalUsd required");if(h!==x)throw new Error("lighter: notionalUsd must match size and price");let E=_(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,w,"lighter: maxNotionalUsd");if(h>E)throw new Error("lighter: notional exceeds cap");let b=k(r.notionalUsd,"lighter: notionalUsd");return ge(r.txType,kr,"txType"),Object.freeze({unit:"usd",value:String(b),notional:String(b),fee:"0",kind:n,symbol:c,marketIndex:i,side:r.side,baseAmount:f,price:m,submitTo:o,actionType:"create-order",amount:String(b)})}var Bt=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var Nr=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0,delegate:0}),ki=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Ct=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),Oi=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"}}),Li=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}});var ze=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},S=(e,t)=>{try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`envelope: ${t} must be a non-negative integer`)}},Nt=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ni=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},C=(e,t,r)=>{if(!Ni(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Lr=(e,t,r)=>{Array.isArray(t)&&t.length&&C(e,t,r)},re=(e,t)=>{let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`envelope: ${t} must be a 20-byte address`);return r},le=e=>String(e||"0x").slice(0,10).toLowerCase(),Pt=e=>S(e.gasLimit,"gasLimit")*S(e.maxFeePerGas??e.gasPrice,"feePerGas")+S(e.l1FeeWei??0,"l1FeeWei")+S(e.operatorFeeWei??0,"operatorFeeWei");function ye(e,t,r,{dynamicTail:n=!1}={}){let o=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(o)||o.length<10+t*64)throw new Error(`envelope: malformed ${r} calldata`);if(!n&&o.length!==10+t*64)throw new Error(`envelope: malformed ${r} calldata`);return{hex:o,word:i=>o.slice(10+i*64,10+(i+1)*64)}}function P(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function G(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function _i(e){if(le(e)!=="0x095ea7b3")return null;let t=ye(e,2,"approval");return{kind:"approval",spender:P(t.word(0),"approval spender"),amount:G(t.word(1),"approval amount")}}function $t(e,t){let r=t==="router02-exact-input-single"?7:8,n=ye(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:P(n.word(0),"input token"),outputToken:P(n.word(1),"output token"),recipient:P(n.word(3),"recipient"),amountIn:G(n.word(o),"amountIn"),minimumOut:G(n.word(o+1),"amountOutMinimum")}}function Bi(e){let t=ye(e,12,"Across depositV3",{dynamicTail:!0}),r=G(t.word(11),"message offset");if(r!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let n=10+Number(r)*2;if(t.hex.length<n+64)throw new Error("envelope: malformed Across depositV3 message");let o=Number(BigInt(`0x${t.hex.slice(n,n+64)}`));if(!Number.isSafeInteger(o))throw new Error("envelope: malformed Across depositV3 message length");let i=Math.ceil(o/32)*64;if(t.hex.length!==n+64+i)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:P(t.word(0),"depositor"),recipient:P(t.word(1),"recipient"),inputToken:P(t.word(2),"input token"),outputToken:P(t.word(3),"output token"),amountIn:G(t.word(4),"inputAmount"),minimumOut:G(t.word(5),"outputAmount"),destinationChainId:G(t.word(6),"destinationChainId")}}function Ci(e){let t=String(e||"").replace(/^0x/i,"").toLowerCase();if(t.length<86||t.length%2!==0)throw new Error("envelope: malformed Uniswap path");let r=`0x${t.slice(0,40)}`,n=`0x${t.slice(t.length-40)}`;if(!/^0x[0-9a-f]{40}$/.test(r)||!/^0x[0-9a-f]{40}$/.test(n))throw new Error("envelope: malformed Uniswap path tokens");return{inputToken:r,outputToken:n}}function _t(e,{hasDeadline:t}){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<74)throw new Error("envelope: malformed exactInput calldata");let n=[];for(let w=10;w+64<=r.length;w+=64)n.push(r.slice(w,w+64));let o=(w,h)=>{if(!n[w])throw new Error(`envelope: malformed ${h}`);return BigInt(`0x${n[w]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let s=i/32,a=Number(o(s,"path offset")),c=n[s+1],u=o(s+(t?3:2),"amountIn"),d=o(s+(t?4:3),"amountOutMinimum"),l=s+a/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let f=Number(o(l,"path length")),m=r.slice(10+(l+1)*64,10+(l+1)*64+f*2),{inputToken:p,outputToken:g}=Ci(`0x${m}`);return{kind:"action",action:"swap",inputToken:p,outputToken:g,recipient:P(c,"recipient"),amountIn:u,minimumOut:d}}function Pi(e){let t=ye(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:P(t.word(0),"input token"),outputToken:P(t.word(1),"output token"),recipient:P(t.word(3),"recipient"),amountIn:G(t.word(5),"amountIn"),minimumOut:G(t.word(6),"amountOutMinimum")}}function $i(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let f=10;f+64<=t.length;f+=64)r.push(t.slice(f,f+64));let n=Number(BigInt(`0x${r[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${r[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let s=Number(BigInt(`0x${r[o+1]}`)),a=o+1+s/32,c=Number(BigInt(`0x${r[a]}`)),d=`0x${t.slice(10+(a+1)*64,10+(a+1)*64+c*2)}`,l=le(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return $t(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function Mi(e,t){let r=le(e),n=Ct[r];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed selector");if(n.layout==="router02-exact-input-single"||n.layout==="swap-router-exact-input-single")return{...$t(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{..._t(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{..._t(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...$i(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Pi(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...Bi(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Ri(e){let t=ye(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",contract:P(t.word(0),"mint NFT contract"),feeRecipient:P(t.word(1),"mint fee recipient"),recipient:P(t.word(2),"mint recipient"),quantity:G(t.word(3),"mint quantity")}}function Fi(e,t){let r=le(e);if(String(t).toLowerCase()==="nft-mint")return qi(e);let n=Oi[r];if(!n)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed NFT selector");if(n.layout==="seadrop-mint-public")return{...Ri(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function qi(e){let t=le(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=Li[t];if(!r)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(r.layout==="mint-no-args")return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:1n};if(r.layout==="mint-quantity"){let n=ye(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:G(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function Ve(e){let t=e?.artifact;if(Array.isArray(t?.transactions))return t.transactions;if(t?.transaction&&typeof t.transaction=="object")return[t.transaction];if(t?.data)return[t];throw new Error("envelope: ordered EVM transaction batch required")}function Mt(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let s=re(e.owner,"owner"),a=e.artifact,c=Number(a?.chainId??Ve(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(C(c,t.chains,"chain"),a?.owner!==void 0&&re(a.owner,"batch owner")!==s)throw new Error("envelope: explicit batch owner mismatch");let u=Ve(e);if(!u.length||u.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,l=0n,f=0n;for(let m of u){if(!m||typeof m!="object"||Array.isArray(m))throw new Error("envelope: structured EVM transaction required");if(Number(m.chainId)!==c)throw new Error("envelope: every batch leg must use the same chain");if(re(m.from,"transaction owner")!==s)throw new Error("envelope: every batch leg must use the same owner");if(C(le(m.data),t.selectors,"selector"),d+=S(m.value??0,"value"),l+=S(m.gasLimit,"gasLimit"),f+=Pt(m),K(c)&&(m.l1FeeWei===void 0||m.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>S(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>S(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(f>S(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:u,chainId:c,owner:s,totalValue:d,totalGas:l,totalFee:f}}function Rt(e,t,{nowMs:r=Date.now(),routeAttestationSecret:n}={}){let o=String(e?.surface||"");if(o!=="evm-swap"&&o!=="evm-bridge")throw new Error("envelope: strict EVM swap/bridge surface required");let i=ze(e.provider,"provider",64).toLowerCase();C(i,t.providers,"provider");let s=Mt(e,t,o,{nowMs:r}),a=[],c=-1;for(let p=0;p<s.transactions.length;p++){let g=s.transactions[p],w=_i(g.data),h;if(w){if(c!==-1)throw new Error("envelope: approval must be before action");if(S(g.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let b=re(g.to,"approval token");if(C(b,t.tokens,"token"),C(w.spender,t.spenders,"spender"),w.amount>S(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...w,token:b,index:p}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");C(g.to,t.destinations,"destination"),h={...Mi(g.data,i),target:re(g.to,"action target"),index:p},c=p}let x=S(g.value??0,"value"),E=S(g.gasLimit,"gasLimit");a.push({...h,value:x,gas:E,fee:Pt(g)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let u=a[c],d=o==="evm-swap"?"swap":"bridge";if(u.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if(re(e.destination,"destination")!==u.target)throw new Error("envelope: destination must equal decoded action target");if(u.recipient!==s.owner)throw new Error("envelope: decoded recipient must equal owner");if(u.depositor&&u.depositor!==s.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(C(u.inputToken,t.tokens,"input token"),C(u.outputToken,t.tokens,"output token"),u.amountIn<=0n||u.amountIn>S(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(u.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(dr(e.autoSlippage,{nowMs:r,chainId:s.chainId,venue:i,tx:s.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(u.minimumOut!==S(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(u.action==="bridge"&&S(e.toChainId,"toChainId")!==u.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=a.filter(p=>p.kind==="approval");if(!new Set([...ki,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(p=>String(p).toLowerCase()):[]]).has(u.inputToken))throw new Error("envelope: strict local signer swap/bridge requires native input token; use wallet signing for token-unit rails");if(l.length)throw new Error("envelope: native-value action must not include token approval");if(u.value!==u.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let m=Object.freeze({quoteAmountOut:S(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:S(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...s,decoded:a,action:u,provider:i,authenticatedQuote:m}}function Ft(e,t,{nowMs:r=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint action");let n=ze(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Lr(n,t.providers,"provider");let o=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;o?.oraclePrepared===!0&&it(o,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"});let i=Mt(e,t,"evm-nft",{nowMs:r});if(i.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let s=i.transactions[0],a=le(s.data);C(a,t.selectors,"selector"),C(s.to,t.destinations,"destination");let c=Fi(s.data,n),u=re(e.contract??e.artifact?.contract,"NFT contract");if(Lr(u,t.nftContracts,"NFT contract"),(c.contract||re(s.to,"NFT contract"))!==u)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==i.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&Lr(c.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let l=S(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>S(t.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(c.quantity!==l)throw new Error("envelope: mint calldata quantity mismatch");let f=S(e.totalWei??e.artifact?.totalWei,"totalWei");if(i.totalValue!==f)throw new Error("envelope: mint value does not match declared totalWei");if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&S(e.priceWei??e.artifact.priceWei,"priceWei")*l!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>S(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...i,provider:n,decoded:[{...c,target:re(s.to,"mint target"),value:i.totalValue,gas:i.totalGas,fee:i.totalFee}]}}function Di(e,{localsWaiver:t=!1}={}){if(!(e in Nr))throw new Error("fee: unknown action");return t?0:Nr[e]}function Ke(e,t,{nowMs:r=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:s=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let a=ze(e.surface,"surface",16);if(!Bt.has(a))throw new Error("envelope: unsupported public surface");let c=ze(e.action,"action",32);C(a,t.surfaces,"surface"),C(c,t.actions,"action"),C(e.owner,t.owners,"owner"),C(e.destination,t.destinations,"destination");let u=Nt(t.maxTtlMs,"maxTtlMs"),d=Nt(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>u)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>d)throw new Error("policy: slippage exceeds cap");let l=e.artifact;if(!l||typeof l!="object"||Array.isArray(l))throw new Error("envelope: structured artifact required");if(a==="evm-swap"||a==="evm-bridge")Rt(e,t,{nowMs:r,routeAttestationSecret:o});else if(a==="evm-nft")Ft(e,t,{nowMs:r});else if(a==="evm"){if(!["transfer","approve"].includes(c))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(String(l.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(String(l.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: artifact from mismatch with owner");He({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:s});let p=String(l.data||"0x").toLowerCase(),g=S(l.value,"EVM value");if(p==="0x"){if(g===0n)throw new Error("envelope: native EVM transfer value required")}else if(V(p)){if(g!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else a==="btc"?gr(e,t):a==="sol"?Ar(e,t):a==="hl"?ie(e,t):a==="poly"?se(e,t):a==="lighter"&&ae(e,t);let f=Number(e.fee?.oracleFeeBps)===0&&Nr[c]!==0;if(e.fee?.waiver||f&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(f&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let m=Di(c,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==m)throw new Error("fee: final artifact fee mismatch");return!0}var _r=Object.freeze([...Bt]),Qc=Object.freeze({...Ct});function Br(e,t){if(e.surface==="hl")return ie(e,t);if(e.surface==="poly")return se(e,t);if(e.surface==="lighter")return ae(e,t);if(e.surface==="btc")return gr(e,t);if(e.surface==="sol")return Ar(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Rt(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1),routeAttestationSecret:t.routeAttestationSecret}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(e.surface==="evm-nft"){let r=Ft(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(String(e.surface).startsWith("evm")){let r=S(e.artifact?.value,"EVM value"),n=S(e.artifact?.gasLimit,"EVM gasLimit"),o=S(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+S(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+S(e.artifact?.operatorFeeWei??0,"EVM operatorFeeWei");return Object.freeze({unit:"wei",value:r.toString(),notional:(r+i).toString(),fee:i.toString()})}throw new Error("envelope: unsupported public surface")}function qt(e={}){let t={};for(let r of _r){let n=e[r];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${r} requires simulate, sign, and broadcast functions`);t[r]=Object.freeze({simulate:(o,i)=>n.simulate(structuredClone(o),structuredClone(i)),sign:(o,i)=>n.sign(structuredClone(o),structuredClone(i)),broadcast:(o,i,s)=>n.broadcast(o,structuredClone(i),structuredClone(s))})}}return Object.freeze(t)}function Ye(e,t){let r=e?.surface||"evm",n=t?.[r];if(!n)throw new Error(`adapter: ${r} is not configured on this self-host`);return n}import{createHash as Gt}from"node:crypto";import{ed25519 as Xi}from"@noble/curves/ed25519.js";import{base58 as Yt}from"@scure/base";import{RawTx as Mr,SigHash as de,Transaction as Rr}from"@scure/btc-signer";import{Transaction as Fr,keccak256 as zt,verifyTypedData as Vt}from"ethers";import{encode as Ui}from"@msgpack/msgpack";import{keccak256 as ji,verifyTypedData as Wi}from"ethers";var Ee=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Cr=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Dt(e){let t=BigInt(e);if(t<0n||t>=2n**64n)throw new Error("hl-l1: nonce must fit uint64");let r=Buffer.alloc(8);return r.writeBigUInt64BE(t),r}function Hi(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Ui(e)),Dt(t)];if(r){let s=String(r).replace(/^0x/i,"");if(!/^[0-9a-fA-F]{40}$/.test(s))throw new Error("hl-l1: vaultAddress must be a 20-byte address");i.push(Buffer.from([1]),Buffer.from(s,"hex"))}else i.push(Buffer.from([0]));return n!=null&&i.push(Buffer.from([0]),Dt(n)),ji(Buffer.concat(i))}function Pr(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:Hi(e,t,{vaultAddress:n,expiresAfter:o})}}function Ut(e){let t=e?.typedData;if(t==null)return null;if(typeof t!="object")throw new Error("hl-l1: typedData must match the validated action");if(Object.prototype.hasOwnProperty.call(e,"vaultAddress"))throw new Error("hl-l1: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(e,"expiresAfter"))throw new Error("hl-l1: expiresAfter is not public");let r=Pr(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==Ee.name||String(t.domain?.version)!==Ee.version||Number(t.domain?.chainId)!==Ee.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(Ee.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(Cr.Agent))throw new Error("hl-l1: typedData types must be Hyperliquid Agent");if(t.message?.source!==r.source||String(t.message?.connectionId||"").toLowerCase()!==String(r.connectionId).toLowerCase())throw new Error("hl-l1: typedData message must hash the validated action");return r}async function jt({wallet:e,action:t,nonce:r,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let s=Pr(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(Ee,Cr,s)}function Wt({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:s=null}){try{let a=Pr(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:s}),c=Wi(Ee,Cr,a,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var Ji=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function $r(e){if(e!=null){if(typeof e=="function")throw new Error("lighter: signed tx_info cannot include functions");if(typeof e=="object"){if(typeof e.toJSON=="function")throw new Error("lighter: signed tx_info cannot define toJSON");if(Array.isArray(e)){for(let t of e)$r(t);return}for(let t of Object.values(e))$r(t)}}}function Gi(e){if(typeof e=="string"){if(!e.startsWith("{"))throw new Error("lighter: official signed tx_info JSON required");let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("lighter: official signed tx_info JSON required");return t}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("lighter: official signed tx_info JSON required");return $r(e),JSON.parse(JSON.stringify(e))}function Xe(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function zi(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^-?(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER)||n<BigInt(Number.MIN_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function Ht(e,t,{signed:r=!1}={}){if(typeof e!="number"||!Number.isSafeInteger(e)||!r&&e<0)throw new Error(`lighter: signed ${t} must be an exact numeric integer`);return e}function be(e,t,r,n={}){let o=t.filter(s=>e[s]!==void 0&&e[s]!==null);if(o.length===0)throw new Error(`lighter: ${r} required`);let i=o.map(s=>Ht(e[s],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function Vi(e,t,r){let n=t.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length===0)throw new Error(`lighter: ${r} required`);let o=n.map(i=>String(e[i]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${r}`);return e[n[0]]}function xe(e,t,r,n){let o=be(e,t,n);if(BigInt(o)!==Xe(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Ki(e,t,r,n){let o=be(e,t,n,{signed:!0});if(BigInt(o)!==zi(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Yi(e){let t={};for(let[r,n]of Ji.entries()){let o=n.filter(s=>e[s]!==void 0&&e[s]!==null);if(!o.length)continue;let i=o.map(s=>{let a=e[s];if(r<3)return Ht(a,n[0]);if(typeof a!="string"||a.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return a});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);t[n[0]]=i[0]}return t}function Pe(e,t){let r=Gi(t),n=xe(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=xe(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=xe(r,["Type","type"],e.orderType,"Type"),s=xe(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),a=xe(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),c=xe(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),u=Ki(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=be(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=be(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),f=be(r,["Price","price"],"Price");if(BigInt(d)!==Xe(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==Xe(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==Xe(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let m=Vi(r,["IsAsk","is_ask","isAsk"],"IsAsk");if(typeof m!="number"||m!==0&&m!==1)throw new Error("lighter: signed IsAsk must be exact numeric 0 or 1");let p=m===1,g=e.side==="sell";if(p!==g)throw new Error("lighter: signed IsAsk must match the prepared side");let w=be(r,["txType","tx_type","TxType"],"txType");if(w!==kr)throw new Error("lighter: signed txType must be official create-order");let h={...Yi(r),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:s,ReduceOnly:a,TriggerPrice:c,OrderExpiry:u,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(f),IsAsk:p?1:0,txType:w},x=JSON.stringify(h),E=JSON.parse(x);if(E.MarketIndex!==Number(d)||E.BaseAmount!==Number(l)||E.Price!==Number(f)||E.IsAsk!==(p?1:0)||E.txType!==w)throw new Error("lighter: canonical tx_info mutated");return{txType:w,txInfo:x,submitTo:Or(e.submitTo)}}function Jt(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var Se=e=>{if(typeof e!="string"||e.length===0||e.length>262144||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return null;let t=Buffer.from(e,"base64");return t.toString("base64")===e?t:null},Ze=e=>String(e||"").toLowerCase();function Zi(e,t){if(typeof e!="string")return!1;let r,n;try{r=Fr.from(e),n=Fr.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce,type:t.type,accessList:t.accessList})}catch{return!1}return Ze(r.from)!==Ze(t.from)||Ze(r.to)!==Ze(t.to)?!1:r.unsignedHash===n.unsignedHash}function Qi(e){let t=Buffer.from(Mr.encode(e)),r=Gt("sha256").update(t).digest();return Buffer.from(Gt("sha256").update(r).digest()).reverse().toString("hex")}function Kt(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Qi(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))return!1;let t=e.nonWitnessUtxo.outputs?.[e.index];return t?BigInt(e.witnessUtxo.amount)===BigInt(t.amount)&&Buffer.from(e.witnessUtxo.script||[]).equals(Buffer.from(t.script||[])):!1}function es(e,t){let r=Se(e),n=Se(t.psbt);if(!r||!n)return!1;try{let o=Rr.fromPSBT(n),i=Rr.fromPSBT(r);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let s=0;s<i.inputsLength;s++){let a=i.getInput(s),c=o.getInput(s);if(!Kt(c)||!Kt(a))return!1;let u=(h,x)=>{if(h==null&&x==null)return!0;if(h==null||x==null)return!1;try{return Buffer.from(h).equals(Buffer.from(x))}catch{return!1}},d=(h,x)=>{if(h==null&&x==null)return!0;if(h==null||x==null)return!1;try{return Buffer.from(Mr.encode(h)).equals(Buffer.from(Mr.encode(x)))}catch{return u(h,x)}};if(!!a.witnessUtxo!=!!c.witnessUtxo||a.witnessUtxo&&(BigInt(a.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!u(a.witnessUtxo.script,c.witnessUtxo.script))||!d(a.nonWitnessUtxo,c.nonWitnessUtxo)||!u(a.redeemScript,c.redeemScript)||!u(a.witnessScript,c.witnessScript)||a.sighashType!==void 0&&a.sighashType!==de.DEFAULT&&a.sighashType!==de.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===de.ALL,f=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===de.ALL:!1;for(let h of a.partialSig||[]){let x=Array.isArray(h)?h[1]:h;if(!l(x))return!1}if(a.tapKeySig&&!f(a.tapKeySig))return!1;for(let h of a.tapScriptSig||[]){let x=Array.isArray(h)?h[1]:h;if(!f(x))return!1}let m=h=>h[h.length-1]===de.ALL,p=h=>h.length>=9&&h.length<=73&&h[1]===h.length-3&&h[2]===2,g=h=>{let x=!1;for(let E of h)if(E instanceof Uint8Array){if(E[0]===48){if(!p(E)||!m(E))return!1;x=!0;continue}if(E.length===64){x=!0;continue}if(E.length===65){if(E[64]!==de.ALL&&E[64]!==de.DEFAULT)return!1;x=!0}}return x};if(a.finalScriptWitness){let h;if(Array.isArray(a.finalScriptWitness))h=a.finalScriptWitness;else if(a.finalScriptWitness instanceof Uint8Array){let x=a.finalScriptWitness,E=O=>{let v=x[O];return v===void 0?null:v<253?{value:v,next:O+1}:v===253?{value:x[O+1]|x[O+2]<<8,next:O+3}:null},b=E(0);if(!b)return!1;h=[];let T=b.next;for(let O=0;O<b.value;O++){let v=E(T);if(!v||T+v.value>x.length)return!1;h.push(x.slice(v.next,v.next+v.value)),T=v.next+v.value}if(T!==x.length)return!1}else return!1;if(!h.length||!g(h))return!1}if(a.finalScriptSig instanceof Uint8Array&&a.finalScriptSig.length){let h=a.finalScriptSig,x=[],E=0;for(;E<h.length;){let b=h[E];if(b>=1&&b<=75){if(E+1+b>h.length)return!1;x.push(h.slice(E+1,E+1+b)),E+=1+b;continue}if(b===76){let T=h[E+1];if(T===void 0||E+2+T>h.length)return!1;x.push(h.slice(E+2,E+2+T)),E+=2+T;continue}return!1}if(!x.length||!g(x))return!1}if(![a.partialSig,a.tapKeySig,a.tapScriptSig,a.finalScriptSig,a.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function Xt(e){let t=0,r=0,n=0;for(;n<e.length&&n<3;){let o=e[n++];if(t|=(o&127)<<r,(o&128)===0)return{value:t,offset:n};r+=7}return null}function rs(e,t,r){let n=Se(e),o=Se(t.messageBase64);if(!n||!o)return!1;let i=Xt(n);if(!i||i.value!==1||i.offset!==1)return!1;let s=i.offset+64;if(s>=n.length)return!1;let a=n.subarray(i.offset,s),c=n.subarray(s);if(!c.equals(o))return!1;try{let u=Yt.decode(String(r));return u.length===32&&Xi.verify(a,c,u)}catch{return!1}}function Zt(e,t,r,n){if(String(e).startsWith("evm"))return Zi(t,r);if(e==="btc")return es(t,r);if(e==="sol")return rs(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String(Vt(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return Wt({signature:t,action:r?.action,nonce:r?.nonce,isMainnet:!String(r?.submitTo||"").includes("testnet"),owner:n?.owner})}if(e==="poly"&&r?.domain&&r.types&&r.message)try{return String(Vt(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Pe(r,t),!0}catch{return!1}return!1}function Qt(e,t){try{if(String(e).startsWith("evm"))return Fr.from(t).hash;if(e==="btc"){let r=Se(t);if(!r)return null;let n=Rr.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=Se(t);if(!r)return null;let n=Xt(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Yt.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return zt(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return zt(t)}catch{}return null}var is=e=>String(e||"").toLowerCase();function te(e){return ts("sha256").update(JSON.stringify(e)).digest("hex")}function Dr(e,t,r={}){return He(e,t,r)}async function ss(e,t={}){if(!K(e?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(typeof t.estimateNetworkFees!="function")throw new Error("policy: rollup fee estimate required");let r=await t.estimateNetworkFees(e);if(!r||r.l1FeeWei===void 0||r.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");return{l1FeeWei:String(r.l1FeeWei),operatorFeeWei:String(r.operatorFeeWei)}}function rn(e,t,r=!1){if(!K(e?.chainId))return!0;if(e.l1FeeWei===void 0||e.operatorFeeWei===void 0)throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei");if(r||t!=null){if(!t||t.l1FeeWei===void 0||t.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let n=BigInt(e.l1FeeWei)+BigInt(e.operatorFeeWei),o=BigInt(t.l1FeeWei)+BigInt(t.operatorFeeWei);if(n<o)throw new Error("policy: rollup fee attestation understates estimate")}return!0}var Qe=class{#e=new Map;constructor({now:t=Date.now}={}){this.now=t}issue({artifact:t,owner:r,ttlMs:n=6e4}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=ns(32).toString("hex");return this.#e.set(o,{digest:te(t),owner:is(r),expiresAtMs:this.now()+n}),o}consume(t,r){let n=this.#e.get(String(t));if(!n)throw new Error("confirmation: used or unknown nonce");if(n.expiresAtMs<=this.now())throw this.#e.delete(String(t)),new Error("confirmation: expired nonce");let o=Buffer.from(n.digest,"hex"),i=Buffer.from(te(r),"hex");if(!os(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(t)),n}clear(){this.#e.clear()}};function as(e){let t=String(e?.data||"0x").toLowerCase(),r=BigInt(e?.value??0);if(t==="0x"){if(r<=0n)throw new Error("signer: native EVM transfer value required");return!0}if(V(t)){if(r!==0n)throw new Error("signer: EVM approval cannot transfer native value");return!0}throw new Error("signer: unsupported EVM calldata; use a versioned envelope")}function cs(e={},t={}){let r={};for(let n of new Set([...Object.keys(e||{}),...Object.keys(t||{})]))r[n]=(BigInt(t?.[n]??0)-BigInt(e?.[n]??0)).toString();return r}function er(e,t){let r=String(t||"");if(String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(r);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(r);if(e==="sol")try{let n=en.decode(r);return n.length===64&&en.encode(n)===r}catch{return!1}return e==="hl"?/^0x[0-9a-fA-F]{64}$/.test(r):e==="poly"?/^0x[0-9a-fA-F]{64}$/.test(r):!1}function tn(e,t,r){return!er(e,t)||!er(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function us(e){let t=e?.confirmationMode;if(t!=="exact-human"&&t!=="auto-within-rails")throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");return t}async function qr({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:s,nowMs:a}){let c=us(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(t?.triggerAttestation,e,a())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(s)return n.confirmations.consume(r,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=a())throw new Error("confirmation: expired nonce");return i}function ls(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function ds(e,t){return e&&ls(e.surface)?Ve(e):[t]}function fs(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!tn(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function ps(e,t){let r=e?.verifiedBefore??e?.before,n=e?.verifiedAfter??e?.after;return{transactionHash:t,status:e?.status,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:cs(r,n)}}async function nn(e,t,r){if(!r.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:w,...h}=e||{};return h})(),i=ds(n,o),s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,a=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:null,consumeNonce:!0,nowMs:a}),u=te(e),d=(w={})=>{n?Ke(n,s,w):(Dr(o,s,{nowMs:w.nowMs,networkFees:w.networkFees,requireNetworkFees:w.requireNetworkFees}),as(o))},l=async w=>{let h=n&&!String(n.surface||"").startsWith("evm")?void 0:await ss(w,r);return{nowMs:a(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:h,requireNetworkFees:K(w?.chainId)}};d({nowMs:a(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let w of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[w]!="function")throw new Error(`signer: ${w} is required`);let f=r.reserveLedger(n||e,s);if(!f)throw new Error("signer: ledger reservation required");let m=!1,p=[];try{for(let w of i){if(typeof r.simulate!="function"||await r.simulate(w,n)!==!0)throw new Error("signer: strict affirmative simulation required");let h=await l(w);if(rn(w,h.networkFees,h.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:c,consumeNonce:!1,nowMs:a}),d(h),r.validateReservation(f,s,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,s):void 0),m=!0;let x=await r.sign(w,n);if(typeof r.verifySigned!="function"||await r.verifySigned(x,w,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!r.isArmed())throw new Error("signer: disarmed before broadcast");if(te(e)!==u)throw new Error("signer: artifact mutated after signing");s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:c,consumeNonce:!1,nowMs:a});let E=await l(w);rn(w,E.networkFees,E.requireNetworkFees),d(E),r.validateReservation(f,s,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,s):void 0);let b=await r.broadcast(x,w,n),T=b?.status,O=n?.surface||"evm",v=fs(b,O),Te=Qt(O,x);if(!tn(O,v,Te))throw new Error("signer: receipt transaction hash does not match signed bytes");if(T===0||T==="0x0")throw er(O,v)?(r.settleFailedLedger(f),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(T!==1&&T!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!er(O,v))throw new Error("signer: successful broadcast requires a valid transaction hash");p.push(ps(b,v))}}catch(w){throw m||r.releaseLedger(f),w}if(r.commitLedger(f),p.length===1){let w={receipt:p[0]};return n?.surface==="evm-bridge"&&(w.originStatus="success",w.destinationStatus="unverified",w.destinationSuccess=!1,w.note="Origin-chain receipts do not prove destination-chain settlement."),w}let g={receipts:p,status:"success"};return n?.surface==="evm-bridge"&&(g.originStatus="success",g.destinationStatus="unverified",g.destinationSuccess=!1,g.note="Origin-chain receipts do not prove destination-chain settlement."),g}var on=new Set(["127.0.0.1","::1","localhost"]),ws=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&hs(r,n)},$=(e,t,r)=>{let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function gs(e){let t=String(e||"");if(t.startsWith("[")){let r=t.indexOf("]");if(r>1)return t.slice(1,r)}return t.split(":")[0]}var sn=e=>new Promise((t,r)=>{let n=0,o=[],i=!1;e.on("data",s=>{n+=s.length,n>64*1024&&!i?(i=!0,r(new Error("request refused")),e.resume()):i||o.push(s)}),e.on("end",()=>{if(!i)try{t(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{r(new Error("request refused"))}}),e.on("error",r)});function an(e={}){let t=e.host||"127.0.0.1";if(!on.has(t))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let i of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[i]!="function")throw new Error(`signer: ${i} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Qe,n=e.origin||`http://${t}`;return ms.createServer(async(i,s)=>{try{let a=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!ws(a,e.token))return $(s,401,{error:"unauthorized"});let c=gs(i.headers.host);if(!on.has(c))return $(s,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return $(s,403,{error:"origin refused"});if(i.method==="GET"&&i.url==="/status"){let u=typeof e.readPolicy=="function"?e.readPolicy():e.policy,d=new Set(_r),l=Array.isArray(u?.surfaces)?u.surfaces.filter(f=>typeof f=="string"&&d.has(f)):[];return $(s,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:l,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(i.method==="POST"&&i.url==="/disarm")return e.disarm(),r.clear(),$(s,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return $(s,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return $(s,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return $(s,403,{error:"autonomous signer does not issue human confirmation nonces"});let u=await sn(i),d=te(u.artifact),l=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(l?.confirmationMode!=="exact-human")return $(s,403,{error:"exact-human policy required"});let f=typeof e.nowMs=="function"?e.nowMs():Date.now();if(u.artifact?.version===1&&u.artifact?.surface)Ke(u.artifact,l,{nowMs:f,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:m,...p}=u.artifact||{};Dr(p,l,{nowMs:f})}return typeof e.confirmArtifact!="function"?$(s,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(u.artifact,d,l)!==!0?$(s,400,{error:"exact human confirmation refused"}):$(s,200,{confirmationNonce:r.issue({artifact:u.artifact,owner:u.artifact?.owner??u.artifact?.from,ttlMs:u.ttlMs})})}if(i.method==="POST"&&i.url==="/execute"){let u=await sn(i),d=await nn(u.artifact,u.confirmationNonce,{...e,confirmations:r});return $(s,200,d)}return $(s,404,{error:"not found"})}catch(a){return e.onError?.(String(a?.message||a)),$(s,400,{error:"request refused"})}})}import{createCipheriv as ku,createDecipheriv as ys,randomBytes as Es,scryptSync as xs}from"node:crypto";import I from"node:fs";import Ae from"node:path";var bs="ORACLE-LOCAL-VAULT",Ss=1,tr=Object.freeze({N:1<<17,r:8,p:1}),As=256*1024*1024,vs=16*1024;function rr(e,t,r,{max:n=t}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${r} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<t||o.length>n)throw new Error(`local-vault: invalid ${r} length`);return o}function Is(e,t,r=tr){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return xs(n,t,32,{...r,maxmem:As})}function cn(e,t){if(e?.magic!==bs||e?.version!==Ss)throw new Error("local-vault: unsupported vault file");if(e?.kdf?.name!=="scrypt"||e?.cipher?.name!=="aes-256-gcm")throw new Error("local-vault: unsupported cryptography");if(e.kdf.N!==tr.N||e.kdf.r!==tr.r||e.kdf.p!==tr.p)throw new Error("local-vault: unsupported KDF parameters");if(Object.keys(e.kdf).sort().join(",")!=="N,name,p,r,salt"||Object.keys(e.cipher).sort().join(",")!=="iv,name")throw new Error("local-vault: unexpected cryptography field");if(!e.meta||Object.keys(e.meta).some(l=>!["address","addresses","kind","createdAt"].includes(l))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||JSON.stringify(e.meta.addresses||{}).length>1024||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let r=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(l=>!r.includes(l)))throw new Error("local-vault: unexpected vault field");let n=rr(e.kdf.salt,32,"salt"),o=rr(e.cipher.iv,12,"iv"),i=rr(e.tag,16,"tag"),s=rr(e.ciphertext,1,"ciphertext",{max:vs}),{ciphertext:a,tag:c,...u}=e,d=Is(t,n);try{let l=ys("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(u))),l.setAuthTag(i),Buffer.concat([l.update(s),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function Ts(e){if(!e.isFile())throw new Error("local-vault: secret source must be a regular file");if(e.uid!==process.getuid?.())throw new Error("local-vault: secret source must be owned by this user");if(e.nlink!==1)throw new Error("local-vault: refusing hard-linked secret source");if((e.mode&63)!==0)throw new Error("local-vault: secret source must be owner-only (0600)")}function ks(e){let t=Ae.dirname(e),r=I.lstatSync(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(r.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((r.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=I.lstatSync(e);if(n.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!n.isFile()||n.uid!==process.getuid?.()||n.nlink!==1)throw new Error("local-vault: unsafe destination file");if(n.dev!==r.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function L(e){let t;try{t=I.openSync(e,I.constants.O_RDONLY|I.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=I.fstatSync(t);if(Ts(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=I.lstatSync(e);if(n.isSymbolicLink()||n.dev!==r.dev||n.ino!==r.ino)throw new Error("local-vault: secret source changed or is too large");return I.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{I.closeSync(t)}}function un(e){return JSON.parse(L(e))}function ce(e,t){I.mkdirSync(Ae.dirname(e),{recursive:!0,mode:448}),ks(e);let r=Ae.join(Ae.dirname(e),`.${Ae.basename(e)}.${process.pid}.${Es(6).toString("hex")}.tmp`);try{let n=I.openSync(r,I.constants.O_CREAT|I.constants.O_EXCL|I.constants.O_WRONLY|I.constants.O_NOFOLLOW,384);try{I.writeFileSync(n,String(t)),I.fsyncSync(n)}finally{I.closeSync(n)}I.renameSync(r,e),I.chmodSync(e,384);let o=I.openSync(Ae.dirname(e),"r");try{I.fsyncSync(o)}finally{I.closeSync(o)}}catch(n){try{I.unlinkSync(r)}catch{}throw n}}import{createHmac as Ls,randomBytes as Ns,timingSafeEqual as _s}from"node:crypto";import M from"node:fs";import fe from"node:path";import{homedir as Ur}from"node:os";import{join as jr}from"node:path";var ln=process.env.ORACLE_PUBLIC_DESKTOP==="1",Os=ln?process.env.ORACLE_CONFIG_DIR||jr(Ur(),".config","oracle"):jr(Ur(),".config","oracle"),Cu=ln?Os:jr(Ur(),".config","mad-desk");var Fu="0".repeat(64),qu=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});function nr(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(nr).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+nr(e[r])).join(",")+"}"}var Du=Promise.resolve();function ve(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=s=>{try{return M.realpathSync(s)}catch{return fe.resolve(s)}},n=r(fe.dirname(fe.resolve(e))),o=r(fe.dirname(fe.resolve(t))),i=(s,a)=>a===s||a.startsWith(s+fe.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var Bs=864e5,D=(e,t)=>Ls("sha256",t).update(nr(e)).digest("hex"),Z=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&_s(r,n)},Cs=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Ps(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Z(e.integrity.mac,D(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function ir(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=L(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!Z(n?.integrity?.mac,D(n?.marker,t)))throw new Error("policy: sequence anchor integrity failed");return{sequence:Number(n?.marker?.policySequence||0),policyMac:n?.marker?.policyMac??null,present:!0,ledgerInitialized:n?.marker?.ledgerInitialized===!0}}function $s(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let a=ir(e,r);i=a.present&&a.ledgerInitialized===!0}catch{i=!1}let s={policySequence:Number(t),policyMac:String(n)};i&&(s.ledgerInitialized=!0),ce(e,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:D(s,r)}})+`
|
|
4
|
-
`)}function
|
|
1
|
+
import da from"node:path";import De from"node:fs";import Dn from"node:os";import me from"node:path";import{fileURLToPath as Un}from"node:url";var jn=me.dirname(Un(import.meta.url)),ga=me.resolve(jn,"../..");function et(){return process.env.ORACLE_FAKE_HOME||Dn.homedir()}function Wn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function Ue(){return Wn()?process.env.ORACLE_CONFIG_DIR||me.join(et(),".config","oracle"):me.join(et(),".config","oracle")}function Hn(){return me.join(Ue(),"desk.json")}function Jn(){return me.join(Ue(),"env")}function pe({force:e=!1}={}){if(pe._done&&!e)return pe._result||null;pe._done=!0;let t={},r=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=Jn();if(De.existsSync(o))for(let i of De.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let a=s[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(s[1],a)}}catch{}try{let o=Hn();if(De.existsSync(o)){let i=JSON.parse(De.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),pe._result=Object.keys(t).length?t:null,pe._result}try{pe()}catch{}import On from"node:fs";import V from"node:path";import zs from"node:os";import{createHash as Vs,randomBytes as Ks}from"node:crypto";import{Transaction as Gr}from"@scure/btc-signer";import{ed25519 as Ys}from"@noble/curves/ed25519.js";import gs from"node:http";import{timingSafeEqual as ys}from"node:crypto";import{createHash as is,randomBytes as ss,timingSafeEqual as as}from"node:crypto";import{base58 as rn}from"@scure/base";import{Interface as Oi}from"ethers";import{Interface as ao,MaxUint256 as co,isAddress as uo,keccak256 as rc,toUtf8Bytes as tc}from"ethers";import{Interface as io,isAddress as Ra}from"ethers";import{isAddress as Na}from"ethers";import{createHash as Yn,createHmac as Xn,timingSafeEqual as Zn}from"node:crypto";import{readFileSync as Gn}from"node:fs";import{homedir as zn}from"node:os";import{join as je}from"node:path";function Vn(){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=zn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||je(t,".config","oracle")).trim();return[e,je(r,"exec.env")].filter(Boolean)}return[e,je(t,".config","oracle","exec.env"),je(t,".config","mad-desk","exec.env")].filter(Boolean)}function Oe(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of Vn())try{let i=Gn(o,"utf8"),s=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(s&&(n=s[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}function he(e,t,r="guard"){let n=Number(t);if(t==null||!Number.isFinite(n))throw new Error(`${r}: current time must be a finite number (got ${Kn(t)})`);let o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${r} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function Kn(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var rt=100;function lr(e){return Array.isArray(e)?`[${e.map(lr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${lr(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Qn(e,{required:t=!1}={}){try{return Oe(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function eo(e){let{signature:t,...r}=e;return r}function ro(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 Yn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function to(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:Zn(r,n)}function no(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=t.length;i+=64)n.push(t.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(r){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function dr(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:i,requireSigned:s=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let a=Qn(o,{required:s});if(s&&!a)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(a){let m=Xn("sha256",a).update(lr(eo(e))).digest("hex");if(!to(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>rt)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>rt||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{he({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},t,"auto-slippage quote")}catch(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 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=no(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==ro(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(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 Da=new io(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as so,isAddress as Wa}from"ethers";var za=new so(["function approve(address spender,uint256 amount) returns (bool)"]),Va=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function k(e,t="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${t} must be a number or decimal string`);return e}throw new Error(`${t} must be a number or decimal string`)}function M(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function ee(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let r=k(e,t);if(r==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(r)}`)}}function fr(e,t="amount"){let r=ee(e,t);if(r<=0n)throw new Error(`${t} must be positive`);return r}function _(e,t,r="amount"){let n=k(e,r);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${r} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[s="0",a=""]=i.split(".");if(a.length>t)throw new Error(`${r} has more than ${t} decimal places, which would lose precision`);let c=BigInt((s||"0")+a.padEnd(t,"0"));return o?-c:c}var cc=new ao(["function approve(address spender,uint256 amount) returns (bool)"]);function tt(e,t){let r=String(e||"").trim();if(!uo(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function lo(e,t="approval amount",{allowZero:r=!1}={}){let n=ee(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=co)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var nt=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),fo=new Set(["0x39509351","0xf9255c1f"]);function K(e){let t=String(e||"").toLowerCase();return t.length<10?!1:nt.has(t.slice(0,10))}function Le(e){if(!K(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=u=>n[u]?"0x"+n[u].slice(24):null,i=u=>n[u]?BigInt("0x"+n[u]):null,s=null,a=null,c=null;switch(r){case"0x095ea7b3":case"0x39509351":s=o(0),a=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),s=o(1),a=i(2);break;case"0xd505accf":s=o(1),a=i(2);break;case"0x8fcbaf0c":{s=o(1),a=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),s=o(1),a=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(s==null||a==null)throw new Error("invalid approve calldata");return{spender:tt(s,"approval spender"),token:c==null?null:tt(c,"approval token"),amount:lo(a,"approval amount",{allowZero:!0}),selector:r,additive:fo.has(r)}}import{createHash as po,createHmac as dc,timingSafeEqual as fc}from"node:crypto";var mo=2,pr=300*1e3,ot=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function ho(e){let t=e==null||e===""?pr:Number(e);return!Number.isFinite(t)||t<0?pr:Math.min(t,ot)}function mr(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(mr).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${mr(e[r])}`).join(",")}}`}function wo(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function go(e){let t=wo(e);return po("sha256").update(mr(t)).digest("hex")}function it(e,{maxAgeMs:t=pr,nowMs:r=Date.now(),providers:n=null,kinds:o=null,label:i="operator"}={}){if(!e||typeof e!="object")throw new Error(`${i}: prepared envelope object required`);if(e.oraclePrepared!==!0)throw new Error(`${i}: prepared integrity envelope missing \u2014 use an @oracle-agent/oracle prepare result`);if(Number(e.prepareVersion)!==mo)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=go(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let a=Number(e.preparedAt),c=Number(e.expiresAt),u=ho(t),d=r-a,l=c-a;if(!Number.isFinite(d)||!Number.isFinite(c)||!Number.isFinite(l)||d<0||l<=0||l>ot||d>u||r>=c)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${u})`);if(n&&!new Set(n).has(e.provider))throw new Error(`${i}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${i}: kind ${e.kind} not allowed here`);return!0}var We=e=>String(e||"").toLowerCase(),yo=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),Eo=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function Y(e){try{return Eo.has(BigInt(e))}catch{return!1}}var J=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},st=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ne=(e,t,r,n=String)=>{if(!Array.isArray(t)||t.length===0)throw new Error(`policy: ${r} allowlist is empty`);if(!t.map(n).includes(n(e)))throw new Error(`policy: ${r} not allowed`)};function He(e,t,{nowMs:r=Date.now(),networkFees:n,requireNetworkFees:o=!1}={}){if(!e||!t)throw new Error("policy: artifact and policy required");if(Object.keys(e).some(p=>!yo.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(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(Ne(e.to,t.destinations,"destination",We),Ne(String(e.data||"0x").slice(0,10),t.selectors,"selector",p=>String(p).toLowerCase()),Ne(e.from,t.owners,"owner",We),K(e.data)){let p;try{p=Le(e.data)}catch(g){throw new Error(`policy: malformed approval calldata: ${g?.message||g}`)}Ne(p.spender,t.spenders,"spender",We),Ne(p.token||e.to,t.erc20Tokens,"ERC-20 token",We);let m=J(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(J(e.value,"value")>J(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=J(e.gasLimit,"gasLimit");if(s>J(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let a=e.maxFeePerGas??e.gasPrice,c=J(a,"feePerGas")*s,u=0n;try{if(Y(e.chainId)&&(e.l1FeeWei===void 0||e.operatorFeeWei===void 0))throw new Error("missing")}catch{throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(e.l1FeeWei!==void 0&&(u+=J(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(u+=J(e.operatorFeeWei,"operatorFeeWei")),Y(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=J(n.l1FeeWei,"estimated l1FeeWei")+J(n.operatorFeeWei,"estimated operatorFeeWei");if(u<p)throw new Error("policy: rollup fee attestation understates estimate")}if(c+u>J(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=st(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>l)throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r)throw new Error("policy: artifact expired");let f=st(t.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-r>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as at}from"node:crypto";import{Address as xo,NETWORK as bo,OutScript as ct,RawTx as So,SigHash as ut,TEST_NETWORK as Ao,Transaction as vo}from"@scure/btc-signer";var lt=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},Io=(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},To=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,ko=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),ue=e=>ko(e)?String(e).toLowerCase():String(e),hr=(e,t)=>Array.isArray(t)&&t.some(r=>ue(r)===ue(e)),Oo=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function Lo(e){let t=Buffer.from(So.encode(e)),r=at("sha256").update(t).digest();return Buffer.from(at("sha256").update(r).digest()).reverse().toString("hex")}function No(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(Lo(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))throw new Error("envelope: Bitcoin prevout txid mismatch");let 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)||!Oo(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function wr(e,t){if(e.action!=="transfer")throw new Error("envelope: BTC decoder requires transfer action");let r=e?.artifact;if(Object.keys(r).some(l=>!["network","psbt"].includes(l)))throw new Error("envelope: unexpected BTC artifact field");if(!hr(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?bo:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?Ao:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=vo.fromPSBT(Io(r.psbt,"PSBT"))}catch(l){throw new Error(`envelope: invalid PSBT: ${l?.message||l}`)}if(o.inputsLength===0||o.outputsLength===0)throw new Error("envelope: PSBT inputs and outputs required");let i=xo(n);for(let l=0;l<o.inputsLength;l++){let f=o.getInput(l);for(let g of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(To(f[g]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==ut.DEFAULT&&f.sighashType!==ut.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let p=No(f),m;try{let g=ct.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(!hr(m,t.owners)||ue(m)!==ue(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let s=new Set([e.owner,...t.changeAddresses||[]].map(l=>ue(l))),a=0n,c=!1,u=[];for(let l=0;l<o.outputsLength;l++){let f=o.getOutput(l),p;try{p=i.encode(ct.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=ue(p);if(u.push(`${p}:${f.amount}`),m===ue(e.destination)){c=!0,a+=f.amount;continue}if(hr(p,t.destinations)){a+=f.amount;continue}if(!s.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>lt(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(a>lt(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:a.toString(),notional:(a+d).toString(),fee:d.toString(),outputs:Object.freeze(u)})}function gr(e,t){let{unit:r,value:n,notional:o,fee:i}=wr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as Er}from"node:crypto";import{base58 as wt}from"@scure/base";import{getCompiledTransactionMessageDecoder as _o}from"@solana/transaction-messages";var xr="11111111111111111111111111111111",Bo="ComputeBudget111111111111111111111111111111",Co="So11111111111111111111111111111111111111112",gt="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var yt="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Po=5000n,$o=2039280n,Ro=37095705934669439343138083508754565189542113879843219016388785533085940283555n,B=57896044618658097711785492504343953926634992332820282019728792003956564819949n,dt=19681161376707505956807079304988542015446066515923890162744021073123829784752n,ft=e=>Er("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Mo=new Map([[ft("route"),{name:"route",prefixBytes:0}],[ft("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),j=(e,t)=>{if(e==null||e==="")throw new Error(`policy: ${t} required`);try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}},Fo=(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},re=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),G=e=>String(e||""),qo=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,Ge=e=>Er("sha256").update(e).digest("hex");function Je(e,t){try{let r=Buffer.from(wt.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function U(e){let t=e%B;return t>=0n?t:B+t}function X(e,t){let r=e;for(;t-- >0n;)r=r*r%B;return r}function Do(e){let r=e*e%B*e%B,n=X(r,2n)*r%B,o=X(n,1n)*e%B,i=X(o,5n)*o%B,s=X(i,10n)*i%B,a=X(s,20n)*s%B,c=X(a,40n)*a%B,u=X(c,80n)*c%B,d=X(u,80n)*c%B,l=X(d,10n)*i%B;return X(l,2n)*e%B}function Uo(e,t){let r=U(t*t*t),n=U(r*r*t),o=Do(e*n),i=U(e*r*o),s=U(t*i*i),a=i,c=U(i*dt),u=s===e,d=s===U(-e),l=s===U(-e*dt);return u&&(i=a),(d||l)&&(i=c),(U(i)&1n)===1n&&(i=U(-i)),!u&&!d?null:i}function jo(e){if(!e||e.length!==32)return!1;let t=0n;for(let o=31;o>=0;o--)t=(t<<8n)+BigInt(o===31?e[o]&127:e[o]);let r=U(t*t),n=Uo(U(r-1n),U(Ro*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function Wo(e,t){let r=Buffer.concat([...e,Je(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=Er("sha256").update(r).digest();if(jo(n))throw new Error("envelope: derived Solana program address is on curve");return wt.encode(n)}function br(e,t,r=gt){let n=[Je(e,"owner"),Je(r,"token program"),Je(t,"mint")];for(let o=255;o>=0;o--)try{return Wo([...n,Buffer.from([o])],yt)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function Ho(e,t){return(t.accountIndices||[]).map(r=>G(e.staticAccounts[r]))}function _e(e){return Buffer.from(e.data||[])}function Jo(e,t){return G(e.staticAccounts[t.programAddressIndex])}function Et(e,t){return Number(t)<e.header.numSignerAccounts}function Go(e,t){let r=e.header.numSignerAccounts,n=e.header.numReadonlySignerAccounts,o=e.header.numReadonlyNonSignerAccounts,i=e.staticAccounts.length;return Number(t)<r?Number(t)<r-n:Number(t)<i-o}function Be(e){return e.accountIndices||[]}function yr(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function pt(e,t){let r=Be(t).map(n=>{let o=Et(e,n)?"s":"n",i=Go(e,n)?"w":"r";return`${n}:${G(e.staticAccounts[n])}:${o}:${i}`});return Ge(Buffer.from(r.join(`
|
|
2
|
+
`)))}function mt(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function zo(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function Vo(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function Ko(e,t,r){let n=r.maxJupiterRoutePlanSteps===void 0?1:Number(r.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(t<1||t>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(r.jupiterRouteVariants)?r.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=r.jupiterRouteVariantPayloadBytes||{},s=0,a=0,c=[];for(let u=0;u<t;u++){if(s>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e[s++];if(!o.includes(d))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(d)))throw new Error("policy: Jupiter route variant payload size required");let l=Number(i[String(d)]);if(!Number.isSafeInteger(l)||l<0||l>16)throw new Error("policy: Jupiter route variant payload size invalid");if(s+l+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e.subarray(s,s+l);s+=l;let p=f.toString("hex"),m=r.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[s++],w=e[s++],h=e[s++];if(g<1||g>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(w!==u||h!==u+1)throw new Error("envelope: unsupported Jupiter route-plan token index");a+=g,c.push(Object.freeze({swapVariant:d,variantPayloadHex:p,percent:g,inputIndex:w,outputIndex:h}))}if(s!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(a!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function Yo(e,t){let r=_e({data:e}),n=r.subarray(0,8).toString("hex"),o=Mo.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,s=o.prefixBytes===1?r[8]:null;if(o.prefixBytes===1&&r.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let a=8+o.prefixBytes,c=a+4,u=r.length-i;if(u<=c)throw new Error("envelope: malformed Jupiter route payload");let d=Vo(r,a,"route plan length"),l=r.subarray(c,u),f=Ko(l,d,t);return Object.freeze({instruction:o.name,routeId:s,routePlanSteps:d,routePlan:f,routePlanHash:Ge(l),inAmount:mt(r,u,"in_amount"),quotedOutAmount:mt(r,u+8,"quoted_out_amount"),slippageBps:zo(r,u+16,"slippage_bps"),platformFeeBps:r[u+18],instructionHash:Ge(r)})}function Xo(e,t,r){let n=Ho(e,t),o=(i,s)=>{let a=n[i];if(!a)throw new Error(`envelope: Jupiter ${s} account missing`);return a};if(r.instruction==="route"){if(n.length<9)throw new Error("envelope: Jupiter route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),userTransferAuthority:o(1,"userTransferAuthority"),userSourceTokenAccount:o(2,"userSourceTokenAccount"),userDestinationTokenAccount:o(3,"userDestinationTokenAccount"),destinationTokenAccount:o(4,"destinationTokenAccount"),destinationMint:o(5,"destinationMint"),platformFeeAccount:o(6,"platformFeeAccount"),eventAuthority:o(7,"eventAuthority"),program:o(8,"program")}}if(r.instruction==="shared_accounts_route"){if(n.length<13)throw new Error("envelope: Jupiter shared route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),programAuthority:o(1,"programAuthority"),userTransferAuthority:o(2,"userTransferAuthority"),userSourceTokenAccount:o(3,"sourceTokenAccount"),programSourceTokenAccount:o(4,"programSourceTokenAccount"),programDestinationTokenAccount:o(5,"programDestinationTokenAccount"),userDestinationTokenAccount:o(6,"destinationTokenAccount"),sourceMint:o(7,"sourceMint"),destinationMint:o(8,"destinationMint"),platformFeeAccount:o(9,"platformFeeAccount"),token2022Program:o(10,"token2022Program"),eventAuthority:o(11,"eventAuthority"),program:o(12,"program")}}throw new Error("envelope: unsupported Jupiter account layout")}function ht(e,t){return e&&e!==t?e:null}function W(e,t,r){let n=G(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function Zo(e,t){let r=_e(e);if(r.length===5&&r[0]===2){let n=r.readUInt32LE(1),o=t.maxComputeUnits===void 0?14e5:Number(t.maxComputeUnits);if(!Number.isSafeInteger(o)||o<=0)throw new Error("policy: maxComputeUnits must be positive");if(n>o)throw new Error("policy: Jupiter compute unit limit exceeds cap");return 0n}throw r.length===9&&r[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function Qo(e,t,r,n,o,i){let s=_e(t);if(s.length!==1||s[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let a=Be(t);if(a.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=W(e,a[0],"ATA payer"),u=W(e,a[1],"ATA account"),d=W(e,a[2],"ATA owner"),l=W(e,a[3],"ATA mint"),f=W(e,a[4],"ATA system program"),p=W(e,a[5],"ATA token program");if(c!==r.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(d!==r.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(f!==xr)throw new Error("envelope: Jupiter ATA system program mismatch");if(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(u!==br(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:u,debit:i}}function ei(e,t,r,n,o){let i=Be(t),s=_e(t);if(i.length!==2||s.length!==12||s.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let a=W(e,i[0],"wrap payer"),c=W(e,i[1],"wrap target"),u=s.readBigUInt64LE(4);if(a!==r.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(u!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return u}function ri(e,t,r,n){let o=Be(t),i=_e(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||W(e,o[0],"syncNative account")!==n)throw new Error("envelope: Jupiter syncNative account mismatch");return{kind:"syncNative"}}if(i[0]===9){if(o.length!==3)throw new Error("envelope: malformed Jupiter closeAccount helper");let s=W(e,o[0],"closeAccount source"),a=W(e,o[1],"closeAccount destination"),c=W(e,o[2],"closeAccount authority");if(s!==n||a!==r.owner||c!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function ti(e,t,r,n,o,i,s){let a=br(t.owner,t.artifact.inputMint,s);if(o.userSourceTokenAccount!==a)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=j(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<$o)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let u=new Map,d=0n,l=!1,f=!1;for(let p of e.instructions){if(p===n)continue;let m=Jo(e,p);if(m===Bo)Zo(p,r);else if(m===yt){let{ata:g,debit:w}=Qo(e,p,t,t.artifact,s,c);u.set(g,w)}else if(m===xr)d+=ei(e,p,t,a,i);else if(m===s){let g=ri(e,p,t,a);g.kind==="syncNative"&&(l=!0),g.kind==="closeAccount"&&(f=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(d>0n&&(!l||!f))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(d!==0n&&d!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...u.values()].reduce((p,m)=>p+m,0n)}function ni(e){let t;try{t=_o().decode(Fo(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 oi(e,t,r){if(e.header.numSignerAccounts!==1||G(e.staticAccounts[0])!==t.owner||!re(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=G(e.staticAccounts[o.programAddressIndex]);if(!i||!re(i,r.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function ii(e,t,r){let n=j(r.lamportsPerSignature,"lamportsPerSignature");if(n<Po)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:j(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),s=i*n,a=i*o;if(t.exactFeeLamports!==void 0){let u=j(t.exactFeeLamports,"exactFeeLamports");if(u<s)throw new Error("policy: Solana exact fee below the base signature fee");if(u>a)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=a;if(c>j(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function si(e,t,r,n){let o=0n,i=!1;for(let s of e.instructions){if(G(e.staticAccounts[s.programAddressIndex])!==xr)throw new Error("envelope: unsupported Solana program decoder");let c=s.accountIndices||[];if(c.length!==2||G(e.staticAccounts[c[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let u=G(e.staticAccounts[c[1]]);if(u!==t.destination||!re(u,r.destinations))throw new Error("envelope: Solana destination mismatch");let d=Buffer.from(s.data||[]);if(d.length!==12||d.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=d.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function ai(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!==Co)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!re(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=qo(r);if(!re(o.inputMint,i)||!re(o.outputMint,i))throw new Error("policy: Solana token not allowed");let s=j(o.inAmount,"inAmount"),a=j(o.outAmount,"outAmount"),c=j(o.otherAmountThreshold,"otherAmountThreshold");if(s<=0n||s>j(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(s>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(a<=0n||c<=0n||c>a)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let u=G(o.jupiterProgram);if(!u||!re(u,r.programs)||!n.includes(u))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(v=>G(e.staticAccounts[v.programAddressIndex])===u);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=d[0],f=Yo(l.data,r);if(f.instruction==="shared_accounts_route"){let v=Array.isArray(r.jupiterSharedRouteIds)?r.jupiterSharedRouteIds.map(Number):[];if(!v.length)throw new Error("policy: Jupiter shared route id allowlist required");if(!v.includes(Number(f.routeId)))throw new Error("policy: Jupiter shared route id not allowed")}else if(f.routeId!=null)throw new Error("envelope: unexpected Jupiter shared route id");if(!yr(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(f.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(f.inAmount!==s)throw new Error("envelope: Jupiter route in_amount mismatch");if(f.quotedOutAmount!==a)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(f.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let 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=Xo(e,l,f),g=Be(l),w=f.instruction==="shared_accounts_route"?2:1;if(!Et(e,g[w]))throw new Error("envelope: Jupiter transfer authority must be signer");if(m.program!==u)throw new Error("envelope: Jupiter program account mismatch");if(m.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(m.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(m.sourceMint!==void 0&&m.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let h=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[gt];if(!re(m.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let x=br(t.owner,o.outputMint,m.tokenProgram);if(m.userDestinationTokenAccount!==x)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=ht(m.destinationTokenAccount,u);if(E&&E!==x)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(ht(m.platformFeeAccount,u))throw new Error("policy: Jupiter platform fee account not allowed");if(!yr(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(pt(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let b=Ge(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,pt(e,l)].join(`
|
|
3
|
+
`)));if(!yr(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(b))throw new Error("policy: Jupiter route review hash not allowed");let T=ti(e,t,r,l,m,s,m.tokenProgram),O=s+T;if(O>j(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:O,programs:n}}function Sr(e,t){if(e.action!=="transfer"&&e.action!=="swap")throw new Error("envelope: Solana decoder requires transfer or swap action");let r=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(r||{}).some(c=>!n.includes(c)))throw new Error("envelope: unexpected Solana artifact field");if(!re(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=ni(r),i=oi(o,e,t),s=e.action==="transfer"?si(o,e,t,i):ai(o,e,t,i),a=ii(o,r,t);return Object.freeze({unit:"lamports",value:s.value.toString(),notional:(s.value+a).toString(),fee:a.toString(),programs:Object.freeze(s.programs)})}function Ar(e,t){let{unit:r,value:n,notional:o,fee:i}=Sr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}var ci=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=ci+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var ui=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),li=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),di=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"}),fi=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"}),oe=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function pi(e,t){let r=e.toString().padStart(t+1,"0");if(t===0)return r;let n=r.slice(0,-t),o=r.slice(-t).replace(/0+$/,"");return o?`${n}.${o}`:n}function xt(e,t){let r=k(e,`hl: ${t}`);if(!/^\d+(?:\.\d+)?$/.test(r))throw new Error(`hl: ${t} must be a positive decimal`);let[n,o=""]=r.split("."),i=BigInt(n+o);if(i<=0n)throw new Error(`hl: ${t} must be positive`);return{raw:i,decimals:o.length}}function Z(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=>Z(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)}:${Z(e[n],t)}`).join(",")}}`}function mi(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)||Z(r,"declared order type")!==Z({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(Z(r,"declared order type")!==Z({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||Z(r,"declared order type")!==Z({trigger:{isMarket:n.isMarket,triggerPx:o,tpsl:n.tpsl}},"expected order type"))throw new Error("hl: trigger order type must match its wire shape")}function hi(e,t,r){let n=xt(e.s,"signed size"),o=xt(e.p,"signed price"),i=n.decimals+o.decimals,s=n.raw*o.raw,a=_(t.notionalUsd,i,"hl: notionalUsd");if(a<=0n||s!==a)throw new Error("hl: signed notional must match");let c=_(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>c)throw new Error("hl: notional exceeds cap")}function wi(e,t){let r=e.action.builder;if(r==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: signed order builder must be structured");let n=oe(r.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(M(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(a=>String(a).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=ee(r.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let s=_(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function bt(e,t,r){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(t.side==="buy"))throw new Error("hl: signed side must match exactly");if(k(e.s,"hl: signed size")!==k(t.size,"hl: size"))throw new Error("hl: signed size must match");if(k(e.p,"hl: signed price")!==k(t.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof t.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==t.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(Z(e.t,"signed order type")!==Z(t.orderWire,"declared order type"))throw new Error("hl: signed order type must match declared order type");let n=Object.prototype.hasOwnProperty.call(e,"c");if(t.clientOrderId==null){if(n)throw new Error("hl: undeclared signed client order id")}else if(!n||typeof e.c!="string"||e.c!==t.clientOrderId)throw new Error("hl: signed client order id must match")}function St(e,t,r,n,o){if(!Number.isSafeInteger(e.a)||e.a!==r)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(t.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(k(e.s,"hl: bracket protection size")!==k(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(k(e.p,"hl: bracket protection price")!==k(n,"hl: protection price"))throw new Error("hl: bracket protection price must match");if(e.r!==!0)throw new Error("hl: bracket protection must be reduce-only");let i=e.t?.trigger;if(!i||i.isMarket!==!0||i.tpsl!==o)throw new Error("hl: bracket protection trigger must match");if(k(i.triggerPx,"hl: triggerPx")!==k(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function gi(e){let t=String(e||"").replace(/\/$/,"");if(!ui.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function Ir(e){return vr(e)!=null}function yi(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(Ir(r)){if(t.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(n.includes(r)||n.includes("#*")||n.includes("*")||n.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(n.length&&!n.includes(r)&&!n.includes("*"))throw new Error("hl: coin not allowed");return!0}function Ei(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(s=>{if(typeof s=="string"){let[a,c]=String(s).split(":");return a===e&&Number(c)===t}return String(s?.coin)===e&&Number(s?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(Ir(e)){let i=Array.isArray(r.coins)?r.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0)return!0;throw new Error("hl: restricted coin policy requires hlMarkets pairs")}let o=Array.isArray(r.coins)?r.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function ie(e,t){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("hl: structured artifact required");let n=oe(r.kind,"kind",48),o=di[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=gi(r.submitTo);if(Object.prototype.hasOwnProperty.call(r,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let s=Number(r.nonce);if(!Number.isSafeInteger(s)||s<=0)throw new Error("hl: nonce must be a positive integer");if(!r.action||typeof r.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(r.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(r.action.type!==fi[n])throw new Error("hl: action type must match kind");let a=r.notionalUsd??0;if(li.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let c=oe(r.coin,"coin",64),u=r.assetId??r.assetIndex;if(!Number.isSafeInteger(u)||u<0)throw new Error("hl: assetId required");if(n==="hip4-order"||u>=1e8){let d=vr(c);if(!d||d.coin!==c)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==u)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(yi(c,t),Ei(c,u,t),n==="hip4-order"&&!Ir(c))throw new Error("hl: HIP-4 orders must use an outcome coin");if(n==="perp-order"||n==="hip3-order"||n==="hip4-order"||n==="perp-bracket"){if(r.side!=="buy"&&r.side!=="sell")throw new Error("hl: side must be buy or sell");if(r.action.type!=="order"||!Array.isArray(r.action.orders))throw new Error("hl: signed orders are required");mi(r);let d=r.action.orders;if(n==="perp-bracket"){let l=r.takeProfitPx,f=r.stopLossPx,p=1+(l==null?0:1)+(f==null?0:1);if(p<2||d.length!==p||r.grouping!=="normalTpsl"||r.action.grouping!==r.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");bt(d[0],r,u);let m=1;l!=null&&St(d[m++],r,u,l,"tp"),f!=null&&St(d[m],r,u,f,"sl")}else{if(d.length!==1)throw new Error("hl: exactly one signed order is required");if(r.grouping!=="na"||r.action.grouping!==r.grouping)throw new Error("hl: signed grouping must match declared grouping");bt(d[0],r,u)}hi(d[0],r,t),wi(r,t),a=k(r.notionalUsd,"hl: notionalUsd")}if(n==="perp-leverage"){let d=r.leverage;if(!Number.isSafeInteger(d)||d<1)throw new Error("hl: leverage must be a positive integer");let l=t.maxLeverage==null?50:t.maxLeverage;if(typeof l!="number"||!Number.isSafeInteger(l)||l<1)throw new Error("hl: maxLeverage must be a positive integer");if(d>l)throw new Error("hl: leverage exceeds cap")}if(n==="perp-cancel"){let d=r.action.cancels;if(!Array.isArray(d)||d.length!==1)throw new Error("hl: exactly one cancel is required");if(!Number.isSafeInteger(d[0].a)||d[0].a!==u)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(r.orderId)||r.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(d[0].o)||d[0].o!==r.orderId)throw new Error("hl: signed cancel order id must match")}if(n==="perp-leverage"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==u)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(r.action.leverage)||r.action.leverage!==r.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(r.marginMode))throw new Error("hl: declared margin mode required");let d=r.marginMode==="cross";if(typeof r.action.isCross!="boolean"||r.action.isCross!==d)throw new Error("hl: signed isCross must match declared margin mode")}if(n==="perp-isolated-margin"){if(!Number.isSafeInteger(r.action.asset)||r.action.asset!==u)throw new Error("hl: signed margin asset must match assetId");let d=oe(r.usd,"margin usd",64),l=_(d,6,"hl: margin usd");if(ee(r.action.ntli,"hl: signed margin ntli")!==l)throw new Error("hl: signed margin amount must match usd");if(typeof r.isBuy!="boolean"||r.action.isBuy!==r.isBuy)throw new Error("hl: signed margin isBuy must match");let p=_(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),m=l<0n?-l:l;if(m>p)throw new Error("hl: margin notional exceeds cap");a=pi(m,6)}}if(n==="builder-fee-approval"){let c=oe(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(oe(r.action.builder,"signed builder",42).toLowerCase()!==c)throw new Error("hl: signed builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(m=>String(m).toLowerCase()):[]).includes(c))throw new Error("hl: builder not allowed");let d=oe(r.maxFeeRate,"maxFeeRate",32);if(oe(r.action.maxFeeRate,"signed maxFeeRate",32)!==d)throw new Error("hl: signed builder fee must match");if(!/^\d+(?:\.\d+)?%$/.test(d))throw new Error("hl: builder fee rate must be a percent");let l=_(d.slice(0,-1),12,"hl: builder fee percent"),f=_(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(f<0n||l*100n>f)throw new Error("hl: builder fee exceeds cap");if(Number(r.action.nonce)!==s)throw new Error("hl: signed builder nonce must match");let 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(a??r.action.wei??0),notional:String(a??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??a??0),coin:r.coin||null,submitTo:i})}import{createHmac as xi}from"node:crypto";var we="0x"+"00".repeat(32);function Tr(e={}){let t=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,r=e.polyApiSecret||process.env.POLYMARKET_API_SECRET||process.env.POLY_API_SECRET,n=e.polyPassphrase||process.env.POLYMARKET_API_PASSPHRASE||process.env.POLY_API_PASSPHRASE;if(!t||!r||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(t),secret:String(r),passphrase:String(n)}}function At({creds:e,address:t,method:r,path:n,body:o="",nowSec:i}={}){if(!e?.key||!e?.secret||!e?.passphrase)throw new Error("poly: L2 credentials required");if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("poly: L2 address required");let s=String(i??Math.floor(Date.now()/1e3)),a=String(r||"").toUpperCase(),c=String(n||"");if(a!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let u=s+a+c+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),f=xi("sha256",l).update(u).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:f,POLY_TIMESTAMP:s,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function bi(e,t){if(e.side!==0&&e.side!==1)throw new Error("poly: side must be BUY or SELL");let r=e.side===0?"BUY":"SELL";if(t&&t!==r)throw new Error("poly: side mismatch");return r}function vt(e,t){let r=BigInt(k(e.makerAmount,"poly: makerAmount")),n=BigInt(k(e.takerAmount,"poly: takerAmount"));if(r<=0n||n<=0n)throw new Error("poly: order amounts must be positive integer micro-units");return Number(t==="BUY"?r:n)/1e6}function Si(e){let t=typeof e=="bigint"?e.toString(10):k(e,"poly: salt");if(!/^[1-9][0-9]*$/.test(t))throw new Error("poly: salt must be a positive integer");let r=BigInt(t);if(r>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("poly: salt exceeds safe integer");return Number(r)}function It({message:e,side:t,signature:r,orderType:n="GTC",apiKey:o}={}){if(!e||typeof e!="object")throw new Error("poly: CLOB v2 message required");if(!String(r||"").startsWith("0x"))throw new Error("poly: EIP-712 signature required");if(n!=="GTC")throw new Error("poly: only GTC is public");if(!o)throw new Error("poly: CLOB owner must be the L2 API key");let i=bi(e,t);if(M(e.metadata||we,"poly: metadata").toLowerCase()!==we)throw new Error("poly: metadata must be zero");if(M(e.builder||we,"poly: builder").toLowerCase()!==we)throw new Error("poly: builder must be zero");let s=Si(e.salt);return{deferExec:!1,order:{builder:we,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:we,salt:String(s),side:i,signature:r,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var Ai=new Set(["https://clob.polymarket.com/order"]),Ce=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Wc=Object.freeze(Ce.map(e=>e[0])),vi=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),Ii="0xe111180000d2663c0091e4f400237545b87b996b",Ti="0xe2222d279d744050d28e00520010520000310f59",Tt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function kt(e){let t=String(e||"").replace(/\/$/,"");if(!Ai.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function Ot(e){let t=M(e,"poly: exchange").toLowerCase();if(!vi.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function se(e,t){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("poly: structured artifact required");let n=Tt(r.kind,"kind",48);if(n!=="poly-order")throw new Error("poly: unsupported Polymarket kind");if(e.action!=="order")throw new Error("poly: surface/action/kind mismatch");if(M(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(kt(r.submitTo),r.chainId!==137)throw new Error("poly: chainId must be Polygon 137");let o=r.domain;if(!o||typeof o!="object")throw new Error("poly: EIP-712 domain required");if(o.name!=="Polymarket CTF Exchange"||o.version!=="2"||o.chainId!==137)throw new Error("poly: EIP-712 domain must be official CTF Exchange v2 on Polygon");if(Ot(o.verifyingContract),Ot(r.exchange),M(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==M(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?Ti:Ii;if(M(r.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let s=r.message||r.value;if(!s||typeof s!="object")throw new Error("poly: signed order message required");let a=r.types?.Order;if(!Array.isArray(a)||a.length!==Ce.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let w=0;w<Ce.length;w+=1)if(a[w]?.name!==Ce[w][0]||a[w]?.type!==Ce[w][1])throw new Error("poly: EIP-712 Order type must be official CLOB v2");if((r.orderType||"GTC")!=="GTC")throw new Error("poly: only GTC is public");let c=String(e.owner||"").toLowerCase();if(M(s.maker,"poly: maker").toLowerCase()!==c)throw new Error("poly: maker must equal owner");if(M(s.signer,"poly: signer").toLowerCase()!==c)throw new Error("poly: signer must equal owner");if(s.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof s.builder!="string"||s.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(s.side!==0&&s.side!==1)throw new Error("poly: side must be BUY or SELL");let u=Tt(r.tokenId,"tokenId",80);if(M(s.tokenId,"poly: tokenId")!==u)throw new Error("poly: tokenId mismatch");let d=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(d.length&&!d.includes(u)&&!d.includes("*"))throw new Error("poly: tokenId not allowed");let l=Number(s.side)===0?"BUY":"SELL";if(r.side&&r.side!==l)throw new Error("poly: side mismatch");let f=vt(s,l),p=_(r.notionalUsdc,6,"poly: notionalUsdc"),m=_(f,6,"poly: computed notional");if(p!==m)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let g=t.maxNotionalUsd??t.maxNotionalUsdc;if(g!=null){let w=_(g,6,"poly: maxNotionalUsd");if(m>w)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:String(f),notional:String(f),fee:"0",kind:n,tokenId:u,side:l,submitTo:kt(r.submitTo)})}var ki=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),kr=14,Lt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function ge(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function Or(e){let t=String(e||"").replace(/\/$/,"");if(!ki.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function ae(e,t={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("lighter: structured artifact required");let n=Lt(r.kind,"kind",48);if(n!=="lighter-order")throw new Error("lighter: unsupported Lighter kind");if(e.action!=="order")throw new Error("lighter: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="lighter")throw new Error("lighter: destination must be lighter");let o=Or(r.submitTo),i=r.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let s=Number(ee(r.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(s)||s<0)throw new Error("lighter: accountIndex required");let a=Number(ee(r.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: clientOrderIndex required");ge(r.orderType,0,"orderType"),ge(r.timeInForce,1,"timeInForce"),ge(r.reduceOnly,0,"reduceOnly"),ge(r.triggerPrice,0,"triggerPrice"),ge(r.orderExpiry,-1,"orderExpiry");let c=Lt(r.symbol||r.coin,"symbol",32),u=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(u.length&&!u.includes(c)&&!u.includes(String(i))&&!u.includes("*"))throw new Error("lighter: market not allowed");if(r.side!=="buy"&&r.side!=="sell")throw new Error("lighter: side must be buy or sell");let d=fr(r.baseAmount,"lighter: baseAmount"),l=fr(r.price,"lighter: price");if(d>BigInt(Number.MAX_SAFE_INTEGER)||l>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("lighter: baseAmount and price must be safe integers");let f=Number(d),p=Number(l),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 w=m+g,h=d*l,x=_(r.notionalUsd,w,"lighter: notionalUsd");if(x<=0n)throw new Error("lighter: notionalUsd required");if(h!==x)throw new Error("lighter: notionalUsd must match size and price");let E=_(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,w,"lighter: maxNotionalUsd");if(h>E)throw new Error("lighter: notional exceeds cap");let b=k(r.notionalUsd,"lighter: notionalUsd");return ge(r.txType,kr,"txType"),Object.freeze({unit:"usd",value:String(b),notional:String(b),fee:"0",kind:n,symbol:c,marketIndex:i,side:r.side,baseAmount:f,price:p,submitTo:o,actionType:"create-order",amount:String(b)})}var Ct=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var Nr=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0,delegate:0}),Li=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Pt=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"}}),Ni=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),Nt=new Oi(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),_i=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}});var ze=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},S=(e,t)=>{try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`envelope: ${t} must be a non-negative integer`)}},_t=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Bi=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},C=(e,t,r)=>{if(!Bi(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Lr=(e,t,r)=>{Array.isArray(t)&&t.length&&C(e,t,r)},H=(e,t)=>{let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`envelope: ${t} must be a 20-byte address`);return r},le=e=>String(e||"0x").slice(0,10).toLowerCase(),$t=e=>S(e.gasLimit,"gasLimit")*S(e.maxFeePerGas??e.gasPrice,"feePerGas")+S(e.l1FeeWei??0,"l1FeeWei")+S(e.operatorFeeWei??0,"operatorFeeWei");function ye(e,t,r,{dynamicTail:n=!1}={}){let o=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(o)||o.length<10+t*64)throw new Error(`envelope: malformed ${r} calldata`);if(!n&&o.length!==10+t*64)throw new Error(`envelope: malformed ${r} calldata`);return{hex:o,word:i=>o.slice(10+i*64,10+(i+1)*64)}}function P(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function z(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function Ci(e){if(le(e)!=="0x095ea7b3")return null;let t=ye(e,2,"approval");return{kind:"approval",spender:P(t.word(0),"approval spender"),amount:z(t.word(1),"approval amount")}}function Rt(e,t){let r=t==="router02-exact-input-single"?7:8,n=ye(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:P(n.word(0),"input token"),outputToken:P(n.word(1),"output token"),recipient:P(n.word(3),"recipient"),amountIn:z(n.word(o),"amountIn"),minimumOut:z(n.word(o+1),"amountOutMinimum")}}function Pi(e){let t=ye(e,12,"Across depositV3",{dynamicTail:!0}),r=z(t.word(11),"message offset");if(r!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let n=10+Number(r)*2;if(t.hex.length<n+64)throw new Error("envelope: malformed Across depositV3 message");let o=Number(BigInt(`0x${t.hex.slice(n,n+64)}`));if(!Number.isSafeInteger(o))throw new Error("envelope: malformed Across depositV3 message length");let i=Math.ceil(o/32)*64;if(t.hex.length!==n+64+i)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:P(t.word(0),"depositor"),recipient:P(t.word(1),"recipient"),inputToken:P(t.word(2),"input token"),outputToken:P(t.word(3),"output token"),amountIn:z(t.word(4),"inputAmount"),minimumOut:z(t.word(5),"outputAmount"),destinationChainId:z(t.word(6),"destinationChainId")}}function $i(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 Bt(e,{hasDeadline:t}){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<74)throw new Error("envelope: malformed exactInput calldata");let n=[];for(let w=10;w+64<=r.length;w+=64)n.push(r.slice(w,w+64));let o=(w,h)=>{if(!n[w])throw new Error(`envelope: malformed ${h}`);return BigInt(`0x${n[w]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let s=i/32,a=Number(o(s,"path offset")),c=n[s+1],u=o(s+(t?3:2),"amountIn"),d=o(s+(t?4:3),"amountOutMinimum"),l=s+a/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let f=Number(o(l,"path length")),p=r.slice(10+(l+1)*64,10+(l+1)*64+f*2),{inputToken:m,outputToken:g}=$i(`0x${p}`);return{kind:"action",action:"swap",inputToken:m,outputToken:g,recipient:P(c,"recipient"),amountIn:u,minimumOut:d}}function Ri(e){let t=ye(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:P(t.word(0),"input token"),outputToken:P(t.word(1),"output token"),recipient:P(t.word(3),"recipient"),amountIn:z(t.word(5),"amountIn"),minimumOut:z(t.word(6),"amountOutMinimum")}}function Mi(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let f=10;f+64<=t.length;f+=64)r.push(t.slice(f,f+64));let n=Number(BigInt(`0x${r[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${r[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let s=Number(BigInt(`0x${r[o+1]}`)),a=o+1+s/32,c=Number(BigInt(`0x${r[a]}`)),d=`0x${t.slice(10+(a+1)*64,10+(a+1)*64+c*2)}`,l=le(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Rt(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function Fi(e,t){let r=le(e),n=Pt[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{...Rt(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...Bt(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...Bt(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...Mi(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Ri(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...Pi(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function qi(e){let t=ye(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:P(t.word(0),"mint NFT contract"),feeRecipient:P(t.word(1),"mint fee recipient"),recipient:P(t.word(2),"mint recipient"),quantity:z(t.word(3),"mint quantity")}}function Di(e){let t;try{t=Nt.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(Nt.encodeFunctionData("mintAllowList",[t[0],t[1],t[2],t[3],r,n]).toLowerCase()!==String(e).toLowerCase())throw new Error("envelope: SeaDrop allowlist calldata must be canonical");let i=BigInt(r.startTime),s=BigInt(r.endTime);if(s<=i)throw new Error("envelope: SeaDrop allowlist stage time range is invalid");let a=BigInt(t[3]);if(BigInt(r.maxTotalMintableByWallet)<a)throw new Error("envelope: SeaDrop allowlist wallet cap is below quantity");return{kind:"mint",action:"mint",mintType:"allowlist",contract:H(t[0],"mint NFT contract"),feeRecipient:H(t[1],"mint fee recipient"),recipient:H(t[2],"mint recipient"),quantity:a,mintPrice:BigInt(r.mintPrice),startTime:i,endTime:s,dropStageIndex:BigInt(r.dropStageIndex),proof:n}}function Ui(e,t){let r=le(e);if(String(t).toLowerCase()==="nft-mint")return ji(e);let n=Ni[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{...qi(e),selector:r,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...Di(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function ji(e){let t=le(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=_i[t];if(!r)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(r.layout==="mint-no-args")return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:1n};if(r.layout==="mint-quantity"){let n=ye(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:z(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function Ve(e){let t=e?.artifact;if(Array.isArray(t?.transactions))return t.transactions;if(t?.transaction&&typeof t.transaction=="object")return[t.transaction];if(t?.data)return[t];throw new Error("envelope: ordered EVM transaction batch required")}function Mt(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let s=H(e.owner,"owner"),a=e.artifact,c=Number(a?.chainId??Ve(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(C(c,t.chains,"chain"),a?.owner!==void 0&&H(a.owner,"batch owner")!==s)throw new Error("envelope: explicit batch owner mismatch");let u=Ve(e);if(!u.length||u.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,l=0n,f=0n;for(let p of u){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(H(p.from,"transaction owner")!==s)throw new Error("envelope: every batch leg must use the same owner");if(C(le(p.data),t.selectors,"selector"),d+=S(p.value??0,"value"),l+=S(p.gasLimit,"gasLimit"),f+=$t(p),Y(c)&&(p.l1FeeWei===void 0||p.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>S(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>S(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(f>S(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:u,chainId:c,owner:s,totalValue:d,totalGas:l,totalFee:f}}function Ft(e,t,{nowMs:r=Date.now(),routeAttestationSecret:n}={}){let o=String(e?.surface||"");if(o!=="evm-swap"&&o!=="evm-bridge")throw new Error("envelope: strict EVM swap/bridge surface required");let i=ze(e.provider,"provider",64).toLowerCase();C(i,t.providers,"provider");let s=Mt(e,t,o,{nowMs:r}),a=[],c=-1;for(let m=0;m<s.transactions.length;m++){let g=s.transactions[m],w=Ci(g.data),h;if(w){if(c!==-1)throw new Error("envelope: approval must be before action");if(S(g.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let b=H(g.to,"approval token");if(C(b,t.tokens,"token"),C(w.spender,t.spenders,"spender"),w.amount>S(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...w,token:b,index:m}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");C(g.to,t.destinations,"destination"),h={...Fi(g.data,i),target:H(g.to,"action target"),index:m},c=m}let x=S(g.value??0,"value"),E=S(g.gasLimit,"gasLimit");a.push({...h,value:x,gas:E,fee:$t(g)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let u=a[c],d=o==="evm-swap"?"swap":"bridge";if(u.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if(H(e.destination,"destination")!==u.target)throw new Error("envelope: destination must equal decoded action target");if(u.recipient!==s.owner)throw new Error("envelope: decoded recipient must equal owner");if(u.depositor&&u.depositor!==s.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(C(u.inputToken,t.tokens,"input token"),C(u.outputToken,t.tokens,"output token"),u.amountIn<=0n||u.amountIn>S(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(u.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(dr(e.autoSlippage,{nowMs:r,chainId:s.chainId,venue:i,tx:s.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(u.minimumOut!==S(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(u.action==="bridge"&&S(e.toChainId,"toChainId")!==u.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=a.filter(m=>m.kind==="approval");if(!new Set([...Li,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(m=>String(m).toLowerCase()):[]]).has(u.inputToken))throw new Error("envelope: strict local signer swap/bridge requires native input token; use wallet signing for token-unit rails");if(l.length)throw new Error("envelope: native-value action must not include token approval");if(u.value!==u.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let p=Object.freeze({quoteAmountOut:S(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:S(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...s,decoded:a,action:u,provider:i,authenticatedQuote:p}}function qt(e,t,{nowMs:r=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint action");let n=ze(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Lr(n,t.providers,"provider");let o=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;o?.oraclePrepared===!0&&it(o,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"});let i=Mt(e,t,"evm-nft",{nowMs:r});if(i.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let s=i.transactions[0],a=le(s.data);C(a,t.selectors,"selector"),C(s.to,t.destinations,"destination");let c=Ui(s.data,n),u=H(e.contract??e.artifact?.contract,"NFT contract");if(Lr(u,t.nftContracts,"NFT contract"),(c.contract||H(s.to,"NFT contract"))!==u)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==i.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&Lr(c.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let l=S(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>S(t.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(c.quantity!==l)throw new Error("envelope: mint calldata quantity mismatch");let f=S(e.totalWei??e.artifact?.totalWei,"totalWei");if(i.totalValue!==f)throw new Error("envelope: mint value does not match declared totalWei");if(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*l!==f)throw new Error("envelope: SeaDrop allowlist price does not match declared totalWei")}if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&S(e.priceWei??e.artifact.priceWei,"priceWei")*l!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>S(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...i,provider:n,decoded:[{...c,target:H(s.to,"mint target"),value:i.totalValue,gas:i.totalGas,fee:i.totalFee}]}}function Wi(e,{localsWaiver:t=!1}={}){if(!(e in Nr))throw new Error("fee: unknown action");return t?0:Nr[e]}function Ke(e,t,{nowMs:r=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:s=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let a=ze(e.surface,"surface",16);if(!Ct.has(a))throw new Error("envelope: unsupported public surface");let c=ze(e.action,"action",32);C(a,t.surfaces,"surface"),C(c,t.actions,"action"),C(e.owner,t.owners,"owner"),C(e.destination,t.destinations,"destination");let u=_t(t.maxTtlMs,"maxTtlMs"),d=_t(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>u)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>d)throw new Error("policy: slippage exceeds cap");let l=e.artifact;if(!l||typeof l!="object"||Array.isArray(l))throw new Error("envelope: structured artifact required");if(a==="evm-swap"||a==="evm-bridge")Ft(e,t,{nowMs:r,routeAttestationSecret:o});else if(a==="evm-nft")qt(e,t,{nowMs:r});else if(a==="evm"){if(!["transfer","approve"].includes(c))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(String(l.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(String(l.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: artifact from mismatch with owner");He({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:s});let m=String(l.data||"0x").toLowerCase(),g=S(l.value,"EVM value");if(m==="0x"){if(g===0n)throw new Error("envelope: native EVM transfer value required")}else if(K(m)){if(g!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else a==="btc"?gr(e,t):a==="sol"?Ar(e,t):a==="hl"?ie(e,t):a==="poly"?se(e,t):a==="lighter"&&ae(e,t);let f=Number(e.fee?.oracleFeeBps)===0&&Nr[c]!==0;if(e.fee?.waiver||f&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(f&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let p=Wi(c,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==p)throw new Error("fee: final artifact fee mismatch");return!0}var _r=Object.freeze([...Ct]),nu=Object.freeze({...Pt});function Br(e,t){if(e.surface==="hl")return ie(e,t);if(e.surface==="poly")return se(e,t);if(e.surface==="lighter")return ae(e,t);if(e.surface==="btc")return gr(e,t);if(e.surface==="sol")return Ar(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Ft(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=qt(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(String(e.surface).startsWith("evm")){let r=S(e.artifact?.value,"EVM value"),n=S(e.artifact?.gasLimit,"EVM gasLimit"),o=S(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+S(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+S(e.artifact?.operatorFeeWei??0,"EVM operatorFeeWei");return Object.freeze({unit:"wei",value:r.toString(),notional:(r+i).toString(),fee:i.toString()})}throw new Error("envelope: unsupported public surface")}function Dt(e={}){let t={};for(let r of _r){let n=e[r];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${r} requires simulate, sign, and broadcast functions`);t[r]=Object.freeze({simulate:(o,i)=>n.simulate(structuredClone(o),structuredClone(i)),sign:(o,i)=>n.sign(structuredClone(o),structuredClone(i)),broadcast:(o,i,s)=>n.broadcast(o,structuredClone(i),structuredClone(s))})}}return Object.freeze(t)}function Ye(e,t){let r=e?.surface||"evm",n=t?.[r];if(!n)throw new Error(`adapter: ${r} is not configured on this self-host`);return n}import{createHash as zt}from"node:crypto";import{ed25519 as es}from"@noble/curves/ed25519.js";import{base58 as Xt}from"@scure/base";import{RawTx as Rr,SigHash as de,Transaction as Mr}from"@scure/btc-signer";import{Transaction as Fr,keccak256 as Vt,verifyTypedData as Kt}from"ethers";import{encode as Hi}from"@msgpack/msgpack";import{keccak256 as Ji,verifyTypedData as Gi}from"ethers";var Ee=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Cr=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Ut(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 zi(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Hi(e)),Ut(t)];if(r){let s=String(r).replace(/^0x/i,"");if(!/^[0-9a-fA-F]{40}$/.test(s))throw new Error("hl-l1: vaultAddress must be a 20-byte address");i.push(Buffer.from([1]),Buffer.from(s,"hex"))}else i.push(Buffer.from([0]));return n!=null&&i.push(Buffer.from([0]),Ut(n)),Ji(Buffer.concat(i))}function Pr(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:zi(e,t,{vaultAddress:n,expiresAfter:o})}}function jt(e){let t=e?.typedData;if(t==null)return null;if(typeof t!="object")throw new Error("hl-l1: typedData must match the validated action");if(Object.prototype.hasOwnProperty.call(e,"vaultAddress"))throw new Error("hl-l1: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(e,"expiresAfter"))throw new Error("hl-l1: expiresAfter is not public");let r=Pr(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==Ee.name||String(t.domain?.version)!==Ee.version||Number(t.domain?.chainId)!==Ee.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(Ee.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(Cr.Agent))throw new Error("hl-l1: typedData types must be Hyperliquid Agent");if(t.message?.source!==r.source||String(t.message?.connectionId||"").toLowerCase()!==String(r.connectionId).toLowerCase())throw new Error("hl-l1: typedData message must hash the validated action");return r}async function Wt({wallet:e,action:t,nonce:r,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let s=Pr(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(Ee,Cr,s)}function Ht({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:s=null}){try{let a=Pr(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:s}),c=Gi(Ee,Cr,a,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var Vi=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function $r(e){if(e!=null){if(typeof e=="function")throw new Error("lighter: signed tx_info cannot include functions");if(typeof e=="object"){if(typeof e.toJSON=="function")throw new Error("lighter: signed tx_info cannot define toJSON");if(Array.isArray(e)){for(let t of e)$r(t);return}for(let t of Object.values(e))$r(t)}}}function Ki(e){if(typeof e=="string"){if(!e.startsWith("{"))throw new Error("lighter: official signed tx_info JSON required");let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("lighter: official signed tx_info JSON required");return t}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("lighter: official signed tx_info JSON required");return $r(e),JSON.parse(JSON.stringify(e))}function Xe(e,t){let r=typeof e=="bigint"?e.toString(10):String(e??"").trim();if(!/^(0|[1-9][0-9]*)$/.test(r))throw new Error(`lighter: ${t} must be an integer`);let n=BigInt(r);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`lighter: ${t} exceeds safe integer`);return n}function Yi(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 Jt(e,t,{signed:r=!1}={}){if(typeof e!="number"||!Number.isSafeInteger(e)||!r&&e<0)throw new Error(`lighter: signed ${t} must be an exact numeric integer`);return e}function be(e,t,r,n={}){let o=t.filter(s=>e[s]!==void 0&&e[s]!==null);if(o.length===0)throw new Error(`lighter: ${r} required`);let i=o.map(s=>Jt(e[s],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function Xi(e,t,r){let n=t.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length===0)throw new Error(`lighter: ${r} required`);let o=n.map(i=>String(e[i]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${r}`);return e[n[0]]}function xe(e,t,r,n){let o=be(e,t,n);if(BigInt(o)!==Xe(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Zi(e,t,r,n){let o=be(e,t,n,{signed:!0});if(BigInt(o)!==Yi(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Qi(e){let t={};for(let[r,n]of Vi.entries()){let o=n.filter(s=>e[s]!==void 0&&e[s]!==null);if(!o.length)continue;let i=o.map(s=>{let a=e[s];if(r<3)return Jt(a,n[0]);if(typeof a!="string"||a.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return a});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);t[n[0]]=i[0]}return t}function Pe(e,t){let r=Ki(t),n=xe(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=xe(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=xe(r,["Type","type"],e.orderType,"Type"),s=xe(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),a=xe(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),c=xe(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),u=Zi(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=be(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=be(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),f=be(r,["Price","price"],"Price");if(BigInt(d)!==Xe(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==Xe(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==Xe(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let p=Xi(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 w=be(r,["txType","tx_type","TxType"],"txType");if(w!==kr)throw new Error("lighter: signed txType must be official create-order");let h={...Qi(r),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:s,ReduceOnly:a,TriggerPrice:c,OrderExpiry:u,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(f),IsAsk:m?1:0,txType:w},x=JSON.stringify(h),E=JSON.parse(x);if(E.MarketIndex!==Number(d)||E.BaseAmount!==Number(l)||E.Price!==Number(f)||E.IsAsk!==(m?1:0)||E.txType!==w)throw new Error("lighter: canonical tx_info mutated");return{txType:w,txInfo:x,submitTo:Or(e.submitTo)}}function Gt(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var Se=e=>{if(typeof e!="string"||e.length===0||e.length>262144||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return null;let t=Buffer.from(e,"base64");return t.toString("base64")===e?t:null},Ze=e=>String(e||"").toLowerCase();function rs(e,t){if(typeof e!="string")return!1;let r,n;try{r=Fr.from(e),n=Fr.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce,type:t.type,accessList:t.accessList})}catch{return!1}return Ze(r.from)!==Ze(t.from)||Ze(r.to)!==Ze(t.to)?!1:r.unsignedHash===n.unsignedHash}function ts(e){let t=Buffer.from(Rr.encode(e)),r=zt("sha256").update(t).digest();return Buffer.from(zt("sha256").update(r).digest()).reverse().toString("hex")}function Yt(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||ts(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 ns(e,t){let r=Se(e),n=Se(t.psbt);if(!r||!n)return!1;try{let o=Mr.fromPSBT(n),i=Mr.fromPSBT(r);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let s=0;s<i.inputsLength;s++){let a=i.getInput(s),c=o.getInput(s);if(!Yt(c)||!Yt(a))return!1;let u=(h,x)=>{if(h==null&&x==null)return!0;if(h==null||x==null)return!1;try{return Buffer.from(h).equals(Buffer.from(x))}catch{return!1}},d=(h,x)=>{if(h==null&&x==null)return!0;if(h==null||x==null)return!1;try{return Buffer.from(Rr.encode(h)).equals(Buffer.from(Rr.encode(x)))}catch{return u(h,x)}};if(!!a.witnessUtxo!=!!c.witnessUtxo||a.witnessUtxo&&(BigInt(a.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!u(a.witnessUtxo.script,c.witnessUtxo.script))||!d(a.nonWitnessUtxo,c.nonWitnessUtxo)||!u(a.redeemScript,c.redeemScript)||!u(a.witnessScript,c.witnessScript)||a.sighashType!==void 0&&a.sighashType!==de.DEFAULT&&a.sighashType!==de.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===de.ALL,f=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===de.ALL:!1;for(let h of a.partialSig||[]){let x=Array.isArray(h)?h[1]:h;if(!l(x))return!1}if(a.tapKeySig&&!f(a.tapKeySig))return!1;for(let h of a.tapScriptSig||[]){let x=Array.isArray(h)?h[1]:h;if(!f(x))return!1}let p=h=>h[h.length-1]===de.ALL,m=h=>h.length>=9&&h.length<=73&&h[1]===h.length-3&&h[2]===2,g=h=>{let x=!1;for(let E of h)if(E instanceof Uint8Array){if(E[0]===48){if(!m(E)||!p(E))return!1;x=!0;continue}if(E.length===64){x=!0;continue}if(E.length===65){if(E[64]!==de.ALL&&E[64]!==de.DEFAULT)return!1;x=!0}}return x};if(a.finalScriptWitness){let h;if(Array.isArray(a.finalScriptWitness))h=a.finalScriptWitness;else if(a.finalScriptWitness instanceof Uint8Array){let x=a.finalScriptWitness,E=O=>{let v=x[O];return v===void 0?null:v<253?{value:v,next:O+1}:v===253?{value:x[O+1]|x[O+2]<<8,next:O+3}:null},b=E(0);if(!b)return!1;h=[];let T=b.next;for(let O=0;O<b.value;O++){let v=E(T);if(!v||T+v.value>x.length)return!1;h.push(x.slice(v.next,v.next+v.value)),T=v.next+v.value}if(T!==x.length)return!1}else return!1;if(!h.length||!g(h))return!1}if(a.finalScriptSig instanceof Uint8Array&&a.finalScriptSig.length){let h=a.finalScriptSig,x=[],E=0;for(;E<h.length;){let b=h[E];if(b>=1&&b<=75){if(E+1+b>h.length)return!1;x.push(h.slice(E+1,E+1+b)),E+=1+b;continue}if(b===76){let T=h[E+1];if(T===void 0||E+2+T>h.length)return!1;x.push(h.slice(E+2,E+2+T)),E+=2+T;continue}return!1}if(!x.length||!g(x))return!1}if(![a.partialSig,a.tapKeySig,a.tapScriptSig,a.finalScriptSig,a.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function Zt(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 os(e,t,r){let n=Se(e),o=Se(t.messageBase64);if(!n||!o)return!1;let i=Zt(n);if(!i||i.value!==1||i.offset!==1)return!1;let s=i.offset+64;if(s>=n.length)return!1;let a=n.subarray(i.offset,s),c=n.subarray(s);if(!c.equals(o))return!1;try{let u=Xt.decode(String(r));return u.length===32&&es.verify(a,c,u)}catch{return!1}}function Qt(e,t,r,n){if(String(e).startsWith("evm"))return rs(t,r);if(e==="btc")return ns(t,r);if(e==="sol")return os(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String(Kt(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return Ht({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(Kt(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Pe(r,t),!0}catch{return!1}return!1}function en(e,t){try{if(String(e).startsWith("evm"))return Fr.from(t).hash;if(e==="btc"){let r=Se(t);if(!r)return null;let n=Mr.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=Se(t);if(!r)return null;let n=Zt(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Xt.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return Vt(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return Vt(t)}catch{}return null}var cs=e=>String(e||"").toLowerCase();function te(e){return is("sha256").update(JSON.stringify(e)).digest("hex")}function Dr(e,t,r={}){return He(e,t,r)}async function us(e,t={}){if(!Y(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 tn(e,t,r=!1){if(!Y(e?.chainId))return!0;if(e.l1FeeWei===void 0||e.operatorFeeWei===void 0)throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei");if(r||t!=null){if(!t||t.l1FeeWei===void 0||t.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let n=BigInt(e.l1FeeWei)+BigInt(e.operatorFeeWei),o=BigInt(t.l1FeeWei)+BigInt(t.operatorFeeWei);if(n<o)throw new Error("policy: rollup fee attestation understates estimate")}return!0}var Qe=class{#e=new Map;constructor({now:t=Date.now}={}){this.now=t}issue({artifact:t,owner:r,ttlMs:n=6e4}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=ss(32).toString("hex");return this.#e.set(o,{digest:te(t),owner:cs(r),expiresAtMs:this.now()+n}),o}consume(t,r){let n=this.#e.get(String(t));if(!n)throw new Error("confirmation: used or unknown nonce");if(n.expiresAtMs<=this.now())throw this.#e.delete(String(t)),new Error("confirmation: expired nonce");let o=Buffer.from(n.digest,"hex"),i=Buffer.from(te(r),"hex");if(!as(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(t)),n}clear(){this.#e.clear()}};function ls(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(K(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 ds(e={},t={}){let r={};for(let n of new Set([...Object.keys(e||{}),...Object.keys(t||{})]))r[n]=(BigInt(t?.[n]??0)-BigInt(e?.[n]??0)).toString();return r}function er(e,t){let r=String(t||"");if(String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(r);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(r);if(e==="sol")try{let n=rn.decode(r);return n.length===64&&rn.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 nn(e,t,r){return!er(e,t)||!er(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function fs(e){let t=e?.confirmationMode;if(t!=="exact-human"&&t!=="auto-within-rails")throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");return t}async function qr({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:s,nowMs:a}){let c=fs(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(t?.triggerAttestation,e,a())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(s)return n.confirmations.consume(r,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=a())throw new Error("confirmation: expired nonce");return i}function ps(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function ms(e,t){return e&&ps(e.surface)?Ve(e):[t]}function hs(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!nn(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function ws(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:ds(r,n)}}async function on(e,t,r){if(!r.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:w,...h}=e||{};return h})(),i=ms(n,o),s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,a=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:null,consumeNonce:!0,nowMs:a}),u=te(e),d=(w={})=>{n?Ke(n,s,w):(Dr(o,s,{nowMs:w.nowMs,networkFees:w.networkFees,requireNetworkFees:w.requireNetworkFees}),ls(o))},l=async w=>{let h=n&&!String(n.surface||"").startsWith("evm")?void 0:await us(w,r);return{nowMs:a(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:h,requireNetworkFees:Y(w?.chainId)}};d({nowMs:a(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let w of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[w]!="function")throw new Error(`signer: ${w} is required`);let f=r.reserveLedger(n||e,s);if(!f)throw new Error("signer: ledger reservation required");let p=!1,m=[];try{for(let w of i){if(typeof r.simulate!="function"||await r.simulate(w,n)!==!0)throw new Error("signer: strict affirmative simulation required");let h=await l(w);if(tn(w,h.networkFees,h.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:c,consumeNonce:!1,nowMs:a}),d(h),r.validateReservation(f,s,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,s):void 0),p=!0;let x=await r.sign(w,n);if(typeof r.verifySigned!="function"||await r.verifySigned(x,w,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!r.isArmed())throw new Error("signer: disarmed before broadcast");if(te(e)!==u)throw new Error("signer: artifact mutated after signing");s=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await qr({artifact:e,envelope:n,nonce:t,deps:r,policy:s,confirmation:c,consumeNonce:!1,nowMs:a});let E=await l(w);tn(w,E.networkFees,E.requireNetworkFees),d(E),r.validateReservation(f,s,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,s):void 0);let b=await r.broadcast(x,w,n),T=b?.status,O=n?.surface||"evm",v=hs(b,O),Te=en(O,x);if(!nn(O,v,Te))throw new Error("signer: receipt transaction hash does not match signed bytes");if(T===0||T==="0x0")throw er(O,v)?(r.settleFailedLedger(f),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(T!==1&&T!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!er(O,v))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(ws(b,v))}}catch(w){throw p||r.releaseLedger(f),w}if(r.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 sn=new Set(["127.0.0.1","::1","localhost"]),Es=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&ys(r,n)},$=(e,t,r)=>{let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function xs(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 an=e=>new Promise((t,r)=>{let n=0,o=[],i=!1;e.on("data",s=>{n+=s.length,n>64*1024&&!i?(i=!0,r(new Error("request refused")),e.resume()):i||o.push(s)}),e.on("end",()=>{if(!i)try{t(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{r(new Error("request refused"))}}),e.on("error",r)});function cn(e={}){let t=e.host||"127.0.0.1";if(!sn.has(t))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let i of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[i]!="function")throw new Error(`signer: ${i} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Qe,n=e.origin||`http://${t}`;return gs.createServer(async(i,s)=>{try{let a=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!Es(a,e.token))return $(s,401,{error:"unauthorized"});let c=xs(i.headers.host);if(!sn.has(c))return $(s,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return $(s,403,{error:"origin refused"});if(i.method==="GET"&&i.url==="/status"){let u=typeof e.readPolicy=="function"?e.readPolicy():e.policy,d=new Set(_r),l=Array.isArray(u?.surfaces)?u.surfaces.filter(f=>typeof f=="string"&&d.has(f)):[];return $(s,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:l,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(i.method==="POST"&&i.url==="/disarm")return e.disarm(),r.clear(),$(s,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return $(s,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return $(s,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return $(s,403,{error:"autonomous signer does not issue human confirmation nonces"});let u=await an(i),d=te(u.artifact),l=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(l?.confirmationMode!=="exact-human")return $(s,403,{error:"exact-human policy required"});let f=typeof e.nowMs=="function"?e.nowMs():Date.now();if(u.artifact?.version===1&&u.artifact?.surface)Ke(u.artifact,l,{nowMs:f,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:p,...m}=u.artifact||{};Dr(m,l,{nowMs:f})}return typeof e.confirmArtifact!="function"?$(s,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(u.artifact,d,l)!==!0?$(s,400,{error:"exact human confirmation refused"}):$(s,200,{confirmationNonce:r.issue({artifact:u.artifact,owner:u.artifact?.owner??u.artifact?.from,ttlMs:u.ttlMs})})}if(i.method==="POST"&&i.url==="/execute"){let u=await an(i),d=await on(u.artifact,u.confirmationNonce,{...e,confirmations:r});return $(s,200,d)}return $(s,404,{error:"not found"})}catch(a){return e.onError?.(String(a?.message||a)),$(s,400,{error:"request refused"})}})}import{createCipheriv as _u,createDecipheriv as bs,randomBytes as Ss,scryptSync as As}from"node:crypto";import I from"node:fs";import Ae from"node:path";var vs="ORACLE-LOCAL-VAULT",Is=1,tr=Object.freeze({N:1<<17,r:8,p:1}),Ts=256*1024*1024,ks=16*1024;function rr(e,t,r,{max:n=t}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${r} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<t||o.length>n)throw new Error(`local-vault: invalid ${r} length`);return o}function Os(e,t,r=tr){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return As(n,t,32,{...r,maxmem:Ts})}function un(e,t){if(e?.magic!==vs||e?.version!==Is)throw new Error("local-vault: unsupported vault file");if(e?.kdf?.name!=="scrypt"||e?.cipher?.name!=="aes-256-gcm")throw new Error("local-vault: unsupported cryptography");if(e.kdf.N!==tr.N||e.kdf.r!==tr.r||e.kdf.p!==tr.p)throw new Error("local-vault: unsupported KDF parameters");if(Object.keys(e.kdf).sort().join(",")!=="N,name,p,r,salt"||Object.keys(e.cipher).sort().join(",")!=="iv,name")throw new Error("local-vault: unexpected cryptography field");if(!e.meta||Object.keys(e.meta).some(l=>!["address","addresses","kind","createdAt"].includes(l))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||JSON.stringify(e.meta.addresses||{}).length>1024||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let r=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(l=>!r.includes(l)))throw new Error("local-vault: unexpected vault field");let n=rr(e.kdf.salt,32,"salt"),o=rr(e.cipher.iv,12,"iv"),i=rr(e.tag,16,"tag"),s=rr(e.ciphertext,1,"ciphertext",{max:ks}),{ciphertext:a,tag:c,...u}=e,d=Os(t,n);try{let l=bs("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(u))),l.setAuthTag(i),Buffer.concat([l.update(s),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function Ls(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 Ns(e){let t=Ae.dirname(e),r=I.lstatSync(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(r.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((r.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=I.lstatSync(e);if(n.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!n.isFile()||n.uid!==process.getuid?.()||n.nlink!==1)throw new Error("local-vault: unsafe destination file");if(n.dev!==r.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function L(e){let t;try{t=I.openSync(e,I.constants.O_RDONLY|I.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=I.fstatSync(t);if(Ls(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=I.lstatSync(e);if(n.isSymbolicLink()||n.dev!==r.dev||n.ino!==r.ino)throw new Error("local-vault: secret source changed or is too large");return I.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{I.closeSync(t)}}function ln(e){return JSON.parse(L(e))}function ce(e,t){I.mkdirSync(Ae.dirname(e),{recursive:!0,mode:448}),Ns(e);let r=Ae.join(Ae.dirname(e),`.${Ae.basename(e)}.${process.pid}.${Ss(6).toString("hex")}.tmp`);try{let n=I.openSync(r,I.constants.O_CREAT|I.constants.O_EXCL|I.constants.O_WRONLY|I.constants.O_NOFOLLOW,384);try{I.writeFileSync(n,String(t)),I.fsyncSync(n)}finally{I.closeSync(n)}I.renameSync(r,e),I.chmodSync(e,384);let o=I.openSync(Ae.dirname(e),"r");try{I.fsyncSync(o)}finally{I.closeSync(o)}}catch(n){try{I.unlinkSync(r)}catch{}throw n}}import{createHmac as Bs,randomBytes as Cs,timingSafeEqual as Ps}from"node:crypto";import R from"node:fs";import fe from"node:path";import{homedir as Ur}from"node:os";import{join as jr}from"node:path";var dn=process.env.ORACLE_PUBLIC_DESKTOP==="1",_s=dn?process.env.ORACLE_CONFIG_DIR||jr(Ur(),".config","oracle"):jr(Ur(),".config","oracle"),Mu=dn?_s:jr(Ur(),".config","mad-desk");var ju="0".repeat(64),Wu=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});function nr(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(nr).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+nr(e[r])).join(",")+"}"}var Hu=Promise.resolve();function ve(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=s=>{try{return R.realpathSync(s)}catch{return fe.resolve(s)}},n=r(fe.dirname(fe.resolve(e))),o=r(fe.dirname(fe.resolve(t))),i=(s,a)=>a===s||a.startsWith(s+fe.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var $s=864e5,D=(e,t)=>Bs("sha256",t).update(nr(e)).digest("hex"),Q=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Ps(r,n)},Rs=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Ms(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Q(e.integrity.mac,D(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function ir(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=L(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!Q(n?.integrity?.mac,D(n?.marker,t)))throw new Error("policy: sequence anchor integrity failed");return{sequence:Number(n?.marker?.policySequence||0),policyMac:n?.marker?.policyMac??null,present:!0,ledgerInitialized:n?.marker?.ledgerInitialized===!0}}function Fs(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let a=ir(e,r);i=a.present&&a.ledgerInitialized===!0}catch{i=!1}let s={policySequence:Number(t),policyMac:String(n)};i&&(s.ledgerInitialized=!0),ce(e,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:D(s,r)}})+`
|
|
4
|
+
`)}function qs(e,t){let r=ir(e,t);if(!r.present)throw new Error("policy: sequence anchor required");if(r.ledgerInitialized)return!0;if(r.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");return Fs(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function fn(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=L(t),o;try{o=JSON.parse(L(e))}catch(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=Ms(o,n);ve(r,e);let s=ir(r,n),a=Number(i.policySequence||0);if(!s.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(a!==s.sequence)throw new Error("policy: rolled back to a superseded policy");if(s.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!Q(s.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Re(e,t,r,n,o){let i=`${e}.continuity`,s;try{let a=JSON.parse(L(e));if(a?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Q(a?.integrity?.mac,D(a.ledger,t)))throw new Error("integrity verification failed");if(s=a.ledger,!Number.isFinite(s?.windowStartMs)||!Array.isArray(s?.entries)||s.sequence!==void 0&&(!Number.isSafeInteger(s.sequence)||s.sequence<0))throw new Error("invalid ledger")}catch(a){if(a?.code==="ENOENT"){if(R.existsSync(i)||R.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=ir(o,t);if(c.present&&c.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:r,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${a?.message||a}`)}try{let a=JSON.parse(L(i));if(a?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Q(a?.integrity?.mac,D(a.marker,t)))throw new Error("continuity verification failed");if(a.marker?.version===2&&(a.marker.sequence!==s.sequence||!Q(a.marker.ledgerMac,D(s,t))))throw new Error("continuity rollback detected");if(a.marker?.version!==2&&s.sequence!==void 0)throw new Error("continuity rollback detected");if(R.existsSync(n)&&(a.marker?.version!==2||s.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(a.marker?.version===2){let c=JSON.parse(L(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!Q(c?.integrity?.mac,D(c.marker,t))||c.marker?.version!==1||c.marker.sequence!==s.sequence||!Q(c.marker.ledgerMac,D(s,t)))throw new Error("checkpoint rollback detected")}}catch(a){throw new Error(`ledger: corrupt or unreadable: ${a?.message||a}`)}if(r-s.windowStartMs>=$s){let a=s.entries.map(c=>c.state==="reserved"?c:{...c,state:"consumed",value:"0",notional:"0"});return{windowStartMs:r,entries:a,sequence:s.sequence??0}}return{...s,sequence:s.sequence??0}}function or(e,t,r){return e.filter(n=>(n.unit||"wei")===r).reduce((n,o)=>n+BigInt(o[t]??0),0n)}function pn(e,t){let r=t==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:t==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:t==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:null;if(!r)throw new Error("ledger: unsupported accounting unit");for(let n of r)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return r.map(n=>BigInt(e[n]))}function Me(e,t){let r=`${e}.lock`,n=Cs(16).toString("hex"),o;try{o=R.openSync(r,R.constants.O_CREAT|R.constants.O_EXCL|R.constants.O_WRONLY|(R.constants.O_NOFOLLOW||0),384),R.writeFileSync(o,n),R.fsyncSync(o)}catch(i){throw o!==void 0&&R.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return t()}finally{R.closeSync(o);try{L(r)===n&&R.unlinkSync(r)}catch{}}}function $e(e,t,r,n,o){let i=`${e}.continuity`,s={...t,sequence:(t.sequence??0)+1},a=D(s,r);ce(e,JSON.stringify({ledger:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:a}})+`
|
|
5
5
|
`);let c={version:2,sequence:s.sequence,ledgerMac:a};ce(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:D(c,r)}})+`
|
|
6
|
-
`);let u={version:1,sequence:s.sequence,ledgerMac:a};
|
|
7
|
-
`),o&&
|
|
8
|
-
`),t}function zr(e,t,r){if(!t)throw new Error(`signer: ${e} key is required by policy`);let n=new Set((r||[]).map(o=>String(o).toLowerCase()));if(!t.addresses.some(o=>n.has(String(o).toLowerCase())))throw new Error(`signer: ${e} vault address is not an allowed policy owner`);return!0}function
|
|
6
|
+
`);let u={version:1,sequence:s.sequence,ledgerMac:a};R.mkdirSync(fe.dirname(n),{recursive:!0,mode:448}),ce(n,JSON.stringify({marker:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:D(u,r)}})+`
|
|
7
|
+
`),o&&qs(o,r)}function mn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:s=0,notional:a=0,fee:c,policy:u,nowMs:d=Date.now()}){let l=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(l))throw new Error("ledger: bounded tradeId required");ve(r,e);let f=L(t);return Me(e,()=>{let p=Re(e,f,d,r,n);if(p.entries.some(b=>String(b.tradeId)===l))throw new Error("ledger: replayed tradeId");let m=BigInt(s),g=BigInt(a),[w,h,x]=pn(u,i);if(m<0n||g<0n||g>x)throw new Error("ledger: per-trade cap exceeded");if(or(p.entries,"value",i)+m>w||or(p.entries,"notional",i)+g>h)throw new Error("ledger: daily cap exceeded");let E={tradeId:l,unit:i,value:m.toString(),notional:g.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:d};return p.entries.push(E),$e(e,p,f,r,n),structuredClone(E)})}function hn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:s,nowMs:a=Date.now()}){ve(r,e);let c=L(t);return Me(e,()=>{let u=Re(e,c,a,r,n),d=u.entries.find(g=>String(g.tradeId)===String(o?.tradeId??"")&&g.state==="reserved");if(!d||d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(s){if(s.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(s.value)>BigInt(d.value)||BigInt(s.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[f,p,m]=pn(i,l);if(BigInt(d.notional)>m)throw new Error("ledger: per-trade cap exceeded");if(or(u.entries,"value",l)>f||or(u.entries,"notional",l)>p)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function wn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ve(r,e);let s=L(t);return Me(e,()=>{let a=Re(e,s,i,r,n),c=a.entries.find(u=>String(u.tradeId)===String(o??"")&&u.state==="reserved");if(!c||c.state!=="reserved")throw new Error("ledger: reservation unavailable");return c.state="committed",c.committedAtMs=i,$e(e,a,s,r,n),structuredClone(c)})}function gn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ve(r,e);let s=L(t);return Me(e,()=>{let a=Re(e,s,i,r,n),c=a.entries.findIndex(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(c<0)throw new Error("ledger: reservation unavailable");let[u]=a.entries.splice(c,1);return $e(e,a,s,r,n),structuredClone(u)})}function yn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ve(r,e);let s=L(t);return Me(e,()=>{let a=Re(e,s,i,r,n),c=a.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");let u=BigInt(c.fee??0);return u<=0n?(c.state="committed",c.committedAtMs=i,c.value="0",c.notional="0",c.settledAs="no-fee",$e(e,a,s,r,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=u.toString(),c.settledAs="fee-only",$e(e,a,s,r,n),structuredClone(c))})}function En(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:te(Rs(t))};return Q(e.mac,D(o,L(r)))}function Ds(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function xn(e,t,r,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(t.owner).toLowerCase(),action:String(t.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:te(Ds(t))};return Q(e.mac,D(o,L(r)))}import{spawnSync as Us}from"node:child_process";function bn(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=Us(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}import{Wallet as Wr}from"ethers";import{base58 as vn}from"@scure/base";import{ed25519 as js}from"@noble/curves/ed25519.js";import{NETWORK as In,TEST_NETWORK as Tn,WIF as Ws,p2wpkh as Sn}from"@scure/btc-signer";import{pubECDSA as Hs}from"@scure/btc-signer/utils.js";var Js=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Gs=e=>{let t=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return null;let r=Buffer.from(t,"base64");return r.toString("base64")===t?r:null},Ie=(e,t)=>{if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)};function Hr(e,t){let r=String(t||"").trim();if(e==="evm")return new Wr(r).privateKey;if(e==="btc")for(let i of[In,Tn])try{return Buffer.from(Ws(i).decode(r))}catch{}if(e==="sol")try{return Ie(vn.decode(r),"sol")}catch{}let n=Js(r);if(n)return e==="evm"?new Wr(`0x${n.toString("hex")}`).privateKey:Ie(n,e);let o=Gs(r);if(o)return Ie(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Ie(Uint8Array.from(i),e);let s=i.privateKey??i.secretKey??i.key;if(s)return Hr(e,Array.isArray(s)?JSON.stringify(s):String(s))}throw new Error(`${e}: unsupported private key format`)}function An(e,t){if(e==="evm"){let r=new Wr(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=Ie(t,"btc"),n=Hs(r);return{kind:e,secret:r.toString("hex"),addresses:[Sn(n,In).address,Sn(n,Tn).address]}}if(e==="sol"){let r=Ie(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[vn.encode(js.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function kn(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:An(t.kind||"evm",Hr(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=An(i,Hr(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function Jr(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}function Xs(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||V.join(process.env.XDG_STATE_HOME||V.join(zs.homedir(),".local","state"),"oracle"),r=Vs("sha256").update(V.resolve(e)).digest("hex").slice(0,16);return{vault:V.join(e,"vault.json"),policy:V.join(e,"signer-policy.json"),policyKey:V.join(e,"policy-integrity-key"),policyAnchor:V.join(t,`signer-policy-${r}.high-water`),ledger:V.join(e,"signer-ledger.json"),ledgerAnchor:V.join(t,`signer-ledger-${r}.high-water`),token:V.join(e,"signer-token"),lock:V.join(t,`signer-${r}.lock`)}}function Zs(e){try{return L(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=Ks(32).toString("hex");return ce(e,t+`
|
|
8
|
+
`),t}function zr(e,t,r){if(!t)throw new Error(`signer: ${e} key is required by policy`);let n=new Set((r||[]).map(o=>String(o).toLowerCase()));if(!t.addresses.some(o=>n.has(String(o).toLowerCase())))throw new Error(`signer: ${e} vault address is not an allowed policy owner`);return!0}function Ln(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function F(e,t){return e.surfaces.includes(t)}function Qs(e,t,r){let n=e?.version===1&&e?.surface?e:null,o=n?.artifact||e||{},i=[`surface=${n?.surface||"evm"} action=${n?.action||"evm"}`,`chain=${o.chainId??o.network??o.cluster??"n/a"} owner=${n?.owner||o.from||"n/a"}`,`to=${o.to||n?.destination||"n/a"} calldata=${String(o.data||"0x")} value=${o.value??"n/a"}`,`gas=${o.gasLimit??"n/a"} maxFeePerGas=${o.maxFeePerGas??o.gasPrice??"n/a"} maxPriorityFeePerGas=${o.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${o.l1FeeWei??"n/a"} operatorFeeWei=${o.operatorFeeWei??"n/a"}`,`nonce=${o.nonce??"n/a"} type=${o.type??"n/a"} accessList=${Array.isArray(o.accessList)?o.accessList.length:0}`,`slippageBps=${n?.slippageBps??o.slippageBps??"n/a"} expiresAtMs=${n?.expiresAtMs??o.expiresAtMs??"n/a"}`],s=(c,u)=>{if(i.push(`LEG ${u} chain=${c.chainId??"n/a"} from=${c.from??"n/a"} to=${c.to??"n/a"}`),i.push(`LEG ${u} calldata=${String(c.data||"0x")} value=${c.value??"n/a"}`),i.push(`LEG ${u} gas=${c.gasLimit??"n/a"} maxFeePerGas=${c.maxFeePerGas??c.gasPrice??"n/a"} maxPriorityFeePerGas=${c.maxPriorityFeePerGas??"n/a"}`),i.push(`LEG ${u} l1FeeWei=${c.l1FeeWei??"n/a"} operatorFeeWei=${c.operatorFeeWei??"n/a"} nonce=${c.nonce??"n/a"} type=${c.type??"n/a"}`),K(String(c.data||"0x")))try{let d=Le(String(c.data||"0x"));i.push(`LEG ${u} APPROVAL token=${d.token||c.to||"n/a"} spender=${d.spender} amount=${d.amount}`)}catch{i.push(`LEG ${u} APPROVAL spender=undecodable amount=undecodable`)}},a=String(o.data||"0x");if(K(a))try{let c=Le(a);i.push(`APPROVAL token=${c.token||o.to||"n/a"} spender=${c.spender} amount=${c.amount}`)}catch{i.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(o.transactions)&&(i.push(`batchLegs=${o.transactions.length}`),o.transactions.forEach((c,u)=>s(c,u))),n?.surface==="btc"){let c=wr(n,r);i.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(n?.surface==="sol"){let c=Sr(n,r);i.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(n?.surface==="hl"){let c=ie(n,r);i.push(`hlKind=${c.kind} actionType=${c.actionType} coin=${c.coin||"n/a"} amount=${c.amount} notionalUsd=${c.notional} submitTo=${c.submitTo}`)}if(n?.surface==="poly"){let c=se(n,r);i.push(`polyKind=${c.kind} tokenId=${c.tokenId} notionalUsdc=${c.notional} submitTo=${c.submitTo}`)}if(n?.surface==="lighter"){let c=ae(n,r);i.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
|
|
9
9
|
Confirm exact action
|
|
10
10
|
${i.join(`
|
|
11
11
|
`)}
|
|
12
|
-
Type digest ${t}: `}async function sr(e,t){let r=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),n=await r.text();if(!r.ok)throw new Error(`rpc: HTTP ${r.status}`);let o=JSON.parse(n||"{}");if(o.error)throw new Error(`rpc: ${o.error.message||"request failed"}`);return o.result}function Ln(e,t){return Buffer.concat([Buffer.from([1]),Buffer.from(t),Buffer.from(e)]).toString("base64")}async function _n(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation and broadcast");return sr(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function Xs(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let s=await fetch(`${o}/tx/${t}/outspend/${r}`);if(s.ok){let a=await s.json();if(a?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(a?.spent===!1)return!0}}catch(s){if(/already spent/.test(String(s?.message||s)))throw s}if(!await _n(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Zs(e){if(!e||typeof e!="object"||!e.value||typeof e.value!="object"||!Object.prototype.hasOwnProperty.call(e.value,"err"))throw new Error("signer: Solana simulation result missing");if(e.value.err!==null)throw new Error("signer: Solana simulation failed");return!0}function Qs(e,t){return{simulate:async(r,n)=>(ie(n,e()),!0),sign:async(r,n)=>{ie(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return r?.typedData?(Ut(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):jt({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{ie(o,e());let{Signature:i,keccak256:s}=await import("ethers"),a=i.from(r);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:a.r,s:a.s,v:a.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:s(r),status:1}}}}function ea(e){return{simulate:async(t,r)=>(ae(r,e()),!0),sign:async(t,r)=>{ae(r,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(t,r);return Pe(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=ae(n,e()),i=Pe(r,t),s=Jt(i),a=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s}),c=await a.json().catch(()=>({}));if(!a.ok||Number(c?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(c?.tx_hash||c?.txHash||"lighter"),status:1}}}}function ra(e,t){return{simulate:async(r,n)=>(se(n,e()),!0),sign:async(r,n)=>{se(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),s=se(o,i),a=Tr(i),{keccak256:c}=await import("ethers"),u=It({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:a.key}),d=JSON.stringify(u),l=At({creds:a,address:o.owner,method:"POST",path:"/order",body:d}),f=await fetch(s.submitTo,{method:"POST",headers:l,body:d}),m=await f.json().catch(()=>({}));if(!f.ok||m?.success===!1||m?.error||m?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:c(r),status:1}}}}function ta(e,t){let r=Jr(t);return{simulate:async n=>{let o=e(),i=Gr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let s=0;s<i.inputsLength;s++){let a=i.getInput(s),c=Buffer.from(a.txid||[]).toString("hex");await Xs(o,c,a.index)}return!0},sign:n=>{let o=Gr.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(r),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let s=Gr.fromPSBT(Buffer.from(n,"base64"));s.finalize(),s.extract();let a;try{let u=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:s.hex});if(a=(await u.text()).trim(),!u.ok)throw new Error(`signer: Bitcoin broadcast failed ${u.status}`)}catch(u){if(!/Bitcoin broadcast failed 404/.test(String(u?.message||u)))throw u;a=await _n(o,"sendrawtransaction",[s.hex])}if(a&&String(a).toLowerCase()!==s.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let u=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${u}/tx/${s.id}/status`);d.ok&&(c=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:s.id,status:c}}}}function na(e,t){let r=Jr(t);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let s=Buffer.from(n.messageBase64,"base64"),a=Ln(s,new Uint8Array(64)),c=await sr(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[a,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Zs(c)},sign:n=>Ln(Buffer.from(n.messageBase64,"base64"),zs.sign(Buffer.from(n.messageBase64,"base64"),r)),broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let s=await sr(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await sr(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[s],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:s,status:0};let u=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:s,status:u?1:null}}}}function oa(e,t={}){for(let r of Object.keys(t||{}))if(Object.prototype.hasOwnProperty.call(e,r))throw new Error(`signer: cannot replace built-in ${r} transport`)}async function Bn({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:s=12e4}={}){let{JsonRpcProvider:a,Wallet:c}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(s<1e3||s>12e4)throw new Error("signer: session must be at most 120 seconds");let u=Vs(e),d=()=>Object.freeze(dn(u.policy,u.policyKey,{sequenceAnchorFile:u.policyAnchor})),l=d();if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let f=["surfaces","actions","destinations","owners"];l.surfaces.some(y=>String(y).startsWith("evm"))&&f.push("chains","spenders");for(let y of f)if(!Array.isArray(l[y])||l[y].length===0)throw new Error(`signer: ${y} allowlist is empty`);if(l.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge"||y==="evm-nft")){for(let y of["providers"])if(!Array.isArray(l[y])||l[y].length===0)throw new Error(`signer: ${y} allowlist is empty`)}if(l.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(y=>String(y).startsWith("evm"))&&(!Array.isArray(l.selectors)||l.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(l.surfaces.includes("sol")&&(!Array.isArray(l.programs)||l.programs.length===0))throw new Error("signer: programs allowlist is empty");if(F(l,"poly")&&(Tr(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(F(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(F(l,"hl")){let y=Array.isArray(l.coins)?l.coins.map(String):[],A=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(y.filter(q=>q!=="*"&&q!=="#*").length&&!y.includes("*")&&A.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let m=r?xn(r):L(t),p=un(u.vault),g=cn(p,m),w;try{w=Tn(g,p.meta)}finally{g.fill(0)}(On(l)||F(l,"hl")||F(l,"poly"))&&zr("evm",w.evm,l.owners),F(l,"btc")&&zr("btc",w.btc,l.owners),F(l,"sol")&&zr("sol",w.sol,l.owners);let h=Array.isArray(l.chains)?l.chains.filter(y=>Number.isInteger(Number(y))&&String(y).trim()!==""):[],x=On(l);if(x&&(h.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(F(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(F(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=x?new a(l.rpcUrl,Number(h[0])):null,b=w.evm&&(x||F(l,"hl")||F(l,"poly"))?E?new c(w.evm.secret).connect(E):new c(w.evm.secret):null,T=E?{simulate:async y=>{if((await E.getNetwork()).chainId!==BigInt(y.chainId))throw new Error("signer: RPC chain mismatch");return await E.call(y),!0},sign:y=>b.signTransaction(y),broadcast:async(y,A)=>{if((await E.getNetwork()).chainId!==BigInt(A.chainId))throw new Error("signer: RPC chain mismatch");let q={native:(await E.getBalance(A.from)).toString()},ke=await E.broadcastTransaction(y),ne=await ke.wait(),qe={native:(await E.getBalance(A.from)).toString()};return{hash:ne?.hash??ke.hash,status:ne?.status??null,verifiedBefore:q,verifiedAfter:qe}}}:null,O=E?async y=>ia(E,y):void 0,v={...T?{evm:T,"evm-swap":T,"evm-bridge":T,"evm-nft":T}:{},...w.btc?{btc:ta(d,w.btc)}:{},...w.sol?{sol:na(d,w.sol)}:{},...b&&F(l,"hl")?{hl:Qs(d,b)}:{},...b&&F(l,"poly")?{poly:ra(d,b)}:{},...F(l,"lighter")?{lighter:ea(d)}:{}};oa(v,n);let Te=qt({...v,...n}),Pn=new Set(Object.keys(v)),$n=new Set(Object.keys(n||{})),Vr=l.surfaces.filter(y=>!Pn.has(y)&&!$n.has(y));if(Vr.length)throw new Error(`signer: ${Vr.join(",")} require local keys or injected surface transports`);let Mn=Date.now(),Kr=Mn+s,ur=!1,Rn=()=>ur?!1:kn.existsSync(u.lock)?(ur=!0,!1):kn.existsSync(u.vault)&&Date.now()<Kr,Fn=()=>(ur=!0,ce(u.lock,`disarmed ${new Date().toISOString()}
|
|
13
|
-
`),!0),Fe=
|
|
14
|
-
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,cr=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function
|
|
15
|
-
`),0;let r=cr(e,"--passphrase-file"),n=await
|
|
16
|
-
`),await new Promise(o=>n.on("close",o)),0}var
|
|
12
|
+
Type digest ${t}: `}async function sr(e,t){let r=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),n=await r.text();if(!r.ok)throw new Error(`rpc: HTTP ${r.status}`);let o=JSON.parse(n||"{}");if(o.error)throw new Error(`rpc: ${o.error.message||"request failed"}`);return o.result}function Nn(e,t){return Buffer.concat([Buffer.from([1]),Buffer.from(t),Buffer.from(e)]).toString("base64")}async function Bn(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation and broadcast");return sr(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function ea(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let s=await fetch(`${o}/tx/${t}/outspend/${r}`);if(s.ok){let a=await s.json();if(a?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(a?.spent===!1)return!0}}catch(s){if(/already spent/.test(String(s?.message||s)))throw s}if(!await Bn(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function ra(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 ta(e,t){return{simulate:async(r,n)=>(ie(n,e()),!0),sign:async(r,n)=>{ie(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return r?.typedData?(jt(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Wt({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{ie(o,e());let{Signature:i,keccak256:s}=await import("ethers"),a=i.from(r);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:a.r,s:a.s,v:a.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:s(r),status:1}}}}function na(e){return{simulate:async(t,r)=>(ae(r,e()),!0),sign:async(t,r)=>{ae(r,e());let n=e();if(typeof n.lighterSignImpl!="function")throw new Error("lighter: official Lighter signer required");let o=await n.lighterSignImpl(t,r);return Pe(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=ae(n,e()),i=Pe(r,t),s=Gt(i),a=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s}),c=await a.json().catch(()=>({}));if(!a.ok||Number(c?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(c?.tx_hash||c?.txHash||"lighter"),status:1}}}}function oa(e,t){return{simulate:async(r,n)=>(se(n,e()),!0),sign:async(r,n)=>{se(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),s=se(o,i),a=Tr(i),{keccak256:c}=await import("ethers"),u=It({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:a.key}),d=JSON.stringify(u),l=At({creds:a,address:o.owner,method:"POST",path:"/order",body:d}),f=await fetch(s.submitTo,{method:"POST",headers:l,body:d}),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 ia(e,t){let r=Jr(t);return{simulate:async n=>{let o=e(),i=Gr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let s=0;s<i.inputsLength;s++){let a=i.getInput(s),c=Buffer.from(a.txid||[]).toString("hex");await ea(o,c,a.index)}return!0},sign:n=>{let o=Gr.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(r),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let s=Gr.fromPSBT(Buffer.from(n,"base64"));s.finalize(),s.extract();let a;try{let u=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:s.hex});if(a=(await u.text()).trim(),!u.ok)throw new Error(`signer: Bitcoin broadcast failed ${u.status}`)}catch(u){if(!/Bitcoin broadcast failed 404/.test(String(u?.message||u)))throw u;a=await Bn(o,"sendrawtransaction",[s.hex])}if(a&&String(a).toLowerCase()!==s.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let u=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${u}/tx/${s.id}/status`);d.ok&&(c=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:s.id,status:c}}}}function sa(e,t){let r=Jr(t);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let s=Buffer.from(n.messageBase64,"base64"),a=Nn(s,new Uint8Array(64)),c=await sr(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[a,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return ra(c)},sign:n=>Nn(Buffer.from(n.messageBase64,"base64"),Ys.sign(Buffer.from(n.messageBase64,"base64"),r)),broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let s=await sr(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await sr(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[s],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:s,status:0};let u=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:s,status:u?1:null}}}}function aa(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 Cn({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:s=12e4}={}){let{JsonRpcProvider:a,Wallet:c}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(s<1e3||s>12e4)throw new Error("signer: session must be at most 120 seconds");let u=Xs(e),d=()=>Object.freeze(fn(u.policy,u.policyKey,{sequenceAnchorFile:u.policyAnchor})),l=d();if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let f=["surfaces","actions","destinations","owners"];l.surfaces.some(y=>String(y).startsWith("evm"))&&f.push("chains","spenders");for(let y of f)if(!Array.isArray(l[y])||l[y].length===0)throw new Error(`signer: ${y} allowlist is empty`);if(l.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge"||y==="evm-nft")){for(let y of["providers"])if(!Array.isArray(l[y])||l[y].length===0)throw new Error(`signer: ${y} allowlist is empty`)}if(l.surfaces.some(y=>y==="evm-swap"||y==="evm-bridge")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(y=>String(y).startsWith("evm"))&&(!Array.isArray(l.selectors)||l.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(l.surfaces.includes("sol")&&(!Array.isArray(l.programs)||l.programs.length===0))throw new Error("signer: programs allowlist is empty");if(F(l,"poly")&&(Tr(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(F(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(F(l,"hl")){let y=Array.isArray(l.coins)?l.coins.map(String):[],A=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(y.filter(q=>q!=="*"&&q!=="#*").length&&!y.includes("*")&&A.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let p=r?bn(r):L(t),m=ln(u.vault),g=un(m,p),w;try{w=kn(g,m.meta)}finally{g.fill(0)}(Ln(l)||F(l,"hl")||F(l,"poly"))&&zr("evm",w.evm,l.owners),F(l,"btc")&&zr("btc",w.btc,l.owners),F(l,"sol")&&zr("sol",w.sol,l.owners);let h=Array.isArray(l.chains)?l.chains.filter(y=>Number.isInteger(Number(y))&&String(y).trim()!==""):[],x=Ln(l);if(x&&(h.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(F(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(F(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=x?new a(l.rpcUrl,Number(h[0])):null,b=w.evm&&(x||F(l,"hl")||F(l,"poly"))?E?new c(w.evm.secret).connect(E):new c(w.evm.secret):null,T=E?{simulate:async y=>{if((await E.getNetwork()).chainId!==BigInt(y.chainId))throw new Error("signer: RPC chain mismatch");return await E.call(y),!0},sign:y=>b.signTransaction(y),broadcast:async(y,A)=>{if((await E.getNetwork()).chainId!==BigInt(A.chainId))throw new Error("signer: RPC chain mismatch");let q={native:(await E.getBalance(A.from)).toString()},ke=await E.broadcastTransaction(y),ne=await ke.wait(),qe={native:(await E.getBalance(A.from)).toString()};return{hash:ne?.hash??ke.hash,status:ne?.status??null,verifiedBefore:q,verifiedAfter:qe}}}:null,O=E?async y=>ca(E,y):void 0,v={...T?{evm:T,"evm-swap":T,"evm-bridge":T,"evm-nft":T}:{},...w.btc?{btc:ia(d,w.btc)}:{},...w.sol?{sol:sa(d,w.sol)}:{},...b&&F(l,"hl")?{hl:ta(d,b)}:{},...b&&F(l,"poly")?{poly:oa(d,b)}:{},...F(l,"lighter")?{lighter:na(d)}:{}};aa(v,n);let Te=Dt({...v,...n}),$n=new Set(Object.keys(v)),Rn=new Set(Object.keys(n||{})),Vr=l.surfaces.filter(y=>!$n.has(y)&&!Rn.has(y));if(Vr.length)throw new Error(`signer: ${Vr.join(",")} require local keys or injected surface transports`);let Mn=Date.now(),Kr=Mn+s,ur=!1,Fn=()=>ur?!1:On.existsSync(u.lock)?(ur=!0,!1):On.existsSync(u.vault)&&Date.now()<Kr,qn=()=>(ur=!0,ce(u.lock,`disarmed ${new Date().toISOString()}
|
|
13
|
+
`),!0),Fe=cn({host:o,port:i,token:Zs(u.token),policy:l,readPolicy:d,isArmed:Fn,disarm:qn,sessionExpiresAtMs:Kr,nowMs:Date.now,simulate:(y,A)=>Ye(A,Te).simulate(y,A),estimateNetworkFees:O,sign:(y,A)=>Ye(A,Te).sign(y,A),verifySigned:(y,A,N)=>Qt(N?.surface||"evm",y,A,N),broadcast:(y,A,N)=>Ye(N,Te).broadcast(y,A,N),confirmArtifact:la,decodeEconomics:(y,A)=>Br(y,A),reserveLedger:(y,A)=>{let N=y?.version===1&&y?.surface?y:null,q=N?.artifact||y,ke=N?.tradeId||q?.tradeId;if(!ke)throw new Error("ledger: executable artifact requires a tradeId");let ne;if(N)ne=Br(N,A);else{if(q?.value===void 0)throw new Error("ledger: executable artifact value required");let qe=BigInt(q.value),Xr=BigInt(q.gasLimit??0),Zr=BigInt(q.maxFeePerGas??q.gasPrice??0);if(Xr<=0n||Zr<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let Qr=Xr*Zr+BigInt(q.l1FeeWei??0)+BigInt(q.operatorFeeWei??0);ne={unit:"wei",value:qe.toString(),notional:(qe+Qr).toString(),fee:Qr.toString()}}if(ne.value===void 0||ne.notional===void 0)throw new Error("ledger: decoded value and notional required");return mn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:ke,...ne,policy:A})},commitLedger:y=>wn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:y.tradeId}),releaseLedger:y=>gn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:y.tradeId}),settleFailedLedger:y=>yn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:y.tradeId}),validateReservation:(y,A,N)=>hn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,reservation:y,policy:A,economics:N}),verifyFeeWaiver:(y,A)=>xn(y,A,u.policyKey),verifyTriggerAttestation:(y,A,N)=>En(y,A,u.policyKey,N),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),Yr=setTimeout(()=>Fe.close(),s);return Yr.unref(),Fe.on("close",()=>{clearTimeout(Yr)}),Fe.listen(i,o),Fe}var ar="0x420000000000000000000000000000000000000F";function _n(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 ca(e,t){if(!Y(t?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:r,Transaction:n}=await import("ethers"),o=new r(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce??0,type:t.type,accessList:t.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let s;try{let a=await e.call({to:ar,data:o.encodeFunctionData("getL1Fee",[i])});s=o.decodeFunctionResult("getL1Fee",a)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:s,operatorFeeWei:await ua(e,o,t.gasLimit)}}async function ua(e,t,r){let n;try{n=BigInt(r)}catch{throw new Error("policy: rollup fee estimate required")}if(n<0n)throw new Error("policy: rollup fee estimate required");try{let o=await e.call({to:ar,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!_n(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:ar,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:ar,data:t.encodeFunctionData("operatorFeeConstant")}),s=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),a=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*s/1000000n+a).toString()}catch(o){if(!_n(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function la(e,t,r){return process.stdin.isTTY?(process.stderr.write(Qs(e,t,r)),process.stdin.resume(),new Promise(n=>{let o=i=>{process.stdin.off("data",o),process.stdin.pause(),n(String(i).trim()===t)};process.stdin.once("data",o)})):!1}var Pn=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
|
|
14
|
+
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,cr=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function fa(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(Pn+`
|
|
15
|
+
`),0;let r=cr(e,"--passphrase-file"),n=await Cn({configDir:da.join(t.configDir||Ue(),"signer"),passphraseFile:r,credentialService:cr(e,"--credential-service"),port:Number(cr(e,"--port",9462)),sessionMs:Number(cr(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
|
|
16
|
+
`),await new Promise(o=>n.on("close",o)),0}var Rl={name:"signer",summary:"run the short-lived loopback signer",usage:Pn,run:e=>fa(e.argv||[])};export{Rl as default,fa as run};
|