@oracle-agent/oracle 0.35.9 → 0.35.11
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/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/clear-sign/erc7730.mjs +1 -0
- package/dist/cli/commands/chat.mjs +180 -180
- package/dist/cli/commands/clear-sign.mjs +10 -0
- package/dist/cli/commands/doctor.mjs +11 -8
- package/dist/cli/commands/eval.mjs +73 -73
- package/dist/cli/commands/model.mjs +184 -184
- package/dist/cli/commands/sign.mjs +10 -10
- package/dist/cli/commands/signer.mjs +16 -16
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/runtime.mjs +13 -13
- package/package.json +2 -1
- package/public/eval-report.json +80 -0
- package/public/oracle-splash/index.html +1 -0
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var gi=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};import Tt from"node:fs";import yi from"node:os";import Ke from"node:path";import{fileURLToPath as Ei}from"node:url";function on(){return process.env.ORACLE_FAKE_HOME||yi.homedir()}function xi(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function Ot(){return xi()?process.env.ORACLE_CONFIG_DIR||Ke.join(on(),".config","oracle"):Ke.join(on(),".config","oracle")}function Si(){return Ke.join(Ot(),"desk.json")}function Ai(){return Ke.join(Ot(),"env")}function Ve({force:e=!1}={}){if(Ve._done&&!e)return Ve._result||null;Ve._done=!0;let t={},r=(o,i)=>{if(i==null)return;let a=String(i).trim();a&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=a,t[o]=a))};try{let o=Ai();if(Tt.existsSync(o))for(let i of Tt.readFileSync(o,"utf8").split(/\r?\n/)){let a=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let u=a[2];(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),r(a[1],u)}}catch{}try{let o=Si();if(Tt.existsSync(o)){let i=JSON.parse(Tt.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)),Ve._result=Object.keys(t).length?t:null,Ve._result}var bi,ul,an=gi(()=>{bi=Ke.dirname(Ei(import.meta.url)),ul=Ke.resolve(bi,"../..");try{Ve()}catch{}});an();import rl from"node:path";import si from"node:fs";import X from"node:path";import Cu from"node:os";import{createHash as Nu,randomBytes as Lu}from"node:crypto";import{execFileSync as $u}from"node:child_process";import{fileURLToPath as Bu}from"node:url";import{Interface as rn,keccak256 as Ru}from"ethers";import{Transaction as Zr}from"@scure/btc-signer";import{ed25519 as Pu}from"@noble/curves/ed25519.js";import ec from"node:http";import{timingSafeEqual as tc}from"node:crypto";import{createHash as js,randomBytes as Us,timingSafeEqual as zs}from"node:crypto";import{base58 as ho}from"@scure/base";import{Interface as Vn}from"ethers";import{Interface as Mi,MaxUint256 as qi,isAddress as ji,keccak256 as Gl,toUtf8Bytes as Vl}from"ethers";import{Interface as Fi,isAddress as Ol}from"ethers";import{isAddress as Sl}from"ethers";import{createHash as Oi,createHmac as Ci,timingSafeEqual as Ni}from"node:crypto";import{readFileSync as vi}from"node:fs";import{homedir as Ii}from"node:os";import{join as Ct}from"node:path";function ki(){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=Ii();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Ct(t,".config","oracle")).trim();return[e,Ct(r,"exec.env")].filter(Boolean)}return[e,Ct(t,".config","oracle","exec.env"),Ct(t,".config","mad-desk","exec.env")].filter(Boolean)}function dt(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of ki())try{let i=vi(o,"utf8"),a=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}function Xe(e,t,r="guard"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${r}: current time must be a finite number (got ${Ti(t)})`);let n=t,o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${r} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function Ti(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var sn=100;function rr(e){return Array.isArray(e)?`[${e.map(rr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${rr(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Li(e,{required:t=!1}={}){try{return dt(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function $i(e){let{signature:t,...r}=e;return r}function Bi(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 Oi("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function Ri(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:Ni(r,n)}function Pi(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=t.length;i+=64)n.push(t.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(r){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function nr(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:i,requireSigned:a=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let u=Li(o,{required:a});if(a&&!u)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(u){let m=Ci("sha256",u).update(rr($i(e))).digest("hex");if(!Ri(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>sn)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(s)||s<0||s>sn||c>s)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{Xe({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=Pi(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==Bi(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 h=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${h}; 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 $l=new Fi(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Di,isAddress as Pl}from"ethers";var Ml=new Di(["function approve(address spender,uint256 amount) returns (bool)"]),ql=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function F(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 H(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function J(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=F(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 Y(e,t="amount"){let r=J(e,t);if(r<=0n)throw new Error(`${t} must be positive`);return r}function _(e,t,r="amount"){let n=F(e,r);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${r} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[a="0",u=""]=i.split(".");if(u.length>t)throw new Error(`${r} has more than ${t} decimal places, which would lose precision`);let c=BigInt((a||"0")+u.padEnd(t,"0"));return o?-c:c}var ed=new Mi(["function approve(address spender,uint256 amount) returns (bool)"]);function cn(e,t){let r=String(e||"").trim();if(!ji(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Ui(e,t="approval amount",{allowZero:r=!1}={}){let n=J(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=qi)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var un=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),zi=new Set(["0x39509351","0xf9255c1f"]);function Q(e){let t=String(e||"").toLowerCase();return t.length<10?!1:un.has(t.slice(0,10))}function Be(e){if(!Q(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=s=>n[s]?"0x"+n[s].slice(24):null,i=s=>n[s]?BigInt("0x"+n[s]):null,a=null,u=null,c=null;switch(r){case"0x095ea7b3":case"0x39509351":a=o(0),u=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),a=o(1),u=i(2);break;case"0xd505accf":a=o(1),u=i(2);break;case"0x8fcbaf0c":{a=o(1),u=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),a=o(1),u=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(a==null||u==null)throw new Error("invalid approve calldata");return{spender:cn(a,"approval spender"),token:c==null?null:cn(c,"approval token"),amount:Ui(u,"approval amount",{allowZero:!0}),selector:r,additive:zi.has(r)}}import{createHash as Wi,createHmac as nd,timingSafeEqual as od}from"node:crypto";var Hi=2,or=300*1e3,ln=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function Ji(e){let t=e==null||e===""?or:Number(e);return!Number.isFinite(t)||t<0?or:Math.min(t,ln)}function ir(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ir).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ir(e[r])}`).join(",")}}`}function Gi(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function Vi(e){let t=Gi(e);return Wi("sha256").update(ir(t)).digest("hex")}function dn(e,{maxAgeMs:t=or,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)!==Hi)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let a=Vi(e);if(String(e.prepareHash||"")!==a)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let u=Number(e.preparedAt),c=Number(e.expiresAt),s=Ji(t),d=r-u,l=c-u;if(!Number.isFinite(d)||!Number.isFinite(c)||!Number.isFinite(l)||d<0||l<=0||l>ln||d>s||r>=c)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${s})`);if(n&&!new Set(n).has(e.provider))throw new Error(`${i}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${i}: kind ${e.kind} not allowed here`);return!0}var ft=e=>String(e||"").toLowerCase(),Ki=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","authorizationList","slippageBps","expiresAtMs"]),Xi=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function ue(e){try{return Xi.has(BigInt(e))}catch{return!1}}var Z=(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`)}},fn=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ye=(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 Nt(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=>!Ki.has(p)))throw new Error("policy: unexpected EVM artifact field");if(e.gasPrice!=null&&(e.maxFeePerGas!=null||e.maxPriorityFeePerGas!=null))throw new Error("policy: ambiguous EVM fee fields");if(e.type!=null&&![0,1,2,4].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");if(Number(e.type)===4){if(!Array.isArray(e.authorizationList)||e.authorizationList.length===0||e.authorizationList.length>8)throw new Error("policy: type-4 requires 1-8 authorizationList entries");for(let[p,m]of e.authorizationList.entries()){if(!m||typeof m!="object")throw new Error(`policy: authorizationList[${p}] required`);Ye(m.address,t.destinations,"destination",ft);try{if(BigInt(m.chainId)!==BigInt(e.chainId))throw new Error("policy: type-4 authorization chainId must match transaction")}catch(h){throw String(h?.message||"").includes("authorization chainId")?h:new Error("policy: type-4 authorization chainId must match transaction")}}if(String(e.data||"0x").toLowerCase()!=="0x")throw new Error("policy: type-4 calldata must be empty");if(Z(e.value,"value")!==0n)throw new Error("policy: type-4 cannot transfer native value")}else if(e.authorizationList!=null)throw new Error("policy: authorizationList is only valid on type-4");let i=(p,m)=>{try{return BigInt(p)===BigInt(m)}catch{return String(p)===String(m)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(p=>i(p,e.chainId)))throw new Error("policy: chain not allowed");if(Ye(e.to,t.destinations,"destination",ft),Ye(String(e.data||"0x").slice(0,10),t.selectors,"selector",p=>String(p).toLowerCase()),Ye(e.from,t.owners,"owner",ft),Q(e.data)){let p;try{p=Be(e.data)}catch(h){throw new Error(`policy: malformed approval calldata: ${h?.message||h}`)}Ye(p.spender,t.spenders,"spender",ft),Ye(p.token||e.to,t.erc20Tokens,"ERC-20 token",ft);let m=Z(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(Z(e.value,"value")>Z(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=Z(e.gasLimit,"gasLimit");if(a>Z(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let u=e.maxFeePerGas??e.gasPrice,c=Z(u,"feePerGas")*a,s=0n;try{if(ue(e.chainId)&&(e.l1FeeWei===void 0||e.operatorFeeWei===void 0))throw new Error("missing")}catch{throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(e.l1FeeWei!==void 0&&(s+=Z(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(s+=Z(e.operatorFeeWei,"operatorFeeWei")),ue(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let p=Z(n.l1FeeWei,"estimated l1FeeWei")+Z(n.operatorFeeWei,"estimated operatorFeeWei");if(s<p)throw new Error("policy: rollup fee attestation understates estimate")}if(c+s>Z(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=fn(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=fn(t.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-r>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as pn}from"node:crypto";import{Address as Yi,NETWORK as Qi,OutScript as mn,RawTx as Zi,SigHash as wn,TEST_NETWORK as ea,Transaction as ta}from"@scure/btc-signer";var hn=(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`)}},ra=(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},na=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,oa=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),Re=e=>oa(e)?String(e).toLowerCase():String(e),ar=(e,t)=>Array.isArray(t)&&t.some(r=>Re(r)===Re(e)),ia=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function aa(e){let t=Buffer.from(Zi.encode(e)),r=pn("sha256").update(t).digest();return Buffer.from(pn("sha256").update(r).digest()).reverse().toString("hex")}function sa(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(aa(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)||!ia(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function sr(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(!ar(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?Qi:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?ea:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=ta.fromPSBT(ra(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=Yi(n);for(let l=0;l<o.inputsLength;l++){let f=o.getInput(l);for(let h of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(na(f[h]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==wn.DEFAULT&&f.sighashType!==wn.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let p=sa(f),m;try{let h=mn.decode(p.script);if(!["wpkh"].includes(h.type))throw new Error("unsupported input");m=i.encode(h)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!ar(m,t.owners)||Re(m)!==Re(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...t.changeAddresses||[]].map(l=>Re(l))),u=0n,c=!1,s=[];for(let l=0;l<o.outputsLength;l++){let f=o.getOutput(l),p;try{p=i.encode(mn.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=Re(p);if(s.push(`${p}:${f.amount}`),m===Re(e.destination)){c=!0,u+=f.amount;continue}if(ar(p,t.destinations)){u+=f.amount;continue}if(!a.has(m))throw new Error("policy: Bitcoin output destination not allowed")}if(!c)throw new Error("envelope: Bitcoin destination mismatch");let d;try{d=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(d<0n||d>hn(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(u>hn(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:u.toString(),notional:(u+d).toString(),fee:d.toString(),outputs:Object.freeze(s)})}function cr(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})}import{createHash as lr}from"node:crypto";import{base58 as Sn}from"@scure/base";import{getCompiledTransactionMessageDecoder as ca}from"@solana/transaction-messages";var dr="11111111111111111111111111111111",ua="ComputeBudget111111111111111111111111111111",la="So11111111111111111111111111111111111111112",An="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var vn="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",da=5000n,fa=2039280n,pa=37095705934669439343138083508754565189542113879843219016388785533085940283555n,U=57896044618658097711785492504343953926634992332820282019728792003956564819949n,gn=19681161376707505956807079304988542015446066515923890162744021073123829784752n,yn=e=>lr("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),ma=new Map([[yn("route"),{name:"route",prefixBytes:0}],[yn("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),te=(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`)}},wa=(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},he=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),oe=e=>String(e||""),ha=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,$t=e=>lr("sha256").update(e).digest("hex");function Lt(e,t){try{let r=Buffer.from(Sn.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function ee(e){let t=e%U;return t>=0n?t:U+t}function le(e,t){let r=e;for(;t-- >0n;)r=r*r%U;return r}function ga(e){let r=e*e%U*e%U,n=le(r,2n)*r%U,o=le(n,1n)*e%U,i=le(o,5n)*o%U,a=le(i,10n)*i%U,u=le(a,20n)*a%U,c=le(u,40n)*u%U,s=le(c,80n)*c%U,d=le(s,80n)*c%U,l=le(d,10n)*i%U;return le(l,2n)*e%U}function ya(e,t){let r=ee(t*t*t),n=ee(r*r*t),o=ga(e*n),i=ee(e*r*o),a=ee(t*i*i),u=i,c=ee(i*gn),s=a===e,d=a===ee(-e),l=a===ee(-e*gn);return s&&(i=u),(d||l)&&(i=c),(ee(i)&1n)===1n&&(i=ee(-i)),!s&&!d?null:i}function Ea(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=ee(t*t),n=ya(ee(r-1n),ee(pa*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function ba(e,t){let r=Buffer.concat([...e,Lt(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=lr("sha256").update(r).digest();if(Ea(n))throw new Error("envelope: derived Solana program address is on curve");return Sn.encode(n)}function fr(e,t,r=An){let n=[Lt(e,"owner"),Lt(r,"token program"),Lt(t,"mint")];for(let o=255;o>=0;o--)try{return ba([...n,Buffer.from([o])],vn)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function xa(e,t){return(t.accountIndices||[]).map(r=>oe(e.staticAccounts[r]))}function pt(e){return Buffer.from(e.data||[])}function Sa(e,t){return oe(e.staticAccounts[t.programAddressIndex])}function In(e,t){return Number(t)<e.header.numSignerAccounts}function Aa(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 mt(e){return e.accountIndices||[]}function ur(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function En(e,t){let r=mt(t).map(n=>{let o=In(e,n)?"s":"n",i=Aa(e,n)?"w":"r";return`${n}:${oe(e.staticAccounts[n])}:${o}:${i}`});return $t(Buffer.from(r.join(`
|
|
2
|
-
`)))}function bn(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function va(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function Ia(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function ka(e,t,r){let n=r.maxJupiterRoutePlanSteps===void 0?1:Number(r.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(t<1||t>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(r.jupiterRouteVariants)?r.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=r.jupiterRouteVariantPayloadBytes||{},a=0,u=0,c=[];for(let s=0;s<t;s++){if(a>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e[a++];if(!o.includes(d))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(d)))throw new Error("policy: Jupiter route variant payload size required");let l=Number(i[String(d)]);if(!Number.isSafeInteger(l)||l<0||l>16)throw new Error("policy: Jupiter route variant payload size invalid");if(a+l+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e.subarray(a,a+l);a+=l;let p=f.toString("hex"),m=r.jupiterRouteVariantPayloads?.[String(d)];if(!Array.isArray(m)||!m.map(String).includes(p))throw new Error("policy: Jupiter route variant payload not allowed");let h=e[a++],g=e[a++],w=e[a++];if(h<1||h>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(g!==s||w!==s+1)throw new Error("envelope: unsupported Jupiter route-plan token index");u+=h,c.push(Object.freeze({swapVariant:d,variantPayloadHex:p,percent:h,inputIndex:g,outputIndex:w}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(u!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function Ta(e,t){let r=pt({data:e}),n=r.subarray(0,8).toString("hex"),o=ma.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,a=o.prefixBytes===1?r[8]:null;if(o.prefixBytes===1&&r.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let u=8+o.prefixBytes,c=u+4,s=r.length-i;if(s<=c)throw new Error("envelope: malformed Jupiter route payload");let d=Ia(r,u,"route plan length"),l=r.subarray(c,s),f=ka(l,d,t);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:d,routePlan:f,routePlanHash:$t(l),inAmount:bn(r,s,"in_amount"),quotedOutAmount:bn(r,s+8,"quoted_out_amount"),slippageBps:va(r,s+16,"slippage_bps"),platformFeeBps:r[s+18],instructionHash:$t(r)})}function Oa(e,t,r){let n=xa(e,t),o=(i,a)=>{let u=n[i];if(!u)throw new Error(`envelope: Jupiter ${a} account missing`);return u};if(r.instruction==="route"){if(n.length<9)throw new Error("envelope: Jupiter route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),userTransferAuthority:o(1,"userTransferAuthority"),userSourceTokenAccount:o(2,"userSourceTokenAccount"),userDestinationTokenAccount:o(3,"userDestinationTokenAccount"),destinationTokenAccount:o(4,"destinationTokenAccount"),destinationMint:o(5,"destinationMint"),platformFeeAccount:o(6,"platformFeeAccount"),eventAuthority:o(7,"eventAuthority"),program:o(8,"program")}}if(r.instruction==="shared_accounts_route"){if(n.length<13)throw new Error("envelope: Jupiter shared route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),programAuthority:o(1,"programAuthority"),userTransferAuthority:o(2,"userTransferAuthority"),userSourceTokenAccount:o(3,"sourceTokenAccount"),programSourceTokenAccount:o(4,"programSourceTokenAccount"),programDestinationTokenAccount:o(5,"programDestinationTokenAccount"),userDestinationTokenAccount:o(6,"destinationTokenAccount"),sourceMint:o(7,"sourceMint"),destinationMint:o(8,"destinationMint"),platformFeeAccount:o(9,"platformFeeAccount"),token2022Program:o(10,"token2022Program"),eventAuthority:o(11,"eventAuthority"),program:o(12,"program")}}throw new Error("envelope: unsupported Jupiter account layout")}function xn(e,t){return e&&e!==t?e:null}function re(e,t,r){let n=oe(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function Ca(e,t){let r=pt(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 Na(e,t,r,n,o,i){let a=pt(t);if(a.length!==1||a[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let u=mt(t);if(u.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=re(e,u[0],"ATA payer"),s=re(e,u[1],"ATA account"),d=re(e,u[2],"ATA owner"),l=re(e,u[3],"ATA mint"),f=re(e,u[4],"ATA system program"),p=re(e,u[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!==dr)throw new Error("envelope: Jupiter ATA system program mismatch");if(p!==o)throw new Error("envelope: Jupiter ATA token program mismatch");if(l!==n.inputMint&&l!==n.outputMint)throw new Error("envelope: Jupiter ATA mint mismatch");if(s!==fr(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:s,debit:i}}function La(e,t,r,n,o){let i=mt(t),a=pt(t);if(i.length!==2||a.length!==12||a.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let u=re(e,i[0],"wrap payer"),c=re(e,i[1],"wrap target"),s=a.readBigUInt64LE(4);if(u!==r.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(s!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return s}function $a(e,t,r,n){let o=mt(t),i=pt(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||re(e,o[0],"syncNative account")!==n)throw new Error("envelope: Jupiter syncNative account mismatch");return{kind:"syncNative"}}if(i[0]===9){if(o.length!==3)throw new Error("envelope: malformed Jupiter closeAccount helper");let a=re(e,o[0],"closeAccount source"),u=re(e,o[1],"closeAccount destination"),c=re(e,o[2],"closeAccount authority");if(a!==n||u!==r.owner||c!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function Ba(e,t,r,n,o,i,a){let u=fr(t.owner,t.artifact.inputMint,a);if(o.userSourceTokenAccount!==u)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=te(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<fa)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let s=new Map,d=0n,l=!1,f=!1;for(let p of e.instructions){if(p===n)continue;let m=Sa(e,p);if(m===ua)Ca(p,r);else if(m===vn){let{ata:h,debit:g}=Na(e,p,t,t.artifact,a,c);s.set(h,g)}else if(m===dr)d+=La(e,p,t,u,i);else if(m===a){let h=$a(e,p,t,u);h.kind==="syncNative"&&(l=!0),h.kind==="closeAccount"&&(f=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(d>0n&&(!l||!f))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(d!==0n&&d!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...s.values()].reduce((p,m)=>p+m,0n)}function Ra(e){let t;try{t=ca().decode(wa(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 Pa(e,t,r){if(e.header.numSignerAccounts!==1||oe(e.staticAccounts[0])!==t.owner||!he(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=oe(e.staticAccounts[o.programAddressIndex]);if(!i||!he(i,r.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function _a(e,t,r){let n=te(r.lamportsPerSignature,"lamportsPerSignature");if(n<da)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:te(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),a=i*n,u=i*o;if(t.exactFeeLamports!==void 0){let s=te(t.exactFeeLamports,"exactFeeLamports");if(s<a)throw new Error("policy: Solana exact fee below the base signature fee");if(s>u)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=u;if(c>te(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function Fa(e,t,r,n){let o=0n,i=!1;for(let a of e.instructions){if(oe(e.staticAccounts[a.programAddressIndex])!==dr)throw new Error("envelope: unsupported Solana program decoder");let c=a.accountIndices||[];if(c.length!==2||oe(e.staticAccounts[c[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let s=oe(e.staticAccounts[c[1]]);if(s!==t.destination||!he(s,r.destinations))throw new Error("envelope: Solana destination mismatch");let d=Buffer.from(a.data||[]);if(d.length!==12||d.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=d.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>te(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function Da(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!==la)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!he(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=ha(r);if(!he(o.inputMint,i)||!he(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=te(o.inAmount,"inAmount"),u=te(o.outAmount,"outAmount"),c=te(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>te(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>te(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(u<=0n||c<=0n||c>u)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let s=oe(o.jupiterProgram);if(!s||!he(s,r.programs)||!n.includes(s))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(v=>oe(e.staticAccounts[v.programAddressIndex])===s);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=d[0],f=Ta(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(!ur(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(f.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(f.inAmount!==a)throw new Error("envelope: Jupiter route in_amount mismatch");if(f.quotedOutAmount!==u)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(f.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let p=f.quotedOutAmount-f.quotedOutAmount*BigInt(f.slippageBps)/10000n;if(c!==p)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(f.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let m=Oa(e,l,f),h=mt(l),g=f.instruction==="shared_accounts_route"?2:1;if(!In(e,h[g]))throw new Error("envelope: Jupiter transfer authority must be signer");if(m.program!==s)throw new Error("envelope: Jupiter program account mismatch");if(m.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(m.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(m.sourceMint!==void 0&&m.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let w=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[An];if(!he(m.tokenProgram,w))throw new Error("policy: Solana token program not allowed");let E=fr(t.owner,o.outputMint,m.tokenProgram);if(m.userDestinationTokenAccount!==E)throw new Error("envelope: Jupiter destination token account is not owner ATA");let b=xn(m.destinationTokenAccount,s);if(b&&b!==E)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(xn(m.platformFeeAccount,s))throw new Error("policy: Jupiter platform fee account not allowed");if(!ur(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(En(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let S=$t(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,En(e,l)].join(`
|
|
3
|
-
`)));if(!ur(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(S))throw new Error("policy: Jupiter route review hash not allowed");let I=Ba(e,t,r,l,m,a,m.tokenProgram),T=a+I;if(T>te(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:T,programs:n}}function pr(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(!he(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=Ra(r),i=Pa(o,e,t),a=e.action==="transfer"?Fa(o,e,t,i):Da(o,e,t,i),u=_a(o,r,t);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+u).toString(),fee:u.toString(),programs:Object.freeze(a.programs)})}function mr(e,t){let{unit:r,value:n,notional:o,fee:i}=pr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}var xd=64*1024;var qa=1e8;function wr(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=qa+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var ja=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),Ua=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),za=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"}),Wa=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"}),Se=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function Ha(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 kn(e,t){let r=F(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 de(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=>de(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)}:${de(e[n],t)}`).join(",")}}`}function Ja(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)||de(r,"declared order type")!==de({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(de(r,"declared order type")!==de({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||de(r,"declared order type")!==de({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 Ga(e,t,r){let n=kn(e.s,"signed size"),o=kn(e.p,"signed price"),i=n.decimals+o.decimals,a=n.raw*o.raw,u=_(t.notionalUsd,i,"hl: notionalUsd");if(u<=0n||a!==u)throw new Error("hl: signed notional must match");let c=_(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(a>c)throw new Error("hl: notional exceeds cap")}function Va(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=Se(r.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(H(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(u=>String(u).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=J(r.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let a=_(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>a)throw new Error("hl: order builder fee exceeds cap")}function Tn(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(F(e.s,"hl: signed size")!==F(t.size,"hl: size"))throw new Error("hl: signed size must match");if(F(e.p,"hl: signed price")!==F(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(de(e.t,"signed order type")!==de(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 On(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(F(e.s,"hl: bracket protection size")!==F(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(F(e.p,"hl: bracket protection price")!==F(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(F(i.triggerPx,"hl: triggerPx")!==F(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function Ka(e){let t=String(e||"").replace(/\/$/,"");if(!ja.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function hr(e){return wr(e)!=null}function Xa(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(hr(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 Ya(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(a=>{if(typeof a=="string"){let[u,c]=String(a).split(":");return u===e&&Number(c)===t}return String(a?.coin)===e&&Number(a?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(hr(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 Ae(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=Se(r.kind,"kind",48),o=za[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=Ka(r.submitTo);if(Object.prototype.hasOwnProperty.call(r,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let a=Number(r.nonce);if(!Number.isSafeInteger(a)||a<=0)throw new Error("hl: nonce must be a positive integer");if(!r.action||typeof r.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(r.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(r.action.type!==Wa[n])throw new Error("hl: action type must match kind");let u=r.notionalUsd??0;if(Ua.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let c=Se(r.coin,"coin",64),s=r.assetId??r.assetIndex;if(!Number.isSafeInteger(s)||s<0)throw new Error("hl: assetId required");if(n==="hip4-order"||s>=1e8){let d=wr(c);if(!d||d.coin!==c)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==s)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(Xa(c,t),Ya(c,s,t),n==="hip4-order"&&!hr(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");Ja(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");Tn(d[0],r,s);let m=1;l!=null&&On(d[m++],r,s,l,"tp"),f!=null&&On(d[m],r,s,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");Tn(d[0],r,s)}Ga(d[0],r,t),Va(r,t),u=F(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!==s)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(r.orderId)||r.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(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!==s)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(r.action.leverage)||r.action.leverage!==r.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(r.marginMode))throw new Error("hl: declared margin mode required");let 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!==s)throw new Error("hl: signed margin asset must match assetId");let d=Se(r.usd,"margin usd",64),l=_(d,6,"hl: margin usd");if(J(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");u=Ha(m,6)}}if(n==="builder-fee-approval"){let c=Se(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(Se(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=Se(r.maxFeeRate,"maxFeeRate",32);if(Se(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)!==a)throw new Error("hl: signed builder nonce must match");let p=i.includes("testnet")?"Testnet":"Mainnet";if(r.hyperliquidChain!==p||r.action.hyperliquidChain!==r.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(r.signatureChainId!=="0x66eee"||r.action.signatureChainId!==r.signatureChainId)throw new Error("hl: signed signature chain id must match")}if(n.startsWith("hype-stake")||n==="hype-delegate"||n==="hype-undelegate"){if(n==="hype-delegate"||n==="hype-undelegate"){let c=n==="hype-undelegate";if(typeof r.action.isUndelegate!="boolean"||r.action.isUndelegate!==c)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(t.maxHypeWei!=null&&BigInt(String(r.action.wei??r.caps?.amountHype??"0"))>BigInt(t.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(u??r.action.wei??0),notional:String(u??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??u??0),coin:r.coin||null,submitTo:i})}import{createHmac as Qa}from"node:crypto";var Qe="0x"+"00".repeat(32);function gr(e={}){let t=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,r=e.polyApiSecret||process.env.POLYMARKET_API_SECRET||process.env.POLY_API_SECRET,n=e.polyPassphrase||process.env.POLYMARKET_API_PASSPHRASE||process.env.POLY_API_PASSPHRASE;if(!t||!r||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(t),secret:String(r),passphrase:String(n)}}function Cn({creds:e,address:t,method:r,path:n,body:o="",nowSec:i}={}){if(!e?.key||!e?.secret||!e?.passphrase)throw new Error("poly: L2 credentials required");if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("poly: L2 address required");let a=String(i??Math.floor(Date.now()/1e3)),u=String(r||"").toUpperCase(),c=String(n||"");if(u!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let s=a+u+c+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),f=Qa("sha256",l).update(s).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:f,POLY_TIMESTAMP:a,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function Za(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 es(e){let t=typeof e=="bigint"?e:Y(e,"poly: atomicUsdc");if(t<=0n)throw new Error("poly: order amounts must be positive integer micro-units");let r=t/1000000n,n=(t%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return n?`${r.toString()}.${n}`:r.toString()}function Nn(e,t){let r=Y(e.makerAmount,"poly: makerAmount"),n=Y(e.takerAmount,"poly: takerAmount");return es(t==="BUY"?r:n)}function ts(e){let t=typeof e=="bigint"?e.toString(10):F(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 Ln({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=Za(e,t);if(H(e.metadata||Qe,"poly: metadata").toLowerCase()!==Qe)throw new Error("poly: metadata must be zero");if(H(e.builder||Qe,"poly: builder").toLowerCase()!==Qe)throw new Error("poly: builder must be zero");let a=ts(e.salt);return{deferExec:!1,order:{builder:Qe,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:Qe,salt:String(a),side:i,signature:r,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var rs=new Set(["https://clob.polymarket.com/order"]),wt=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Fd=Object.freeze(wt.map(e=>e[0])),ns=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),os="0xe111180000d2663c0091e4f400237545b87b996b",is="0xe2222d279d744050d28e00520010520000310f59",$n=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function Bn(e){let t=String(e||"").replace(/\/$/,"");if(!rs.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function Rn(e){let t=H(e,"poly: exchange").toLowerCase();if(!ns.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function ve(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=$n(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(H(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(Bn(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(Rn(o.verifyingContract),Rn(r.exchange),H(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==H(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?is:os;if(H(r.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let a=r.message||r.value;if(!a||typeof a!="object")throw new Error("poly: signed order message required");let u=r.types?.Order;if(!Array.isArray(u)||u.length!==wt.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let v=0;v<wt.length;v+=1)if(u[v]?.name!==wt[v][0]||u[v]?.type!==wt[v][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(H(a.maker,"poly: maker").toLowerCase()!==c)throw new Error("poly: maker must equal owner");if(H(a.signer,"poly: signer").toLowerCase()!==c)throw new Error("poly: signer must equal owner");if(a.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof a.builder!="string"||a.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(a.side!==0&&a.side!==1)throw new Error("poly: side must be BUY or SELL");let s=$n(r.tokenId,"tokenId",80);if(H(a.tokenId,"poly: tokenId")!==s)throw new Error("poly: tokenId mismatch");let d=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(d.length&&!d.includes(s)&&!d.includes("*"))throw new Error("poly: tokenId not allowed");let l=Number(a.side)===0?"BUY":"SELL";if(r.side&&r.side!==l)throw new Error("poly: side mismatch");let f=Y(a.makerAmount,"poly: makerAmount"),p=Y(a.takerAmount,"poly: takerAmount"),m=Y(r.makerAmount,"poly: prepared makerAmount"),h=Y(r.takerAmount,"poly: prepared takerAmount");if(f!==m)throw new Error("poly: signed makerAmount differs from prepared envelope");if(p!==h)throw new Error("poly: signed takerAmount differs from prepared envelope");let g=l==="BUY"?f:p,w=l==="BUY"?p:f,E=_(r.quantity,6,"poly: quantity");if(E<=0n||E!==w)throw new Error("poly: quantity must match CLOB v2 amounts");let b=_(r.price,6,"poly: price");if(b<=0n||b>=1000000n)throw new Error("poly: price must be within (0,1)");if(w*b!==g*1000000n)throw new Error("poly: price must match CLOB v2 amounts");if(_(r.notionalUsdc,6,"poly: notionalUsdc")!==g)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let I=Nn(a,l);if(_(I,6,"poly: displayed notionalUsdc")!==g)throw new Error("poly: displayed notionalUsdc must match CLOB v2 amounts");let T=t.maxNotionalUsd??t.maxNotionalUsdc;if(T!=null){let v=_(T,6,"poly: maxNotionalUsd");if(g>v)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:g.toString(),notional:g.toString(),fee:"0",kind:n,tokenId:s,side:l,makerAmount:f.toString(),takerAmount:p.toString(),price:String(r.price),quantity:String(r.quantity),notionalUsdc:I,submitTo:Bn(r.submitTo)})}var as=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),yr=14,Pn=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function Ze(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function Er(e){let t=String(e||"").replace(/\/$/,"");if(!as.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function Ie(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=Pn(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=Er(r.submitTo),i=r.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=Number(J(r.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: accountIndex required");let u=Number(J(r.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(u)||u<0)throw new Error("lighter: clientOrderIndex required");Ze(r.orderType,0,"orderType"),Ze(r.timeInForce,1,"timeInForce"),Ze(r.reduceOnly,0,"reduceOnly"),Ze(r.triggerPrice,0,"triggerPrice"),Ze(r.orderExpiry,-1,"orderExpiry");let c=Pn(r.symbol||r.coin,"symbol",32),s=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(s.length&&!s.includes(c)&&!s.includes(String(i))&&!s.includes("*"))throw new Error("lighter: market not allowed");if(r.side!=="buy"&&r.side!=="sell")throw new Error("lighter: side must be buy or sell");let d=Y(r.baseAmount,"lighter: baseAmount"),l=Y(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),h=Number(r.priceDecimals??0);if(!Number.isInteger(m)||m<0||m>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(h)||h<0||h>12)throw new Error("lighter: priceDecimals required");let g=m+h,w=d*l,E=_(r.notionalUsd,g,"lighter: notionalUsd");if(E<=0n)throw new Error("lighter: notionalUsd required");if(w!==E)throw new Error("lighter: notionalUsd must match size and price");let b=_(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,g,"lighter: maxNotionalUsd");if(w>b)throw new Error("lighter: notional exceeds cap");let S=F(r.notionalUsd,"lighter: notionalUsd");return Ze(r.txType,yr,"txType"),Object.freeze({unit:"usd",value:String(S),notional:String(S),fee:"0",kind:n,symbol:c,marketIndex:i,side:r.side,baseAmount:f,price:p,submitTo:o,actionType:"create-order",amount:String(S)})}import{TypedDataEncoder as Dn,getAddress as ie}from"ethers";import{TypedDataEncoder as Ud,getAddress as zd,isAddress as Wd}from"ethers";var _n=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),br=Object.freeze({Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"receiver",type:"address"},{name:"makerAsset",type:"address"},{name:"takerAsset",type:"address"},{name:"makingAmount",type:"uint256"},{name:"takingAmount",type:"uint256"},{name:"makerTraits",type:"uint256"}]});import{TypedDataEncoder as tf,getAddress as rf,isAddress as nf}from"ethers";var Gd=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});var Fn=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),df=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var xr=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),ff=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});var cs=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"]),us="0x0000000000000000000000000000000000000000";function Sr(e,t,r=256){if(typeof e!="string"||!e||e.length>r)throw new Error(`evm-order: bounded ${t} required`);return e}function Mn(e,t){let r=String(e||"").replace(/\/$/,"");if(!cs.some(o=>r===`${o}/v4.0/${t}`||r===`${o}/v4.1/${t}`))throw new Error("evm-order: submitTo must be the official 1inch orderbook");return r}function qn(e,t){let r={1:"https://api.cow.fi/mainnet/api/v1/orders",100:"https://api.cow.fi/xdai/api/v1/orders",42161:"https://api.cow.fi/arbitrum_one/api/v1/orders",8453:"https://api.cow.fi/base/api/v1/orders"}[Number(t)],n=String(e||"").replace(/\/$/,"");if(!r||n!==r)throw new Error("evm-order: cow submitTo must be official api.cow.fi");return n}function jn(e,t){let r=e?.Order,n=t.Order;return!Array.isArray(r)||r.length!==n.length?!1:r.every((o,i)=>o?.name===n[i].name&&o?.type===n[i].type)}function Un(e,...t){let r=Array.isArray(e.tokens)?e.tokens.map(n=>String(n).toLowerCase()):[];if(!r.length)throw new Error("evm-order: tokens allowlist is empty");if(!r.includes("*")){for(let n of t)if(!r.includes(String(n).toLowerCase()))throw new Error("evm-order: token not allowed")}}function zn(e,t,{allowZero:r=!1}={}){let n=String(t||"").toLowerCase();if(!n)throw new Error("evm-order: receiver required");if(n===us){if(!r)throw new Error("evm-order: receiver must equal owner");return}if(n!==e)throw new Error("evm-order: receiver must equal owner")}function Pe(e,t){if(e?.surface!=="evm-order")throw new Error("evm-order: surface evm-order required");if(e.action!=="order")throw new Error("evm-order: action must be order");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("evm-order: structured artifact required");let n=Sr(r.kind,"kind",32);if(n==="option")throw new Error("evm-order: option kind refused until official Derive/Lyra domain is pinned");if(n==="cow"){let l=Number(r.chainId??e.chainId);if(qn(r.submitTo,l),Sr(e.destination,"destination",32)!=="cowswap")throw new Error("evm-order: cow destination must be cowswap");let f=Fn[l];if(!f)throw new Error(`evm-order: unsupported cow chainId ${l}`);let p=r.domain||r.typedData?.domain,m=r.types||r.typedData?.types,h=r.message||r.typedData?.message;if(!p||!m?.Order||!h)throw new Error("evm-order: CoW EIP-712 Order required");if(!jn(m,xr))throw new Error("evm-order: cow types must be official GPv2 Order");if(Number(p.chainId)!==l)throw new Error("evm-order: cow domain chain mismatch");if(String(p.name)!=="Gnosis Protocol"||String(p.version)!=="v2")throw new Error("evm-order: cow domain must be official GPv2");if(ie(p.verifyingContract)!==ie(f))throw new Error("evm-order: cow verifyingContract must be official GPv2 settlement");let g=String(e.owner||"").toLowerCase();zn(g,h.receiver),Un(t,h.sellToken,h.buyToken);let w=ie(h.sellToken),E=String(h.feeAmount||"0"),b=(BigInt(h.sellAmount)+BigInt(E)).toString();return Object.freeze({unit:`erc20:${w.toLowerCase()}`,value:b,notional:b,fee:E,submitTo:qn(r.submitTo,l),digest:Dn.hash(p,{Order:xr.Order},h),chainId:l,kind:"cow",receiver:ie(h.receiver),sellAmount:String(h.sellAmount),buyAmount:String(h.buyAmount)})}if(n!=="1inch-limit")throw new Error("evm-order: unsupported kind");if(Sr(e.destination,"destination",32)!=="1inch-lop")throw new Error("evm-order: destination must be 1inch-lop");let o=Number(r.chainId??e.chainId),i=_n[o];if(!i)throw new Error(`evm-order: unsupported chainId ${o}`);Mn(r.submitTo,o);let a=r.domain||r.typedData?.domain,u=r.types||r.typedData?.types,c=r.message||r.typedData?.message;if(!a||!u?.Order||!c)throw new Error("evm-order: EIP-712 Order required");if(!jn(u,br))throw new Error("evm-order: types must be official LOP v4 Order");if(Number(a.chainId)!==o)throw new Error("evm-order: domain chain mismatch");if(ie(a.verifyingContract)!==ie(i))throw new Error("evm-order: verifyingContract must be official LOP v4");if(a.name!=="1inch Limit Order Protocol"||String(a.version)!=="4")throw new Error("evm-order: EIP-712 domain must be official LOP v4");let s=String(e.owner||"").toLowerCase();if(ie(c.maker).toLowerCase()!==s)throw new Error("evm-order: maker must equal owner");zn(s,c.receiver,{allowZero:!0}),Un(t,c.makerAsset,c.takerAsset);let d=Dn.hash(a,{Order:br.Order},c);return Object.freeze({unit:`erc20:${ie(c.makerAsset).toLowerCase()}`,value:String(c.makingAmount),notional:String(c.makingAmount),fee:"0",submitTo:Mn(r.submitTo,o),digest:d,chainId:o,kind:"1inch-limit",receiver:ie(c.receiver),makerAsset:ie(c.makerAsset),takerAsset:ie(c.takerAsset),makingAmount:String(c.makingAmount),takingAmount:String(c.takingAmount)})}var Kn=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]);var Ar=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,delegate:0,identity:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0}),ls=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Xn=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),ds=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),Bt=new Vn(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Wn=new Vn(["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"]),fs=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 gt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},k=(e,t)=>{try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`envelope: ${t} must be a non-negative integer`)}},Hn=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},ps=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},q=(e,t,r)=>{if(!ps(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},ht=(e,t,r)=>{Array.isArray(t)&&t.length&&q(e,t,r)},$=(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},_e=e=>String(e||"0x").slice(0,10).toLowerCase(),Yn=e=>k(e.gasLimit,"gasLimit")*k(e.maxFeePerGas??e.gasPrice,"feePerGas")+k(e.l1FeeWei??0,"l1FeeWei")+k(e.operatorFeeWei??0,"operatorFeeWei");function et(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 z(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function ae(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function ms(e){if(_e(e)!=="0x095ea7b3")return null;let t=et(e,2,"approval");return{kind:"approval",spender:z(t.word(0),"approval spender"),amount:ae(t.word(1),"approval amount")}}function Qn(e,t){let r=t==="router02-exact-input-single"?7:8,n=et(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:z(n.word(0),"input token"),outputToken:z(n.word(1),"output token"),recipient:z(n.word(3),"recipient"),amountIn:ae(n.word(o),"amountIn"),minimumOut:ae(n.word(o+1),"amountOutMinimum")}}function ws(e){let t=et(e,12,"Across depositV3",{dynamicTail:!0}),r=ae(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:z(t.word(0),"depositor"),recipient:z(t.word(1),"recipient"),inputToken:z(t.word(2),"input token"),outputToken:z(t.word(3),"output token"),amountIn:ae(t.word(4),"inputAmount"),minimumOut:ae(t.word(5),"outputAmount"),destinationChainId:ae(t.word(6),"destinationChainId")}}function hs(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 Jn(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 g=10;g+64<=r.length;g+=64)n.push(r.slice(g,g+64));let o=(g,w)=>{if(!n[g])throw new Error(`envelope: malformed ${w}`);return BigInt(`0x${n[g]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let a=i/32,u=Number(o(a,"path offset")),c=n[a+1],s=o(a+(t?3:2),"amountIn"),d=o(a+(t?4:3),"amountOutMinimum"),l=a+u/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let f=Number(o(l,"path length")),p=r.slice(10+(l+1)*64,10+(l+1)*64+f*2),{inputToken:m,outputToken:h}=hs(`0x${p}`);return{kind:"action",action:"swap",inputToken:m,outputToken:h,recipient:z(c,"recipient"),amountIn:s,minimumOut:d}}function gs(e){let t=et(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:z(t.word(0),"input token"),outputToken:z(t.word(1),"output token"),recipient:z(t.word(3),"recipient"),amountIn:ae(t.word(5),"amountIn"),minimumOut:ae(t.word(6),"amountOutMinimum")}}function ys(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let f=10;f+64<=t.length;f+=64)r.push(t.slice(f,f+64));let n=Number(BigInt(`0x${r[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${r[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let a=Number(BigInt(`0x${r[o+1]}`)),u=o+1+a/32,c=Number(BigInt(`0x${r[u]}`)),d=`0x${t.slice(10+(u+1)*64,10+(u+1)*64+c*2)}`,l=_e(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Qn(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function Es(e,t){let r=_e(e),n=Xn[r];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed selector");if(n.layout==="router02-exact-input-single"||n.layout==="swap-router-exact-input-single")return{...Qn(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...Jn(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...Jn(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...ys(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...gs(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...ws(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function bs(e){let t=et(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:z(t.word(0),"mint NFT contract"),feeRecipient:z(t.word(1),"mint fee recipient"),recipient:z(t.word(2),"mint recipient"),quantity:ae(t.word(3),"mint quantity")}}function xs(e){let t;try{t=Wn.decodeFunctionData("mintAllowList",e)}catch{throw new Error("envelope: malformed SeaDrop mintAllowList calldata")}let r=t[4],n=[...t[5]].map(String);if(n.length<1||n.length>64||n.some(c=>!/^0x[0-9a-fA-F]{64}$/.test(c)))throw new Error("envelope: bounded canonical SeaDrop allowlist proof required");if(Wn.encodeFunctionData("mintAllowList",[t[0],t[1],t[2],t[3],r,n]).toLowerCase()!==String(e).toLowerCase())throw new Error("envelope: SeaDrop allowlist calldata must be canonical");let i=BigInt(r.startTime),a=BigInt(r.endTime);if(a<=i)throw new Error("envelope: SeaDrop allowlist stage time range is invalid");let u=BigInt(t[3]);if(BigInt(r.maxTotalMintableByWallet)<u)throw new Error("envelope: SeaDrop allowlist wallet cap is below quantity");return{kind:"mint",action:"mint",mintType:"allowlist",contract:$(t[0],"mint NFT contract"),feeRecipient:$(t[1],"mint fee recipient"),recipient:$(t[2],"mint recipient"),quantity:u,mintPrice:BigInt(r.mintPrice),startTime:i,endTime:a,dropStageIndex:BigInt(r.dropStageIndex),proof:n}}function Ss(e,t){let r=_e(e);if(String(t).toLowerCase()==="nft-mint")return As(e);let n=ds[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{...bs(e),selector:r,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...xs(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function As(e){let t=_e(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=fs[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=et(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:ae(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function Rt(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 Zn(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=$(e.owner,"owner"),u=e.artifact,c=Number(u?.chainId??Rt(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(q(c,t.chains,"chain"),u?.owner!==void 0&&$(u.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let s=Rt(e);if(!s.length||s.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,l=0n,f=0n;for(let p of s){if(!p||typeof p!="object"||Array.isArray(p))throw new Error("envelope: structured EVM transaction required");if(Number(p.chainId)!==c)throw new Error("envelope: every batch leg must use the same chain");if($(p.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(q(_e(p.data),t.selectors,"selector"),d+=k(p.value??0,"value"),l+=k(p.gasLimit,"gasLimit"),f+=Yn(p),ue(c)&&(p.l1FeeWei===void 0||p.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>k(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>k(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(f>k(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:s,chainId:c,owner:a,totalValue:d,totalGas:l,totalFee:f}}function eo(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=gt(e.provider,"provider",64).toLowerCase();q(i,t.providers,"provider");let a=Zn(e,t,o,{nowMs:r}),u=[],c=-1;for(let m=0;m<a.transactions.length;m++){let h=a.transactions[m],g=ms(h.data),w;if(g){if(c!==-1)throw new Error("envelope: approval must be before action");if(k(h.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let S=$(h.to,"approval token");if(q(S,t.tokens,"token"),q(g.spender,t.spenders,"spender"),g.amount>k(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");w={...g,token:S,index:m}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");q(h.to,t.destinations,"destination"),w={...Es(h.data,i),target:$(h.to,"action target"),index:m},c=m}let E=k(h.value??0,"value"),b=k(h.gasLimit,"gasLimit");u.push({...w,value:E,gas:b,fee:Yn(h)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let s=u[c],d=o==="evm-swap"?"swap":"bridge";if(s.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if($(e.destination,"destination")!==s.target)throw new Error("envelope: destination must equal decoded action target");if(s.recipient!==a.owner)throw new Error("envelope: decoded recipient must equal owner");if(s.depositor&&s.depositor!==a.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(q(s.inputToken,t.tokens,"input token"),q(s.outputToken,t.tokens,"output token"),s.amountIn<=0n||s.amountIn>k(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(s.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(nr(e.autoSlippage,{nowMs:r,chainId:a.chainId,venue:i,tx:a.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(s.minimumOut!==k(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(s.action==="bridge"&&k(e.toChainId,"toChainId")!==s.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=u.filter(m=>m.kind==="approval");if(!new Set([...ls,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(m=>String(m).toLowerCase()):[]]).has(s.inputToken))throw new Error("envelope: strict local signer swap/bridge requires native input token; use wallet signing for token-unit rails");if(l.length)throw new Error("envelope: native-value action must not include token approval");if(s.value!==s.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let p=Object.freeze({quoteAmountOut:k(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:k(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...a,decoded:u,action:s,provider:i,authenticatedQuote:p}}function vs(e,t,{nowMs:r}){let n=e.anvilAttestation,o=e.artifact?.anvilAttestation;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("envelope: Anvil attestation is required");if(!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: Anvil attestation artifact mismatch");if(Number(n.version)!==1||n.source!=="anvil-snapshot-rpc-reviewed-runtime")throw new Error("envelope: unsupported Anvil attestation");if(Number(n.chainId)!==4663)throw new Error("envelope: Anvil attestation chain mismatch");let i=$(e.destination,"Anvil market"),a=$(e.contract,"NFT contract"),u=$(e.paymentToken,"payment token");if($(n.market,"attested Anvil market")!==i)throw new Error("envelope: Anvil attestation market mismatch");if($(n.collection,"attested NFT collection")!==a)throw new Error("envelope: Anvil attestation collection mismatch");if($(n.paymentToken,"attested payment token")!==u)throw new Error("envelope: Anvil attestation payment token mismatch");let c=Number(e.paymentTokenDecimals??e.artifact?.paymentTokenDecimals);if(!Number.isSafeInteger(c)||c<0||c>255||Number(n.paymentTokenDecimals)!==c)throw new Error("envelope: Anvil payment token decimals mismatch");let s=k(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei").toString();if(k(n.nativeSwapFeeWei,"attested nativeSwapFeeWei").toString()!==s)throw new Error("envelope: Anvil attestation native swap fee mismatch");let d=Number(n.snapshotFetchedAtMs),l=Number(n.snapshotExpiresAtMs);if(!Number.isFinite(d)||!Number.isFinite(l)||d>r||l<=r||l<=d)throw new Error("envelope: Anvil snapshot attestation is stale");let f=k(n.blockNumber,"attested blockNumber");if(f<=0n||!/^0x[0-9a-f]{64}$/.test(String(n.blockHash||"").toLowerCase()))throw new Error("envelope: Anvil block attestation is invalid");let p=String(n.runtimeCodeHash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(p))throw new Error("envelope: Anvil runtime code hash is invalid");let m=Object.entries(t.anvilRuntimeCodeHashes||{}).find(([g])=>g.toLowerCase()===i)?.[1];if(!m||String(m).toLowerCase()!==p)throw new Error("policy: Anvil runtime code hash is not reviewed");let h=Object.entries(t.nftPaymentTokenCaps||{}).find(([g])=>g.toLowerCase()===u)?.[1];if(!h||Number(h.decimals)!==c)throw new Error("policy: Anvil payment token decimals are not reviewed");return Object.freeze({...n,market:i,collection:a,paymentToken:u,paymentTokenDecimals:c,runtimeCodeHash:p,blockNumber:f})}function Gn(e,t){let r=e.artifact,n=e.anvilQuote,o=r?.anvilQuote;if(!n||typeof n!="object"||Array.isArray(n)||!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: exact Anvil quote artifact mismatch");if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("envelope: exact Anvil quote confirmation required");let i=t==="buy"?[[n.totalCostRaw,"anvilQuote.totalCostRaw"],[e.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw"],[r?.maxPaymentTokenAmountRaw,"artifact maxPaymentTokenAmountRaw"],[e.exactQuoteTotalCostRaw,"exactQuoteTotalCostRaw"],[r?.exactQuoteTotalCostRaw,"artifact exactQuoteTotalCostRaw"],[e.preconditions?.confirmedTotalCostRaw,"confirmedTotalCostRaw"]]:[[n.netPayoutRaw,"anvilQuote.netPayoutRaw"],[e.minPayoutRaw,"minPayoutRaw"],[r?.minPayoutRaw,"artifact minPayoutRaw"],[e.exactQuoteNetPayoutRaw,"exactQuoteNetPayoutRaw"],[r?.exactQuoteNetPayoutRaw,"artifact exactQuoteNetPayoutRaw"],[e.preconditions?.confirmedNetPayoutRaw,"confirmedNetPayoutRaw"]],a=k(i[0][0],i[0][1]);for(let[u,c]of i.slice(1))if(k(u,c)!==a)throw new Error(`envelope: Anvil ${t} exact settlement limit mismatch`);return a}function to(e,t,{nowMs:r=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint or NFT action");let n=gt(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();ht(n,t.providers,"provider");let o=Zn(e,t,"evm-nft",{nowMs:r});if(n==="anvil-nft"){if(e.action!=="nft")throw new Error("envelope: Anvil requires NFT action");if(o.chainId!==4663)throw new Error("envelope: Anvil requires chain 4663");if(t.confirmationMode!=="exact-human")throw new Error("policy: Anvil requires exact-human confirmation");if(o.transactions.length!==1)throw new Error("envelope: Anvil requires one atomic action with pre-existing approval");if(Number(e.slippageBps)!==0)throw new Error("envelope: Anvil exact limit requires zero slippageBps");let[p]=o.transactions,m=$(e.destination,"Anvil market");if($(p.to,"Anvil action target")!==m)throw new Error("envelope: Anvil action target mismatch");q(m,t.destinations,"destination");let h=$(e.contract??e.artifact?.contract,"NFT contract");if(ht(h,t.nftContracts,"NFT contract"),$(e.marketCollection??e.artifact?.marketCollection,"Anvil market collection")!==h)throw new Error("envelope: Anvil market collection mismatch");let w=$(e.paymentToken??e.artifact?.paymentToken,"payment token");ht(w,t.erc20Tokens,"ERC20 token");let E=vs(e,t,{nowMs:r}),b=k(e.tokenId??e.artifact?.tokenId,"tokenId"),S=k(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei");if(o.totalValue!==S||k(p.value??0,"Anvil action value")!==S)throw new Error("envelope: Anvil native swap fee mismatch");if(S>k(t.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"))throw new Error("policy: Anvil native swap fee exceeds cap");let I=gt(e.nftAction,"nftAction",8).toLowerCase(),T;if(I==="buy"){let v=Gn(e,I),C=Object.entries(t.nftPaymentTokenCaps||{}).find(([ce])=>ce.toLowerCase()===w)?.[1];if(!C)throw new Error("policy: Anvil payment-token cap required");if(v>k(C.maxPerTradeRaw,"maxPerTradeRaw"))throw new Error("policy: Anvil payment amount exceeds cap");if(e.preconditions?.allowanceVerified!==!0||k(e.preconditions?.allowanceRaw,"allowanceRaw")<v)throw new Error("envelope: Anvil pre-existing allowance proof required");let R=Bt.decodeFunctionData("buySpecificNFT",p.data);if(Bt.encodeFunctionData("buySpecificNFT",[R[0],R[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil buy calldata");if(BigInt(R[0])!==b)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(R[1])!==v)throw new Error("envelope: Anvil maxCost mismatch");T={kind:"nft",action:"buy",tokenId:b,maxPaymentTokenAmountRaw:v,target:m}}else if(I==="sell"){let v=e.preconditions||{},C=$(v.approvedAddress,"NFT approval address");if(v.nftApprovalVerified!==!0||C!==m&&v.approvedForAll!==!0)throw new Error("envelope: Anvil pre-existing NFT approval proof required");let R=Gn(e,I),j=Bt.decodeFunctionData("sellNFT",p.data);if(Bt.encodeFunctionData("sellNFT",[j[0],j[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil sell calldata");if(BigInt(j[0])!==b)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(j[1])!==R)throw new Error("envelope: Anvil minPayout mismatch");T={kind:"nft",action:"sell",tokenId:b,minPayoutRaw:R,target:m}}else throw new Error("envelope: unsupported Anvil NFT action");return{...o,provider:n,nftAction:I,tokenId:b,paymentToken:w,paymentTokenDecimals:E.paymentTokenDecimals,anvilAttestation:E,decoded:[T]}}let i=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;if(i?.oraclePrepared===!0&&dn(i,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"}),o.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let a=o.transactions[0],u=_e(a.data);q(u,t.selectors,"selector"),q(a.to,t.destinations,"destination");let c=Ss(a.data,n),s=$(e.contract??e.artifact?.contract,"NFT contract");if(ht(s,t.nftContracts,"NFT contract"),(c.contract||$(a.to,"NFT contract"))!==s)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==o.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&ht(c.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let l=k(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>k(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=k(e.totalWei??e.artifact?.totalWei,"totalWei");if(o.totalValue!==f)throw new Error("envelope: mint value does not match declared totalWei");if(c.mintType==="allowlist"){let p=BigInt(Math.floor(r/1e3));if(c.startTime>p||c.endTime<=p)throw new Error("policy: SeaDrop allowlist stage is not open");if(c.mintPrice*l!==f)throw new Error("envelope: SeaDrop allowlist price does not match declared totalWei")}if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&k(e.priceWei??e.artifact.priceWei,"priceWei")*l!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>k(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...o,provider:n,decoded:[{...c,target:$(a.to,"mint target"),value:o.totalValue,gas:o.totalGas,fee:o.totalFee}]}}function Is(e,{localsWaiver:t=!1}={}){if(!(e in Ar))throw new Error("fee: unknown action");return t?0:Ar[e]}function yt(e,t,{nowMs:r=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:a=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let u=gt(e.surface,"surface",16);if(!Kn.has(u))throw new Error("envelope: unsupported public surface");let c=gt(e.action,"action",32);q(u,t.surfaces,"surface"),q(c,t.actions,"action"),q(e.owner,t.owners,"owner"),q(e.destination,t.destinations,"destination");let s=Hn(t.maxTtlMs,"maxTtlMs"),d=Hn(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>s)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>d)throw new Error("policy: slippage exceeds cap");let l=e.artifact;if(!l||typeof l!="object"||Array.isArray(l))throw new Error("envelope: structured artifact required");if(u==="evm-swap"||u==="evm-bridge")eo(e,t,{nowMs:r,routeAttestationSecret:o});else if(u==="evm-nft")to(e,t,{nowMs:r});else if(u==="evm"){if(!["transfer","approve","delegate","identity"].includes(c))throw new Error(c==="mint"?"envelope: generic evm requires transfer or approve; use strict evm-nft for mint action":"envelope: generic evm requires transfer, approve, delegate, or identity");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(Number(l.type)===4&&c!=="delegate")throw new Error("envelope: type-4 requires delegate");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");Nt({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:a});let m=String(l.data||"0x").toLowerCase(),h=k(l.value,"EVM value");if(c==="delegate"){if(Number(l.type)!==4)throw new Error("envelope: delegate requires type-4");if(m!=="0x")throw new Error("envelope: 7702 delegate calldata must be empty");if(h!==0n)throw new Error("envelope: 7702 delegate cannot transfer native value")}else if(c==="identity"){if(h!==0n)throw new Error("envelope: ERC-8004 identity cannot transfer native value");let g=m.slice(0,10);if(g!=="0xf2c298be"&&g!=="0x0af28bd3")throw new Error("envelope: ERC-8004 selector not allowed")}else if(m==="0x"){if(h===0n)throw new Error("envelope: native EVM transfer value required")}else if(Q(m)){if(h!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else u==="btc"?cr(e,t):u==="sol"?mr(e,t):u==="hl"?Ae(e,t):u==="poly"?ve(e,t):u==="lighter"?Ie(e,t):u==="evm-order"&&Pe(e,t);let f=Number(e.fee?.oracleFeeBps)===0&&Ar[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=Is(c,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==p)throw new Error("fee: final artifact fee mismatch");return!0}var vr=Object.freeze([...Kn]),Cf=Object.freeze({...Xn});function Ir(e,t){if(e.surface==="hl")return Ae(e,t);if(e.surface==="poly")return ve(e,t);if(e.surface==="lighter")return Ie(e,t);if(e.surface==="evm-order")return Pe(e,t);if(e.surface==="btc")return cr(e,t);if(e.surface==="sol")return mr(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=eo(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=to(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalFee.toString();if(r.provider==="anvil-nft"&&r.nftAction==="buy"){let i=k(e.maxPaymentTokenAmountRaw??e.artifact?.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw").toString(),a=r.totalValue.toString(),u=r.totalFee,c=[{unit:`erc20:${r.paymentToken}`,value:i,notional:i,fee:"0"},{unit:"wei",value:a,notional:(r.totalValue+u).toString(),fee:u.toString()}].sort((s,d)=>s.unit<d.unit?-1:s.unit>d.unit?1:0);return Object.freeze({units:c})}let o=r.totalValue.toString();return Object.freeze({unit:"wei",value:o,notional:(r.totalValue+r.totalFee).toString(),fee:n})}if(String(e.surface).startsWith("evm")){let r=k(e.artifact?.value,"EVM value"),n=k(e.artifact?.gasLimit,"EVM gasLimit"),o=k(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+k(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+k(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 ro(e={}){let t={};for(let r of vr){let n=e[r];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${r} requires simulate, sign, and broadcast functions`);t[r]=Object.freeze({simulate:(o,i)=>n.simulate(structuredClone(o),structuredClone(i)),sign:(o,i)=>n.sign(structuredClone(o),structuredClone(i)),broadcast:(o,i,a)=>n.broadcast(o,structuredClone(i),structuredClone(a))})}}return Object.freeze(t)}function Pt(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 uo}from"node:crypto";import{ed25519 as _s}from"@noble/curves/ed25519.js";import{base58 as fo}from"@scure/base";import{RawTx as Lr,SigHash as Fe,Transaction as $r}from"@scure/btc-signer";import{Transaction as Br,keccak256 as Cr,verifyTypedData as Nr}from"ethers";import{encode as ks}from"@msgpack/msgpack";import{keccak256 as Ts,verifyTypedData as Os}from"ethers";var tt=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),kr=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function no(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 Cs(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(ks(e)),no(t)];if(r){let a=String(r).replace(/^0x/i,"");if(!/^[0-9a-fA-F]{40}$/.test(a))throw new Error("hl-l1: vaultAddress must be a 20-byte address");i.push(Buffer.from([1]),Buffer.from(a,"hex"))}else i.push(Buffer.from([0]));return n!=null&&i.push(Buffer.from([0]),no(n)),Ts(Buffer.concat(i))}function Tr(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:Cs(e,t,{vaultAddress:n,expiresAfter:o})}}function oo(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=Tr(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==tt.name||String(t.domain?.version)!==tt.version||Number(t.domain?.chainId)!==tt.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(tt.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(kr.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 io({wallet:e,action:t,nonce:r,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let a=Tr(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(tt,kr,a)}function ao({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:a=null}){try{let u=Tr(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:a}),c=Os(tt,kr,u,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var Ns=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function Or(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)Or(t);return}for(let t of Object.values(e))Or(t)}}}function Ls(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 Or(e),JSON.parse(JSON.stringify(e))}function _t(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 $s(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 so(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 nt(e,t,r,n={}){let o=t.filter(a=>e[a]!==void 0&&e[a]!==null);if(o.length===0)throw new Error(`lighter: ${r} required`);let i=o.map(a=>so(e[a],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function Bs(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 rt(e,t,r,n){let o=nt(e,t,n);if(BigInt(o)!==_t(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Rs(e,t,r,n){let o=nt(e,t,n,{signed:!0});if(BigInt(o)!==$s(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Ps(e){let t={};for(let[r,n]of Ns.entries()){let o=n.filter(a=>e[a]!==void 0&&e[a]!==null);if(!o.length)continue;let i=o.map(a=>{let u=e[a];if(r<3)return so(u,n[0]);if(typeof u!="string"||u.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return u});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);t[n[0]]=i[0]}return t}function Et(e,t){let r=Ls(t),n=rt(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=rt(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=rt(r,["Type","type"],e.orderType,"Type"),a=rt(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),u=rt(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),c=rt(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),s=Rs(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=nt(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=nt(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),f=nt(r,["Price","price"],"Price");if(BigInt(d)!==_t(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==_t(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==_t(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let p=Bs(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,h=e.side==="sell";if(m!==h)throw new Error("lighter: signed IsAsk must match the prepared side");let g=nt(r,["txType","tx_type","TxType"],"txType");if(g!==yr)throw new Error("lighter: signed txType must be official create-order");let w={...Ps(r),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:a,ReduceOnly:u,TriggerPrice:c,OrderExpiry:s,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(f),IsAsk:m?1:0,txType:g},E=JSON.stringify(w),b=JSON.parse(E);if(b.MarketIndex!==Number(d)||b.BaseAmount!==Number(l)||b.Price!==Number(f)||b.IsAsk!==(m?1:0)||b.txType!==g)throw new Error("lighter: canonical tx_info mutated");return{txType:g,txInfo:E,submitTo:Er(e.submitTo)}}function co(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var ot=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},Ft=e=>String(e||"").toLowerCase();function Fs(e,t){if(typeof e!="string")return!1;let r,n;try{r=Br.from(e),n=Br.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce,type:t.type,accessList:t.accessList,authorizationList:t.authorizationList})}catch{return!1}return Ft(r.from)!==Ft(t.from)||Ft(r.to)!==Ft(t.to)?!1:r.unsignedHash===n.unsignedHash}function Ds(e){let t=Buffer.from(Lr.encode(e)),r=uo("sha256").update(t).digest();return Buffer.from(uo("sha256").update(r).digest()).reverse().toString("hex")}function lo(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Ds(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 Ms(e,t){let r=ot(e),n=ot(t.psbt);if(!r||!n)return!1;try{let o=$r.fromPSBT(n),i=$r.fromPSBT(r);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let a=0;a<i.inputsLength;a++){let u=i.getInput(a),c=o.getInput(a);if(!lo(c)||!lo(u))return!1;let s=(w,E)=>{if(w==null&&E==null)return!0;if(w==null||E==null)return!1;try{return Buffer.from(w).equals(Buffer.from(E))}catch{return!1}},d=(w,E)=>{if(w==null&&E==null)return!0;if(w==null||E==null)return!1;try{return Buffer.from(Lr.encode(w)).equals(Buffer.from(Lr.encode(E)))}catch{return s(w,E)}};if(!!u.witnessUtxo!=!!c.witnessUtxo||u.witnessUtxo&&(BigInt(u.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!s(u.witnessUtxo.script,c.witnessUtxo.script))||!d(u.nonWitnessUtxo,c.nonWitnessUtxo)||!s(u.redeemScript,c.redeemScript)||!s(u.witnessScript,c.witnessScript)||u.sighashType!==void 0&&u.sighashType!==Fe.DEFAULT&&u.sighashType!==Fe.ALL)return!1;let l=w=>!(w instanceof Uint8Array)||w.length<9?!1:w[w.length-1]===Fe.ALL,f=w=>w instanceof Uint8Array?w.length===64?!0:w.length===65&&w[64]===Fe.ALL:!1;for(let w of u.partialSig||[]){let E=Array.isArray(w)?w[1]:w;if(!l(E))return!1}if(u.tapKeySig&&!f(u.tapKeySig))return!1;for(let w of u.tapScriptSig||[]){let E=Array.isArray(w)?w[1]:w;if(!f(E))return!1}let p=w=>w[w.length-1]===Fe.ALL,m=w=>w.length>=9&&w.length<=73&&w[1]===w.length-3&&w[2]===2,h=w=>{let E=!1;for(let b of w)if(b instanceof Uint8Array){if(b[0]===48){if(!m(b)||!p(b))return!1;E=!0;continue}if(b.length===64){E=!0;continue}if(b.length===65){if(b[64]!==Fe.ALL&&b[64]!==Fe.DEFAULT)return!1;E=!0}}return E};if(u.finalScriptWitness){let w;if(Array.isArray(u.finalScriptWitness))w=u.finalScriptWitness;else if(u.finalScriptWitness instanceof Uint8Array){let E=u.finalScriptWitness,b=T=>{let v=E[T];return v===void 0?null:v<253?{value:v,next:T+1}:v===253?{value:E[T+1]|E[T+2]<<8,next:T+3}:null},S=b(0);if(!S)return!1;w=[];let I=S.next;for(let T=0;T<S.value;T++){let v=b(I);if(!v||I+v.value>E.length)return!1;w.push(E.slice(v.next,v.next+v.value)),I=v.next+v.value}if(I!==E.length)return!1}else return!1;if(!w.length||!h(w))return!1}if(u.finalScriptSig instanceof Uint8Array&&u.finalScriptSig.length){let w=u.finalScriptSig,E=[],b=0;for(;b<w.length;){let S=w[b];if(S>=1&&S<=75){if(b+1+S>w.length)return!1;E.push(w.slice(b+1,b+1+S)),b+=1+S;continue}if(S===76){let I=w[b+1];if(I===void 0||b+2+I>w.length)return!1;E.push(w.slice(b+2,b+2+I)),b+=2+I;continue}return!1}if(!E.length||!h(E))return!1}if(![u.partialSig,u.tapKeySig,u.tapScriptSig,u.finalScriptSig,u.finalScriptWitness].some(w=>Array.isArray(w)||w instanceof Uint8Array?w.length>0:w!=null))return!1}return!0}catch{return!1}}function po(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 qs(e,t,r){let n=ot(e),o=ot(t.messageBase64);if(!n||!o)return!1;let i=po(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let u=n.subarray(i.offset,a),c=n.subarray(a);if(!c.equals(o))return!1;try{let s=fo.decode(String(r));return s.length===32&&_s.verify(u,c,s)}catch{return!1}}function mo(e,t,r,n){if(e==="evm-order"){let o=r?.domain||r?.typedData?.domain,i=r?.types||r?.typedData?.types,a=r?.message||r?.typedData?.message;if(!o||!i||!a)return!1;try{return String(Nr(o,i,a,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}}if(String(e).startsWith("evm"))return Fs(t,r);if(e==="btc")return Ms(t,r);if(e==="sol")return qs(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String(Nr(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return ao({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(Nr(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Et(r,t),!0}catch{return!1}return!1}function wo(e,t){try{if(e==="evm-order")return Cr(t);if(String(e).startsWith("evm"))return Br.from(t).hash;if(e==="btc"){let r=ot(t);if(!r)return null;let n=$r.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=ot(t);if(!r)return null;let n=po(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?fo.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return Cr(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return Cr(t)}catch{}return null}var Ws=e=>String(e||"").toLowerCase();function G(e){return js("sha256").update(JSON.stringify(e)).digest("hex")}function qt(e,t,r={}){return Nt(e,t,r)}async function Hs(e,t={}){if(!ue(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 go(e,t,r=!1){if(!ue(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 Dt=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=Us(32).toString("hex");return this.#e.set(o,{digest:G(t),owner:Ws(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(G(r),"hex");if(!zs(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(t)),n}clear(){this.#e.clear()}};function Js(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(Q(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 Gs(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 Vs(e){return e==="evm"||e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Mt(e,t){let r=String(t||"");if(e==="evm-order"||String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(r);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(r);if(e==="sol")try{let n=ho.decode(r);return n.length===64&&ho.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 yo(e,t,r){return!Mt(e,t)||!Mt(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function Ks(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 Rr({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:u}){let c=Ks(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(t?.triggerAttestation,e,u())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(a)return n.confirmations.consume(r,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=u())throw new Error("confirmation: expired nonce");return i}function Xs(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Ys(e,t){return e&&Xs(e.surface)?Rt(e):[t]}function Qs(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!yo(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function Zs(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:Gs(r,n)}}async function Pr(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:g,...w}=e||{};return w})(),i=Ys(n,o),a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,u=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),c=await Rr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:null,consumeNonce:!0,nowMs:u}),s=G(e),d=(g={})=>{n?yt(n,a,g):(qt(o,a,{nowMs:g.nowMs,networkFees:g.networkFees,requireNetworkFees:g.requireNetworkFees}),Js(o))},l=async g=>{let w=!n||Vs(n.surface),E=w?await Hs(g,r):void 0;return{nowMs:u(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:E,requireNetworkFees:w&&ue(g?.chainId)}};d({nowMs:u(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let g of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[g]!="function")throw new Error(`signer: ${g} is required`);let f=r.reserveLedger(n||e,a);if(!f)throw new Error("signer: ledger reservation required");let p=!1,m=[];try{for(let g of i){if(typeof r.simulate!="function"||await r.simulate(g,n)!==!0)throw new Error("signer: strict affirmative simulation required");let w=await l(g);if((w.requireNetworkFees||w.networkFees!=null)&&go(g,w.networkFees,w.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await Rr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:u}),d(w),r.validateReservation(f,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0),p=!0;let E=await r.sign(g,n);if(typeof r.verifySigned!="function"||await r.verifySigned(E,g,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!r.isArmed())throw new Error("signer: disarmed before broadcast");if(G(e)!==s)throw new Error("signer: artifact mutated after signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await Rr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:u});let b=await l(g);(b.requireNetworkFees||b.networkFees!=null)&&go(g,b.networkFees,b.requireNetworkFees),d(b),r.validateReservation(f,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0);let S=await r.broadcast(E,g,n),I=S?.status,T=n?.surface||"evm",v=Qs(S,T),C=wo(T,E);if(!yo(T,v,C))throw new Error("signer: receipt transaction hash does not match signed bytes");if(I===0||I==="0x0")throw Mt(T,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(I!==1&&I!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Mt(T,v))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(Zs(S,v))}}catch(g){throw p||r.releaseLedger(f),g}if(r.commitLedger(f),m.length===1){let g={receipt:m[0]};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}let h={receipts:m,status:"success"};return n?.surface==="evm-bridge"&&(h.originStatus="success",h.destinationStatus="unverified",h.destinationSuccess=!1,h.note="Origin-chain receipts do not prove destination-chain settlement."),h}var Eo=new Set(["127.0.0.1","::1","localhost"]),rc=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&tc(r,n)},O=(e,t,r)=>{let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function nc(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 bt=e=>new Promise((t,r)=>{let n=0,o=[],i=!1;e.on("data",a=>{n+=a.length,n>64*1024&&!i?(i=!0,r(new Error("request refused")),e.resume()):i||o.push(a)}),e.on("end",()=>{if(!i)try{t(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{r(new Error("request refused"))}}),e.on("error",r)});function bo(e={}){let t=e.host||"127.0.0.1";if(!Eo.has(t))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let c of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[c]!="function")throw new Error(`signer: ${c} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Dt,n=e.pending||new Map;function o(c){let s=c.artifact?.version===1&&c.artifact?.surface?c.artifact:null,d=s?.artifact||c.artifact||{};return{id:c.digest.slice(0,8),digest:c.digest,surface:s?.surface||"evm",action:s?.action||"evm",chain:d.chainId??d.network??null,to:d.to||s?.destination||null,value:d.value??d.message?.sellAmount??d.message?.makingAmount??null,receiver:d.message?.receiver||d.typedData?.message?.receiver||null,maker:d.message?.maker||d.typedData?.message?.maker||null,makingAmount:d.message?.makingAmount||d.typedData?.message?.makingAmount||null,takingAmount:d.message?.takingAmount||d.typedData?.message?.takingAmount||null,sellAmount:d.message?.sellAmount||d.typedData?.message?.sellAmount||null,buyAmount:d.message?.buyAmount||d.typedData?.message?.buyAmount||null,kind:d.kind||null,type:d.type??null,authorizationList:d.authorizationList||null,feeAmount:d.message?.feeAmount||d.typedData?.message?.feeAmount||null,createdAtMs:c.createdAtMs}}function i(c){let s=String(c||"").trim().toLowerCase().replace(/^0x/,"");return s?[...n.values()].filter(d=>d.digest.toLowerCase().startsWith(s)||d.digest.slice(0,8)===s):[...n.values()]}let a=e.origin||`http://${t}`;return ec.createServer(async(c,s)=>{try{let d=String(c.headers.authorization||"").replace(/^Bearer /i,"");if(!rc(d,e.token))return O(s,401,{error:"unauthorized"});let l=nc(c.headers.host);if(!Eo.has(l))return O(s,403,{error:"host refused"});if(c.headers.origin&&c.headers.origin!==a)return O(s,403,{error:"origin refused"});if(c.method==="GET"&&c.url==="/status"){let f=typeof e.readPolicy=="function"?e.readPolicy():e.policy,p=new Set(vr),m=Array.isArray(f?.surfaces)?f.surfaces.filter(h=>typeof h=="string"&&p.has(h)):[];return O(s,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:m,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(c.method==="POST"&&c.url==="/disarm")return e.disarm(),r.clear(),n.clear(),O(s,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(c.method))return O(s,405,{error:"request refused"});if(c.method==="POST"&&String(c.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return O(s,415,{error:"request refused"});if(c.method==="GET"&&c.url==="/pending"){let f=[...n.values()].map(o);return O(s,200,{ok:!0,armed:e.isArmed?.()===!0,count:f.length,items:f})}if(c.method==="POST"&&c.url==="/pending"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not queue human approvals"});let p=(await bt(c)).artifact;if(!p||typeof p!="object")return O(s,400,{error:"artifact required"});let m=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(m?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});let h=typeof e.nowMs=="function"?e.nowMs():Date.now();if(p?.surface==="cex"){if(typeof e.inspectCex!="function")return O(s,403,{error:"cex execution unavailable"});e.inspectCex(p,m,h)}else if(p?.version===1&&p?.surface)yt(p,m,{nowMs:h,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:E,...b}=p||{};qt(b,m,{nowMs:h})}let g=G(p),w=p?.surface==="cex"?Object.freeze(structuredClone(p)):p;return n.set(g,{artifact:w,digest:g,createdAtMs:h}),O(s,200,{ok:!0,...o(n.get(g))})}if(c.method==="POST"&&c.url==="/ack"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not accept messaging acks"});let f=await bt(c),p=i(f.digest||f.id);if(p.length===0)return O(s,404,{error:"no pending artifact"});if(p.length>1)return O(s,409,{error:"ambiguous digest; pass more hex"});let m=p[0];if((typeof e.readPolicy=="function"?e.readPolicy():e.policy)?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});if(e.isArmed?.()!==!0)return O(s,403,{error:"signer is disarmed"});if(m.artifact?.surface==="cex"){if(typeof e.verifyCexOwnerProof!="function"||e.verifyCexOwnerProof(f.ownerProof,{digest:m.digest})!==!0)return O(s,403,{error:"exact owner Allow proof required"});if(typeof e.cexExecute!="function")return O(s,403,{error:"cex execution unavailable"});n.delete(m.digest);let E=await e.cexExecute(m.artifact);return O(s,200,{ok:!0,executed:!0,digest:m.digest,id:m.digest.slice(0,8),result:E})}n.delete(m.digest);let g=r.issue({artifact:m.artifact,owner:m.artifact?.owner??m.artifact?.from,ttlMs:f.ttlMs}),w=await Pr(m.artifact,g,{...e,confirmations:r});return O(s,200,{ok:!0,executed:!0,confirmationNonce:g,digest:m.digest,id:m.digest.slice(0,8),result:w})}if(c.method==="POST"&&c.url==="/deny"){let f=await bt(c),p=i(f.digest||f.id);return p.length===0?O(s,404,{error:"no pending artifact"}):p.length>1?O(s,409,{error:"ambiguous digest; pass more hex"}):(n.delete(p[0].digest),O(s,200,{ok:!0,denied:!0,id:p[0].digest.slice(0,8)}))}if(c.method==="POST"&&c.url==="/confirm"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not issue human confirmation nonces"});let f=await bt(c);if(f.artifact?.surface==="cex")return O(s,403,{error:"cex requires pending owner ack"});let p=G(f.artifact),m=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(m?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});let h=typeof e.nowMs=="function"?e.nowMs():Date.now();if(f.artifact?.version===1&&f.artifact?.surface)yt(f.artifact,m,{nowMs:h,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:g,...w}=f.artifact||{};qt(w,m,{nowMs:h})}return typeof e.confirmArtifact!="function"?O(s,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(f.artifact,p,m)!==!0?O(s,400,{error:"exact human confirmation refused"}):O(s,200,{confirmationNonce:r.issue({artifact:f.artifact,owner:f.artifact?.owner??f.artifact?.from,ttlMs:f.ttlMs})})}if(c.method==="POST"&&c.url==="/execute"){let f=await bt(c);if(f.artifact?.surface==="cex")return O(s,403,{error:"cex requires pending owner ack"});let p=await Pr(f.artifact,f.confirmationNonce,{...e,confirmations:r});return O(s,200,p)}return O(s,404,{error:"not found"})}catch(d){e.onError?.(String(d?.message||d));let l=String(c.url||"");return l==="/pending"||l==="/ack"||l==="/deny"?O(s,400,{error:String(d?.message||"request refused").slice(0,300)}):O(s,400,{error:"request refused"})}})}import{createCipheriv as np,createDecipheriv as oc,randomBytes as ic,scryptSync as ac}from"node:crypto";import B from"node:fs";import it from"node:path";var sc="ORACLE-LOCAL-VAULT",cc=1,Ut=Object.freeze({N:1<<17,r:8,p:1}),uc=256*1024*1024,lc=16*1024;function jt(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 dc(e,t,r=Ut){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return ac(n,t,32,{...r,maxmem:uc})}function xo(e,t){if(e?.magic!==sc||e?.version!==cc)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!==Ut.N||e.kdf.r!==Ut.r||e.kdf.p!==Ut.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=jt(e.kdf.salt,32,"salt"),o=jt(e.cipher.iv,12,"iv"),i=jt(e.tag,16,"tag"),a=jt(e.ciphertext,1,"ciphertext",{max:lc}),{ciphertext:u,tag:c,...s}=e,d=dc(t,n);try{let l=oc("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(s))),l.setAuthTag(i),Buffer.concat([l.update(a),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function fc(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 pc(e){let t=it.dirname(e),r=B.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=B.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 N(e){let t;try{t=B.openSync(e,B.constants.O_RDONLY|B.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=B.fstatSync(t);if(fc(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=B.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 B.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{B.closeSync(t)}}function So(e){return JSON.parse(N(e))}function se(e,t){B.mkdirSync(it.dirname(e),{recursive:!0,mode:448}),pc(e);let r=it.join(it.dirname(e),`.${it.basename(e)}.${process.pid}.${ic(6).toString("hex")}.tmp`);try{let n=B.openSync(r,B.constants.O_CREAT|B.constants.O_EXCL|B.constants.O_WRONLY|B.constants.O_NOFOLLOW,384);try{B.writeFileSync(n,String(t)),B.fsyncSync(n)}finally{B.closeSync(n)}B.renameSync(r,e),B.chmodSync(e,384);let o=B.openSync(it.dirname(e),"r");try{B.fsyncSync(o)}finally{B.closeSync(o)}}catch(n){try{B.unlinkSync(r)}catch{}throw n}}var Ao=/^0x[0-9a-fA-F]+$/,mc=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});function wc(e){let t=process.env[`ORACLE_PRIVATE_RELAY_${Number(e)}`];if(!t)return null;let r=t.split(",").map(n=>n.trim()).filter(Boolean);return r.length?r:null}function hc(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=mc[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=wc(r),i=o||n.endpoints,a=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&a!=="public-only";if(t&&!u)throw new Error(`private relay: no keyless private endpoint for chain ${r} (${n.name}); set ORACLE_PRIVATE_RELAY_${r} to force one, or allow public fallback`);return{chainId:r,name:n.name,mode:a,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function vo(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!Ao.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let a=hc(t,{requirePrivate:r}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let c=[];for(let s of a.endpoints){let d=new AbortController,l=setTimeout(()=>d.abort(),i);try{let f=await u(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendRawTransaction",params:[e]}),signal:d.signal}),p=await f.text(),m=null;try{m=JSON.parse(p)}catch{}if(m&&m.result&&Ao.test(m.result))return{hash:m.result,endpoint:s,mode:a.mode,chainId:a.chainId,fellBack:!1};c.push({endpoint:s,error:m&&m.error&&m.error.message||`http ${f.status}`})}catch(f){c.push({endpoint:s,error:String(f&&f.message||f).slice(0,160)})}finally{clearTimeout(l)}}if(n&&!r)return{fellBack:!0,mode:a.mode,chainId:a.chainId,attempts:c};throw new Error(`submitPrivate: all private endpoints failed for chain ${a.chainId} (${c.map(s=>`${s.endpoint}:${s.error}`).join("; ")||"none configured"})`)}import{createHmac as yc,randomBytes as Ec,timingSafeEqual as bc}from"node:crypto";import W from"node:fs";import De from"node:path";import{homedir as _r}from"node:os";import{join as Fr}from"node:path";var Io=process.env.ORACLE_PUBLIC_DESKTOP==="1",gc=Io?process.env.ORACLE_CONFIG_DIR||Fr(_r(),".config","oracle"):Fr(_r(),".config","oracle"),lp=Io?gc:Fr(_r(),".config","mad-desk");var wp="0".repeat(64),hp=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 zt(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(zt).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+zt(e[r])).join(",")+"}"}var gp=Promise.resolve();function Me(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=a=>{try{return W.realpathSync(a)}catch{return De.resolve(a)}},n=r(De.dirname(De.resolve(e))),o=r(De.dirname(De.resolve(t))),i=(a,u)=>u===a||u.startsWith(a+De.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var xc=864e5,V=(e,t)=>yc("sha256",t).update(zt(e)).digest("hex"),fe=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&bc(r,n)},Sc=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Ac(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!fe(e.integrity.mac,V(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Ht(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=N(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!fe(n?.integrity?.mac,V(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 vc(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let u=Ht(e,r);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(t),policyMac:String(n)};i&&(a.ledgerInitialized=!0),se(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:V(a,r)}})+`
|
|
4
|
-
`)}function
|
|
5
|
-
`);let c={version:2,sequence:a.sequence,ledgerMac:u};se(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:
|
|
6
|
-
`);let s={version:1,sequence:a.sequence,ledgerMac:u};W.mkdirSync(De.dirname(n),{recursive:!0,mode:448}),se(n,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:
|
|
7
|
-
`),o&&Ic(o,r)}function xt({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:u=0,fee:c,units:s,policy:d,nowMs:l=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");Me(r,e);let p=N(t);return st(e,()=>{let m=at(e,p,l,r,n);if(m.entries.some(g=>String(g.tradeId)===f))throw new Error("ledger: replayed tradeId");let h;if(s!==void 0){let g=Dr(s);for(let w of g){let[E,b,S]=Wt(d,w.unit),I=BigInt(w.value),T=BigInt(w.notional);if(T>S)throw new Error("ledger: per-trade cap exceeded");if(ke(m.entries,"value",w.unit)+I>E||ke(m.entries,"notional",w.unit)+T>b)throw new Error("ledger: daily cap exceeded")}h={tradeId:f,units:g,state:"reserved",atMs:l}}else{let g=BigInt(a),w=BigInt(u),[E,b,S]=Wt(d,i);if(g<0n||w<0n||w>S)throw new Error("ledger: per-trade cap exceeded");if(ke(m.entries,"value",i)+g>E||ke(m.entries,"notional",i)+w>b)throw new Error("ledger: daily cap exceeded");h={tradeId:f,unit:i,value:g.toString(),notional:w.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:l}}return m.entries.push(h),Te(e,m,p,r,n),structuredClone(h)})}function ko({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:u=Date.now()}){Me(r,e);let c=N(t);return st(e,()=>{let s=at(e,c,u,r,n),d=s.entries.find(h=>String(h.tradeId)===String(o?.tradeId??"")&&h.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let h=Dr(o.units);if(JSON.stringify(h)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(a){if(!Array.isArray(a.units))throw new Error("ledger: reserved units no longer match decoded economics");let g=Dr(a.units);if(g.length!==d.units.length||g.some((w,E)=>w.unit!==d.units[E].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let w=0;w<g.length;w++)if(BigInt(g[w].value)>BigInt(d.units[w].value)||BigInt(g[w].notional)>BigInt(d.units[w].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let g of d.units){let[w,E,b]=Wt(i,g.unit);if(BigInt(g.notional)>b)throw new Error("ledger: per-trade cap exceeded");if(ke(s.entries,"value",g.unit)>w||ke(s.entries,"notional",g.unit)>E)throw new Error("ledger: daily cap exceeded")}return structuredClone(d)}if(d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(d.value)||BigInt(a.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[f,p,m]=Wt(i,l);if(BigInt(d.notional)>m)throw new Error("ledger: per-trade cap exceeded");if(ke(s.entries,"value",l)>f||ke(s.entries,"notional",l)>p)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function To({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(r,e);let a=N(t);return st(e,()=>{let u=at(e,a,i,r,n),c=u.entries.find(s=>String(s.tradeId)===String(o??"")&&s.state==="reserved");if(!c||c.state!=="reserved")throw new Error("ledger: reservation unavailable");return c.state="committed",c.committedAtMs=i,Te(e,u,a,r,n),structuredClone(c)})}function Oo({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(r,e);let a=N(t);return st(e,()=>{let u=at(e,a,i,r,n),c=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");let s=structuredClone(c);return c.state="consumed",c.releasedAtMs=i,Array.isArray(c.units)?c.units=c.units.map(d=>({...d,value:"0",notional:"0",fee:"0"})):(c.value="0",c.notional="0",c.fee="0"),Te(e,u,a,r,n),s})}function Oc(e,t){if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(e)))throw new Error("ledger: authoritative CEX fill invalid");let[r,n=""]=String(e).split("."),o=n.length;return BigInt(r+n)>BigInt(t)*10n**BigInt(o)}function Co({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:a,disposition:u,nowMs:c=Date.now()}){if(Me(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let s=N(t);return st(e,()=>{let d=at(e,s,c,r,n),l=d.entries.find(f=>f.tradeId===o&&f.state==="reserved"&&f.unit===i);if(!l)throw new Error("ledger: exact held CEX reservation unavailable");if(Oc(a,l.notional))throw new Error("ledger: CEX overfill refused; reservation retained");if(u==="release"){if(!/^0(?:\.0+)?$/.test(a))throw new Error("ledger: nonzero CEX fill cannot release");let f=structuredClone(l);return l.state="consumed",l.releasedAtMs=c,l.value="0",l.notional="0",l.fee="0",Te(e,d,s,r,n),f}return l.state="committed",l.committedAtMs=c,l.filledQuote=a,Te(e,d,s,r,n),structuredClone(l)})}function No({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(r,e);let a=N(t);return st(e,()=>{let u=at(e,a,i,r,n),c=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");if(Array.isArray(c.units))return c.state="committed",c.committedAtMs=i,c.units=c.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),c.settledAs=c.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",Te(e,u,a,r,n),structuredClone(c);let s=BigInt(c.fee??0);return s<=0n?(c.state="committed",c.committedAtMs=i,c.value="0",c.notional="0",c.settledAs="no-fee",Te(e,u,a,r,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=s.toString(),c.settledAs="fee-only",Te(e,u,a,r,n),structuredClone(c))})}function Lo(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:G(Sc(t))};return fe(e.mac,V(o,N(r)))}function Cc(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function $o(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:G(Cc(t))};return fe(e.mac,V(o,N(r)))}import{spawnSync as Nc}from"node:child_process";function Bo(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=Nc(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}var Lc=/^0x[0-9a-f]{40}$/,$c=/^0x(?:[0-9a-f]{2})*$/,Bc=/^(?:0x)?[0-9a-f]{64}$/,Rc=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Pc=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,_c=new Set([12,15,18,21,24]),Gt=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function Mr(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Pc.test(e)||_c.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new Gt(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,i)=>Mr(o,`${t}[${i}]`,r));qe(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(Rc.test(i))throw new Gt(`${t}.${o}`);e[o]!==void 0&&(n[o]=Mr(e[o],`${t}.${o}`,o))}return n}function qe(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function St(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function ct(e,t){let r=String(St(e,t)).toLowerCase();if(!Lc.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function ge(e,t,{positive:r=!1}={}){try{let n=BigInt(St(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function qr(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function Ro(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Ro(t);Object.freeze(e)}return e}function Fc(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};qe(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:qr(String(n),`${t}.reason`)}}function Dc(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Fc(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function Mc(e){if(e==null)return null;if(qe(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:qr(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=ge(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=ge(e.gasLimit,"simulation.gasLimit")),t}function qc(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{qe(t,`assetDeltas[${r}]`);let n=ge(t.before,`assetDeltas[${r}].before`),o=ge(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),a;try{a=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(a!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:qr(String(St(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:a}})}function jc(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{qe(t,`approvalDeltas[${r}]`);let n=ge(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:ct(t.token,`approvalDeltas[${r}].token`),spender:ct(t.spender,`approvalDeltas[${r}].spender`),owner:ct(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function Po(e={}){qe(e,"input");let t=Mr(e),r=t.tx==null?t:qe(t.tx,"tx"),n=ge(t.chainId??r.chainId,"chainId",{positive:!0}),o=ct(t.account??t.from??r.from,"account/from"),i=ct(t.destination??t.to??r.to,"destination/to"),a=String(St(t.prepareHash,"prepareHash")).toLowerCase();if(!Bc.test(a))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let u=t.route??t.venue;if(u==null)throw new TypeError("sign-time review: route/venue required");let c=t.decodedCalldata??t.decodedAction;if(c==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let s=String(St(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!$c.test(s))throw new TypeError("sign-time review: calldata/data must be even-length hex");let d=t.policyChecks!==void 0&&t.policyChecks!==null,l=Dc(d?t.policyChecks:[]),f=Mc(t.simulation),p=qc(t.assetDeltas),m=jc(t.approvalDeltas),h=t.allowlistHits??[];if(!Array.isArray(h))throw new TypeError("sign-time review: allowlistHits must be an array");let g=f?.willRevert===!0||["failed","error"].includes(f?.status),w=f!=null&&f.willRevert===!1&&["ok","success"].includes(f.status),E=g||l.failed>0?"BLOCKED":w&&d&&l.checks.length>0&&p!=null?"READY":"UNKNOWN",b=typeof c=="string"?c:c.method??c.action??c.type??"transaction",S=`${E}: review ${b} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${p?.length??0} asset delta${p?.length===1?"":"s"}; local signature required`,I={reviewVersion:1,status:E,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:u,venue:t.venue??(typeof u=="string"?u:u.venue??u.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:ct(t.spender,"spender")},prepareHash:a,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:s,data:s,selector:s.length>=10?s.slice(0,10):null,value:ge(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:ge(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:ge(t.gasLimit??r.gasLimit,"gasLimit")},simulation:f,policyChecks:l,allowlistHits:h,assetDeltas:p,approvalDeltas:m,summary:S};return Ro(I)}var Uc=/^0x[0-9a-f]{40}$/;function At(e){let t=String(e??"").toLowerCase();return Uc.test(t)?t:null}function zc(e,{token:t,owner:r}){if(!Q(e))return[];let n;try{n=Be(e)}catch{return[]}let o={token:At(n.token??t),spender:At(n.spender),owner:At(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function Wc(e,t,r={}){let n=e?.version===1&&e?.surface?e:null,o=n?.surface||"evm";if(o!=="evm"&&o!=="evm-nft")return null;let i=n?.artifact||e||{},a=At(n?.owner??i.from),u=At(i.to??n?.destination),c=String(i.data??"0x").toLowerCase();if(!a||!u)return null;let s=[],d=r?.destinationAllowlist;if(Array.isArray(d)&&d.length){let l=d.map(f=>String(f).toLowerCase()).includes(u);s.push({name:"destination-allowlist",passed:l,reason:l?"destination is allowlisted":"destination is not on the allowlist"})}try{return Po({chainId:i.chainId,account:a,destination:u,calldata:c,value:i.value??0,prepareHash:t,route:n?.provider??n?.venue??o,decodedAction:n?.action??"transaction",...i.gasLimit==null?{}:{gasLimit:i.gasLimit},...s.length?{policyChecks:s}:{},approvalDeltas:zc(c,{token:u,owner:a})})}catch{return null}}function _o(e,t,r={}){let n=Wc(e,t,r);if(!n)return[];let o=[`REVIEW status=${n.status} action=${n.decodedAction??"transaction"} selector=${n.selector??"none"}`,`REVIEW route=${typeof n.route=="string"?n.route:n.venue??"n/a"} value=${n.value} signing=local custody=${n.custody}`];n.policyChecks.checks.length&&o.push(`REVIEW policy passed=${n.policyChecks.passed} failed=${n.policyChecks.failed}${n.policyChecks.failed?` reasons=${n.policyChecks.reasons.join("; ")}`:""}`);for(let i of n.approvalDeltas)o.push(`REVIEW APPROVAL token=${i.token} spender=${i.spender} amount=${i.amount} revokeLike=${i.revokeLike}`);return n.assetDeltas==null&&o.push("REVIEW assetDeltas=unavailable (no simulated balance change supplied)"),n.status!=="READY"&&o.push("REVIEW status is not READY: these facts are decoded, not proven safe."),o}import{Wallet as jr}from"ethers";import{base58 as Ur}from"@scure/base";import{ed25519 as jo}from"@noble/curves/ed25519.js";import{NETWORK as Uo,TEST_NETWORK as zo,WIF as Hc,p2wpkh as Fo}from"@scure/btc-signer";import{pubECDSA as Jc}from"@scure/btc-signer/utils.js";var Vt=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Gc=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},Do=e=>{let t=String(e||"").trim();try{let r=Buffer.from(Ur.decode(t));return Ur.encode(r)===t?r:null}catch{return null}},zr=e=>{if(!(e instanceof Uint8Array))throw new Error("sol: key bytes required");if(e.length!==32&&e.length!==64)throw new Error("sol: expected 32-byte private key material");let t=Buffer.from(e.subarray(0,32));if(e.length===64){let r=Buffer.from(e.subarray(32,64)),n=Buffer.from(jo.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},Mo=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),ye=(e,t)=>{if(t==="sol")return zr(e);if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)},Vc=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return ye(r,t)};function Wr(e,t){let r=String(t||"").trim();if(e==="evm")return new jr(r).privateKey;if(e==="btc")for(let i of[Uo,zo])try{return Buffer.from(Hc(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let s=Vt(r.slice(4));if(!s)throw new Error("sol: invalid explicit hex private key");return ye(s,"sol")}if(/^base58:/i.test(r)){let s=Do(r.slice(7));if(!Mo(s))throw new Error("sol: invalid explicit base58 private key");return zr(s)}if(/^0x/i.test(r)){let s=Vt(r);if(!s)throw new Error("sol: invalid explicit hex private key");return ye(s,"sol")}let i=Vt(r),a=i&&(i.length===32||i.length===64)?ye(i,"sol"):null,u=Do(r),c=Mo(u);if(a&&c&&!a.equals(c))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(c)return zr(u);if(i)return ye(i,"sol")}let n=Vt(r);if(n)return e==="evm"?new jr(`0x${n.toString("hex")}`).privateKey:ye(n,e);let o=Gc(r);if(o)return ye(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return Vc(i,e);let a=i.privateKey??i.secretKey??i.key;if(a)return Wr(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function qo(e,t){if(e==="evm"){let r=new jr(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=ye(t,"btc"),n=Jc(r);return{kind:e,secret:r.toString("hex"),addresses:[Fo(n,Uo).address,Fo(n,zo).address]}}if(e==="sol"){let r=ye(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[Ur.encode(jo.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function Wo(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:qo(t.kind||"evm",Wr(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=qo(i,Wr(i,n[i])));if(n.cex!==void 0){if(!n.cex||typeof n.cex!="object"||Array.isArray(n.cex))throw new Error("local-vault: cex credential records invalid");o.cex={};for(let[i,a]of Object.entries(n.cex)){if(!/^[A-Za-z0-9._-]{1,64}$/.test(i)||!a||typeof a!="object")throw new Error("local-vault: cex credential record invalid");if(!/^(?:binance|bybit|okx|coinbase)$/.test(a.venue)||!/^[A-Za-z0-9._-]{1,64}$/.test(a.accountId||""))throw new Error("local-vault: cex credential binding invalid");let u=(s,d=!0)=>{let l=a[s];if(!(!d&&l===void 0)){if(!Array.isArray(l)||l.length<4||l.some(f=>!Number.isInteger(f)||f<0||f>255))throw new Error("local-vault: cex credential bytes invalid");return Buffer.from(l)}},c=a.apiSecretEncoding;if(c!==(a.venue==="coinbase"?"base64":"raw"))throw new Error("local-vault: explicit cex secret encoding refused");o.cex[i]=Object.freeze({venue:a.venue,accountId:a.accountId,apiKeyBytes:u("apiKeyBytes"),apiSecretBytes:u("apiSecretBytes"),apiSecretEncoding:c,passphraseBytes:u("passphraseBytes",!1)})}if(!Object.keys(o.cex).length)throw new Error("local-vault: empty cex credential records refused");Object.freeze(o.cex)}if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function Hr(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var Kc=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),Xc=Object.freeze(["binance","bybit","okx","coinbase"]),Yc=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Qc=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Zc=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),qp=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),eu=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),jp=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),Up=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),zp=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),Wp=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function Jr(e,t){let r=String(e??"");if(!/^\d+$/.test(r))throw new Error(`cex-policy: ${t} must be an integer string`);return BigInt(r)}function K(e,t,r){let n=String(e??"");if(!r.test(n))throw new Error(`cex-policy: bounded ${t} required`);return n}function Ho(e,t){let r=String(e??"");if(!/^(?:0|[1-9]\d{0,29})(?:\.\d{1,18})?$/.test(r))throw new Error(`cex-policy: positive decimal ${t} required`);let[n,o=""]=r.split("."),i=BigInt(`${n}${o}`);if(i<=0n)throw new Error(`cex-policy: positive decimal ${t} required`);return{text:r,numerator:i,scale:o.length}}function tu(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function ru(e){return new Date(e).toISOString().slice(0,10)}function nu(e,t){let r=K(e.credentialRef,"credentialRef",/^[A-Za-z0-9._-]{1,64}$/),n=t.cexAccounts?.[r];if(!n||typeof n!="object")throw new Error("cex-policy: sealed account policy required");return{credentialRef:r,account:n}}function Kt(e={},t={},r=Date.now()){for(let R of Object.keys(e)){let j=R.toLowerCase();if(eu.some(ce=>ce.toLowerCase()===j))throw new Error(`cex-policy: envelope field ${R} forbidden`);if(!Zc.includes(R))throw new Error(`cex-policy: envelope field ${R} not in allowlist`)}if(e.version!==1)throw new Error("cex-policy: version 1 required");if(e.surface!=="cex")throw new Error("cex-policy: surface cex required");let n=String(e.kind||"");if(!Kc.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=K(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!Xc.includes(o)||!Yc[o]||!Qc[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:a}=nu(e,t);if(!Array.isArray(a.venues)||!a.venues.includes(o))throw new Error(`cex-policy: venue ${o} not allowlisted`);let u=K(e.symbol,"symbol",/^[A-Z0-9._/-]{1,32}$/);if(!Array.isArray(a.symbols)||!a.symbols.includes(u))throw new Error(`cex-policy: symbol ${u} not allowlisted`);let c=K(e.quote,"quote",/^[A-Z0-9._-]{1,24}$/);if(!a.symbolQuotes||typeof a.symbolQuotes!="object"||a.symbolQuotes[u]!==c)throw new Error("cex-policy: quote does not match sealed symbol policy");let s=K(a.accountId,"accountId",/^[A-Za-z0-9._-]{1,64}$/);if(!Array.isArray(a.allowedOperations)||!a.allowedOperations.includes(n))throw new Error("cex-policy: operation not in sealed allowlist");let d=K(e.base,"base",/^[A-Z0-9._-]{1,24}$/);if(a.base!==d||a.quote!==c)throw new Error("cex-policy: base/quote do not match sealed account policy");if(a.credentialRecordRef!==i)throw new Error("cex-policy: credential record reference mismatch");let l=a.filters?.[u];if(!l||typeof l.tickSize!="string"||typeof l.stepSize!="string"||typeof l.minNotional!="string")throw new Error("cex-policy: sealed symbol filters required");K(e.nonce,"nonce",/^[A-Za-z0-9._:-]{1,128}$/),K(e.grantId,"grantId",/^[A-Za-z0-9._:-]{1,128}$/),K(e.artifactHash,"artifactHash",/^[A-Za-z0-9._:-]{1,128}$/);let f=e.clientOrderId===void 0?void 0:K(e.clientOrderId,"clientOrderId",/^[A-Za-z0-9._-]{1,64}$/),p,m,h,g,w=0n,E=0n,b;if(n==="spot-limit-create"){if(p=K(e.side,"side",/^(?:buy|sell)$/),m=K(e.timeInForce,"timeInForce",/^GTC$/),h=Ho(e.baseSize,"baseSize"),g=Ho(e.limitPrice,"limitPrice"),!f)throw new Error("cex-policy: clientOrderId required");if(w=Jr(e.maxQuoteNotional,"maxQuoteNotional"),E=tu(h,g),w<E)throw new Error("cex-policy: maxQuoteNotional understates baseSize times limitPrice")}else{for(let R of["side","baseSize","limitPrice","maxQuoteNotional","timeInForce"])if(e[R]!==void 0)throw new Error(`cex-policy: ${R} forbidden for cancel/status`);if(b=e.venueOrderId===void 0?void 0:K(e.venueOrderId,"venueOrderId",/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/),!b&&!f)throw new Error("cex-policy: exact prior order id required")}let S=Jr(a.perOrderQuoteCap,"sealed perOrderQuoteCap"),I=Jr(a.dailyGrossQuoteCap,"sealed dailyGrossQuoteCap");if(w>S)throw new Error("cex-policy: maxQuoteNotional exceeds sealed perOrderQuoteCap");if(w>I)throw new Error("cex-policy: maxQuoteNotional exceeds sealed dailyGrossQuoteCap");let T=Number(e.expiresAtMs);if(!Number.isSafeInteger(T)||T<=r||T-r>12e4)throw new Error("cex-policy: bounded expiry required");let v=`cex:${i}:${o}:${s}:${f||b}`,C=`cex:${i}:${s}:${o}:${c}:${ru(r)}`;return Object.freeze({kind:n,venue:o,symbol:u,base:d,quote:c,side:p,timeInForce:m,baseSize:h?.text,limitPrice:g?.text,clientOrderId:f,venueOrderId:b,filter:Object.freeze({...l}),accountId:s,credentialRef:i,tradeId:v,unit:C,notional:w.toString(),impliedNotional:E.toString()})}function Jo({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Jt(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Kt(e,n,r);return xt({file:t.ledger,keyFile:t.policyKey,anchorFile:t.ledgerAnchor,policyAnchorFile:t.policyAnchor,tradeId:o.tradeId,unit:o.unit,value:o.notional,notional:o.notional,policy:n,nowMs:r})}import D from"node:fs";import je from"node:path";import{createHmac as ou,randomBytes as iu,timingSafeEqual as au}from"node:crypto";var Xt=(e,t)=>ou("sha256",e).update(JSON.stringify(t)).digest("hex"),Go=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&au(r,n)},Vo=e=>Buffer.from(N(e));function Ko({file:e,keyFile:t,anchorFile:r}){if(!e||!t||!r)throw new Error("cex-state: protected paths required");if(je.dirname(je.resolve(e))===je.dirname(je.resolve(r)))throw new Error("cex-state: external rollback anchor required");let n=`${e}.lock`,o=(()=>{try{return D.readFileSync(`/proc/${process.pid}/stat`,"utf8").trim().split(/\s+/)[21]}catch{return null}})(),i=d=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,d),a=d=>{if(!Number.isSafeInteger(d.pid)||d.pid<1||typeof d.processStart!="string"||!d.processStart)return null;try{process.kill(d.pid,0)}catch(l){return l?.code==="ESRCH"?!1:null}try{return D.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{D.mkdirSync(je.dirname(n),{recursive:!0,mode:448});let l=iu(16).toString("hex"),f=Date.now()+5e3,p=`${n}.${process.pid}.${l}.tmp`,m=JSON.stringify({version:1,pid:process.pid,processStart:o,token:l,createdAtMs:Date.now()})+`
|
|
8
|
-
`;for(;;)try{let h=D.openSync(p,"wx",384);try{D.writeFileSync(h,m),D.fsyncSync(h)}finally{D.closeSync(h)}try{D.linkSync(p,n)}finally{D.unlinkSync(p)}break}catch(h){try{D.existsSync(p)&&D.unlinkSync(p)}catch{}if(h?.code!=="EEXIST")throw new Error("cex-state: lock refused");let g;try{g=D.readFileSync(n,"utf8")}catch(b){if(b?.code==="ENOENT")continue;throw new Error("cex-state: corrupt lock refused")}let w;try{w=JSON.parse(g)}catch{throw new Error("cex-state: corrupt lock refused")}if(w?.version!==1||!/^[0-9a-f]{32}$/.test(w.token||"")||!Number.isSafeInteger(w.createdAtMs))throw new Error("cex-state: corrupt lock refused");if(a(w)===!1&&Date.now()-w.createdAtMs>3e4){try{D.unlinkSync(n)}catch{throw new Error("cex-state: stale lock recovery refused")}continue}if(Date.now()>=f)throw new Error("cex-state: lock busy");i(10)}try{return d()}finally{let h;try{h=JSON.parse(D.readFileSync(n,"utf8"))}catch{throw new Error("cex-state: lock ownership lost")}if(h.token!==l||h.pid!==process.pid||h.processStart!==o)throw new Error("cex-state: lock ownership lost");D.unlinkSync(n)}},c=()=>{let d=
|
|
1
|
+
var Si=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};import Tt from"node:fs";import Ai from"node:os";import Ke from"node:path";import{fileURLToPath as vi}from"node:url";function on(){return process.env.ORACLE_FAKE_HOME||Ai.homedir()}function ki(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function Ot(){return ki()?process.env.ORACLE_CONFIG_DIR||Ke.join(on(),".config","oracle"):Ke.join(on(),".config","oracle")}function Ti(){return Ke.join(Ot(),"desk.json")}function Oi(){return Ke.join(Ot(),"env")}function Ve({force:e=!1}={}){if(Ve._done&&!e)return Ve._result||null;Ve._done=!0;let t={},r=(o,i)=>{if(i==null)return;let a=String(i).trim();a&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=a,t[o]=a))};try{let o=Oi();if(Tt.existsSync(o))for(let i of Tt.readFileSync(o,"utf8").split(/\r?\n/)){let a=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let u=a[2];(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),r(a[1],u)}}catch{}try{let o=Ti();if(Tt.existsSync(o)){let i=JSON.parse(Tt.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)),Ve._result=Object.keys(t).length?t:null,Ve._result}var Ii,Tl,an=Si(()=>{Ii=Ke.dirname(vi(import.meta.url)),Tl=Ke.resolve(Ii,"../..");try{Ve()}catch{}});an();import bl from"node:path";import fi from"node:fs";import Y from"node:path";import Gu from"node:os";import{createHash as Vu,randomBytes as Ku}from"node:crypto";import{execFileSync as Xu}from"node:child_process";import{fileURLToPath as Yu}from"node:url";import{Interface as rn,keccak256 as Qu}from"ethers";import{Transaction as Zr}from"@scure/btc-signer";import{ed25519 as Zu}from"@noble/curves/ed25519.js";import ic from"node:http";import{timingSafeEqual as ac}from"node:crypto";import{createHash as Js,randomBytes as Gs,timingSafeEqual as Vs}from"node:crypto";import{base58 as ho}from"@scure/base";import{Interface as Vn}from"ethers";import{Interface as Wi,MaxUint256 as Hi,isAddress as Ji,keccak256 as dd,toUtf8Bytes as fd}from"ethers";import{Interface as Ui,isAddress as Jl}from"ethers";import{isAddress as ql}from"ethers";import{createHash as Bi,createHmac as Ri,timingSafeEqual as _i}from"node:crypto";import{readFileSync as Ci}from"node:fs";import{homedir as Ni}from"node:os";import{join as Ct}from"node:path";function Li(){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=Ni();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Ct(t,".config","oracle")).trim();return[e,Ct(r,"exec.env")].filter(Boolean)}return[e,Ct(t,".config","oracle","exec.env"),Ct(t,".config","mad-desk","exec.env")].filter(Boolean)}function dt(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of Li())try{let i=Ci(o,"utf8"),a=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${r}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}function Xe(e,t,r="guard"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${r}: current time must be a finite number (got ${$i(t)})`);let n=t,o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${r} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function $i(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var sn=100;function rr(e){return Array.isArray(e)?`[${e.map(rr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${rr(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Pi(e,{required:t=!1}={}){try{return dt(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Fi(e){let{signature:t,...r}=e;return r}function Di(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 Bi("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function Mi(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:_i(r,n)}function qi(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=t.length;i+=64)n.push(t.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(r){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function nr(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:i,requireSigned:a=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let u=Pi(o,{required:a});if(a&&!u)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(u){let m=Ri("sha256",u).update(rr(Fi(e))).digest("hex");if(!Mi(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>sn)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(s)||s<0||s>sn||c>s)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{Xe({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=qi(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==Di(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 h=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${h}; 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 Xl=new Ui(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as zi,isAddress as Zl}from"ethers";var nd=new zi(["function approve(address spender,uint256 amount) returns (bool)"]),od=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function F(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 H(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function G(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=F(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 Q(e,t="amount"){let r=G(e,t);if(r<=0n)throw new Error(`${t} must be positive`);return r}function P(e,t,r="amount"){let n=F(e,r);if(!/^-?\d*(\.\d+)?$/.test(n)||n===""||n==="."||n==="-")throw new Error(`${r} must be a decimal number, got ${JSON.stringify(n)}`);let o=n.startsWith("-"),i=o?n.slice(1):n,[a="0",u=""]=i.split(".");if(u.length>t)throw new Error(`${r} has more than ${t} decimal places, which would lose precision`);let c=BigInt((a||"0")+u.padEnd(t,"0"));return o?-c:c}var yd=new Wi(["function approve(address spender,uint256 amount) returns (bool)"]);function cn(e,t){let r=String(e||"").trim();if(!Ji(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Gi(e,t="approval amount",{allowZero:r=!1}={}){let n=G(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=Hi)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var un=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),Vi=new Set(["0x39509351","0xf9255c1f"]);function J(e){let t=String(e||"").toLowerCase();return t.length<10?!1:un.has(t.slice(0,10))}function he(e){if(!J(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=s=>n[s]?"0x"+n[s].slice(24):null,i=s=>n[s]?BigInt("0x"+n[s]):null,a=null,u=null,c=null;switch(r){case"0x095ea7b3":case"0x39509351":a=o(0),u=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),a=o(1),u=i(2);break;case"0xd505accf":a=o(1),u=i(2);break;case"0x8fcbaf0c":{a=o(1),u=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),a=o(1),u=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(a==null||u==null)throw new Error("invalid approve calldata");return{spender:cn(a,"approval spender"),token:c==null?null:cn(c,"approval token"),amount:Gi(u,"approval amount",{allowZero:!0}),selector:r,additive:Vi.has(r)}}import{createHash as Ki,createHmac as xd,timingSafeEqual as Sd}from"node:crypto";var Xi=2,or=300*1e3,ln=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function Yi(e){let t=e==null||e===""?or:Number(e);return!Number.isFinite(t)||t<0?or:Math.min(t,ln)}function ir(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ir).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ir(e[r])}`).join(",")}}`}function Qi(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function Zi(e){let t=Qi(e);return Ki("sha256").update(ir(t)).digest("hex")}function dn(e,{maxAgeMs:t=or,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)!==Xi)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let a=Zi(e);if(String(e.prepareHash||"")!==a)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let u=Number(e.preparedAt),c=Number(e.expiresAt),s=Yi(t),d=r-u,l=c-u;if(!Number.isFinite(d)||!Number.isFinite(c)||!Number.isFinite(l)||d<0||l<=0||l>ln||d>s||r>=c)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${s})`);if(n&&!new Set(n).has(e.provider))throw new Error(`${i}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${i}: kind ${e.kind} not allowed here`);return!0}var ft=e=>String(e||"").toLowerCase(),ea=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","authorizationList","slippageBps","expiresAtMs"]),ta=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function ue(e){try{return ta.has(BigInt(e))}catch{return!1}}var Z=(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`)}},fn=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Ye=(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 Nt(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=>!ea.has(p)))throw new Error("policy: unexpected EVM artifact field");if(e.gasPrice!=null&&(e.maxFeePerGas!=null||e.maxPriorityFeePerGas!=null))throw new Error("policy: ambiguous EVM fee fields");if(e.type!=null&&![0,1,2,4].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");if(Number(e.type)===4){if(!Array.isArray(e.authorizationList)||e.authorizationList.length===0||e.authorizationList.length>8)throw new Error("policy: type-4 requires 1-8 authorizationList entries");for(let[p,m]of e.authorizationList.entries()){if(!m||typeof m!="object")throw new Error(`policy: authorizationList[${p}] required`);Ye(m.address,t.destinations,"destination",ft);try{if(BigInt(m.chainId)!==BigInt(e.chainId))throw new Error("policy: type-4 authorization chainId must match transaction")}catch(h){throw String(h?.message||"").includes("authorization chainId")?h:new Error("policy: type-4 authorization chainId must match transaction")}}if(String(e.data||"0x").toLowerCase()!=="0x")throw new Error("policy: type-4 calldata must be empty");if(Z(e.value,"value")!==0n)throw new Error("policy: type-4 cannot transfer native value")}else if(e.authorizationList!=null)throw new Error("policy: authorizationList is only valid on type-4");let i=(p,m)=>{try{return BigInt(p)===BigInt(m)}catch{return String(p)===String(m)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(p=>i(p,e.chainId)))throw new Error("policy: chain not allowed");if(Ye(e.to,t.destinations,"destination",ft),Ye(String(e.data||"0x").slice(0,10),t.selectors,"selector",p=>String(p).toLowerCase()),Ye(e.from,t.owners,"owner",ft),J(e.data)){let p;try{p=he(e.data)}catch(h){throw new Error(`policy: malformed approval calldata: ${h?.message||h}`)}Ye(p.spender,t.spenders,"spender",ft),Ye(p.token||e.to,t.erc20Tokens,"ERC-20 token",ft);let m=Z(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(Z(e.value,"value")>Z(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=Z(e.gasLimit,"gasLimit");if(a>Z(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let u=e.maxFeePerGas??e.gasPrice,c=Z(u,"feePerGas")*a,s=0n;try{if(ue(e.chainId)&&(e.l1FeeWei===void 0||e.operatorFeeWei===void 0))throw new Error("missing")}catch{throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(e.l1FeeWei!==void 0&&(s+=Z(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(s+=Z(e.operatorFeeWei,"operatorFeeWei")),ue(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let p=Z(n.l1FeeWei,"estimated l1FeeWei")+Z(n.operatorFeeWei,"estimated operatorFeeWei");if(s<p)throw new Error("policy: rollup fee attestation understates estimate")}if(c+s>Z(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=fn(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=fn(t.maxTtlMs??12e4,"maxTtlMs");if(f<=0||e.expiresAtMs-r>f)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as pn}from"node:crypto";import{Address as ra,NETWORK as na,OutScript as mn,RawTx as oa,SigHash as wn,TEST_NETWORK as ia,Transaction as aa}from"@scure/btc-signer";var hn=(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`)}},sa=(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},ca=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,ua=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),Re=e=>ua(e)?String(e).toLowerCase():String(e),ar=(e,t)=>Array.isArray(t)&&t.some(r=>Re(r)===Re(e)),la=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function da(e){let t=Buffer.from(oa.encode(e)),r=pn("sha256").update(t).digest();return Buffer.from(pn("sha256").update(r).digest()).reverse().toString("hex")}function fa(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(da(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)||!la(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function sr(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(!ar(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?na:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?ia:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=aa.fromPSBT(sa(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=ra(n);for(let l=0;l<o.inputsLength;l++){let f=o.getInput(l);for(let h of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(ca(f[h]))throw new Error("envelope: signed or finalized PSBT refused");if(f.sighashType!==void 0&&f.sighashType!==wn.DEFAULT&&f.sighashType!==wn.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let p=fa(f),m;try{let h=mn.decode(p.script);if(!["wpkh"].includes(h.type))throw new Error("unsupported input");m=i.encode(h)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!ar(m,t.owners)||Re(m)!==Re(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...t.changeAddresses||[]].map(l=>Re(l))),u=0n,c=!1,s=[];for(let l=0;l<o.outputsLength;l++){let f=o.getOutput(l),p;try{p=i.encode(mn.decode(f.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=Re(p);if(s.push(`${p}:${f.amount}`),m===Re(e.destination)){c=!0,u+=f.amount;continue}if(ar(p,t.destinations)){u+=f.amount;continue}if(!a.has(m))throw new Error("policy: Bitcoin output destination not allowed")}if(!c)throw new Error("envelope: Bitcoin destination mismatch");let d;try{d=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(d<0n||d>hn(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(u>hn(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:u.toString(),notional:(u+d).toString(),fee:d.toString(),outputs:Object.freeze(s)})}function cr(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})}import{createHash as lr}from"node:crypto";import{base58 as Sn}from"@scure/base";import{getCompiledTransactionMessageDecoder as pa}from"@solana/transaction-messages";var dr="11111111111111111111111111111111",ma="ComputeBudget111111111111111111111111111111",wa="So11111111111111111111111111111111111111112",An="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var vn="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",ha=5000n,ga=2039280n,ya=37095705934669439343138083508754565189542113879843219016388785533085940283555n,U=57896044618658097711785492504343953926634992332820282019728792003956564819949n,gn=19681161376707505956807079304988542015446066515923890162744021073123829784752n,yn=e=>lr("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Ea=new Map([[yn("route"),{name:"route",prefixBytes:0}],[yn("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),te=(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`)}},ba=(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},ge=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),oe=e=>String(e||""),xa=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,$t=e=>lr("sha256").update(e).digest("hex");function Lt(e,t){try{let r=Buffer.from(Sn.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function ee(e){let t=e%U;return t>=0n?t:U+t}function le(e,t){let r=e;for(;t-- >0n;)r=r*r%U;return r}function Sa(e){let r=e*e%U*e%U,n=le(r,2n)*r%U,o=le(n,1n)*e%U,i=le(o,5n)*o%U,a=le(i,10n)*i%U,u=le(a,20n)*a%U,c=le(u,40n)*u%U,s=le(c,80n)*c%U,d=le(s,80n)*c%U,l=le(d,10n)*i%U;return le(l,2n)*e%U}function Aa(e,t){let r=ee(t*t*t),n=ee(r*r*t),o=Sa(e*n),i=ee(e*r*o),a=ee(t*i*i),u=i,c=ee(i*gn),s=a===e,d=a===ee(-e),l=a===ee(-e*gn);return s&&(i=u),(d||l)&&(i=c),(ee(i)&1n)===1n&&(i=ee(-i)),!s&&!d?null:i}function va(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=ee(t*t),n=Aa(ee(r-1n),ee(ya*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function Ia(e,t){let r=Buffer.concat([...e,Lt(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=lr("sha256").update(r).digest();if(va(n))throw new Error("envelope: derived Solana program address is on curve");return Sn.encode(n)}function fr(e,t,r=An){let n=[Lt(e,"owner"),Lt(r,"token program"),Lt(t,"mint")];for(let o=255;o>=0;o--)try{return Ia([...n,Buffer.from([o])],vn)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function ka(e,t){return(t.accountIndices||[]).map(r=>oe(e.staticAccounts[r]))}function pt(e){return Buffer.from(e.data||[])}function Ta(e,t){return oe(e.staticAccounts[t.programAddressIndex])}function In(e,t){return Number(t)<e.header.numSignerAccounts}function Oa(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 mt(e){return e.accountIndices||[]}function ur(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function En(e,t){let r=mt(t).map(n=>{let o=In(e,n)?"s":"n",i=Oa(e,n)?"w":"r";return`${n}:${oe(e.staticAccounts[n])}:${o}:${i}`});return $t(Buffer.from(r.join(`
|
|
2
|
+
`)))}function bn(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function Ca(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function Na(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function La(e,t,r){let n=r.maxJupiterRoutePlanSteps===void 0?1:Number(r.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(t<1||t>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(r.jupiterRouteVariants)?r.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=r.jupiterRouteVariantPayloadBytes||{},a=0,u=0,c=[];for(let s=0;s<t;s++){if(a>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e[a++];if(!o.includes(d))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(d)))throw new Error("policy: Jupiter route variant payload size required");let l=Number(i[String(d)]);if(!Number.isSafeInteger(l)||l<0||l>16)throw new Error("policy: Jupiter route variant payload size invalid");if(a+l+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e.subarray(a,a+l);a+=l;let p=f.toString("hex"),m=r.jupiterRouteVariantPayloads?.[String(d)];if(!Array.isArray(m)||!m.map(String).includes(p))throw new Error("policy: Jupiter route variant payload not allowed");let h=e[a++],g=e[a++],w=e[a++];if(h<1||h>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(g!==s||w!==s+1)throw new Error("envelope: unsupported Jupiter route-plan token index");u+=h,c.push(Object.freeze({swapVariant:d,variantPayloadHex:p,percent:h,inputIndex:g,outputIndex:w}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(u!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function $a(e,t){let r=pt({data:e}),n=r.subarray(0,8).toString("hex"),o=Ea.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,a=o.prefixBytes===1?r[8]:null;if(o.prefixBytes===1&&r.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let u=8+o.prefixBytes,c=u+4,s=r.length-i;if(s<=c)throw new Error("envelope: malformed Jupiter route payload");let d=Na(r,u,"route plan length"),l=r.subarray(c,s),f=La(l,d,t);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:d,routePlan:f,routePlanHash:$t(l),inAmount:bn(r,s,"in_amount"),quotedOutAmount:bn(r,s+8,"quoted_out_amount"),slippageBps:Ca(r,s+16,"slippage_bps"),platformFeeBps:r[s+18],instructionHash:$t(r)})}function Ba(e,t,r){let n=ka(e,t),o=(i,a)=>{let u=n[i];if(!u)throw new Error(`envelope: Jupiter ${a} account missing`);return u};if(r.instruction==="route"){if(n.length<9)throw new Error("envelope: Jupiter route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),userTransferAuthority:o(1,"userTransferAuthority"),userSourceTokenAccount:o(2,"userSourceTokenAccount"),userDestinationTokenAccount:o(3,"userDestinationTokenAccount"),destinationTokenAccount:o(4,"destinationTokenAccount"),destinationMint:o(5,"destinationMint"),platformFeeAccount:o(6,"platformFeeAccount"),eventAuthority:o(7,"eventAuthority"),program:o(8,"program")}}if(r.instruction==="shared_accounts_route"){if(n.length<13)throw new Error("envelope: Jupiter shared route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),programAuthority:o(1,"programAuthority"),userTransferAuthority:o(2,"userTransferAuthority"),userSourceTokenAccount:o(3,"sourceTokenAccount"),programSourceTokenAccount:o(4,"programSourceTokenAccount"),programDestinationTokenAccount:o(5,"programDestinationTokenAccount"),userDestinationTokenAccount:o(6,"destinationTokenAccount"),sourceMint:o(7,"sourceMint"),destinationMint:o(8,"destinationMint"),platformFeeAccount:o(9,"platformFeeAccount"),token2022Program:o(10,"token2022Program"),eventAuthority:o(11,"eventAuthority"),program:o(12,"program")}}throw new Error("envelope: unsupported Jupiter account layout")}function xn(e,t){return e&&e!==t?e:null}function re(e,t,r){let n=oe(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function Ra(e,t){let r=pt(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 _a(e,t,r,n,o,i){let a=pt(t);if(a.length!==1||a[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let u=mt(t);if(u.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=re(e,u[0],"ATA payer"),s=re(e,u[1],"ATA account"),d=re(e,u[2],"ATA owner"),l=re(e,u[3],"ATA mint"),f=re(e,u[4],"ATA system program"),p=re(e,u[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!==dr)throw new Error("envelope: Jupiter ATA system program mismatch");if(p!==o)throw new Error("envelope: Jupiter ATA token program mismatch");if(l!==n.inputMint&&l!==n.outputMint)throw new Error("envelope: Jupiter ATA mint mismatch");if(s!==fr(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:s,debit:i}}function Pa(e,t,r,n,o){let i=mt(t),a=pt(t);if(i.length!==2||a.length!==12||a.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let u=re(e,i[0],"wrap payer"),c=re(e,i[1],"wrap target"),s=a.readBigUInt64LE(4);if(u!==r.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(s!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return s}function Fa(e,t,r,n){let o=mt(t),i=pt(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||re(e,o[0],"syncNative account")!==n)throw new Error("envelope: Jupiter syncNative account mismatch");return{kind:"syncNative"}}if(i[0]===9){if(o.length!==3)throw new Error("envelope: malformed Jupiter closeAccount helper");let a=re(e,o[0],"closeAccount source"),u=re(e,o[1],"closeAccount destination"),c=re(e,o[2],"closeAccount authority");if(a!==n||u!==r.owner||c!==r.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function Da(e,t,r,n,o,i,a){let u=fr(t.owner,t.artifact.inputMint,a);if(o.userSourceTokenAccount!==u)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=te(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<ga)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let s=new Map,d=0n,l=!1,f=!1;for(let p of e.instructions){if(p===n)continue;let m=Ta(e,p);if(m===ma)Ra(p,r);else if(m===vn){let{ata:h,debit:g}=_a(e,p,t,t.artifact,a,c);s.set(h,g)}else if(m===dr)d+=Pa(e,p,t,u,i);else if(m===a){let h=Fa(e,p,t,u);h.kind==="syncNative"&&(l=!0),h.kind==="closeAccount"&&(f=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(d>0n&&(!l||!f))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(d!==0n&&d!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...s.values()].reduce((p,m)=>p+m,0n)}function Ma(e){let t;try{t=pa().decode(ba(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 qa(e,t,r){if(e.header.numSignerAccounts!==1||oe(e.staticAccounts[0])!==t.owner||!ge(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=oe(e.staticAccounts[o.programAddressIndex]);if(!i||!ge(i,r.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function ja(e,t,r){let n=te(r.lamportsPerSignature,"lamportsPerSignature");if(n<ha)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:te(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),a=i*n,u=i*o;if(t.exactFeeLamports!==void 0){let s=te(t.exactFeeLamports,"exactFeeLamports");if(s<a)throw new Error("policy: Solana exact fee below the base signature fee");if(s>u)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=u;if(c>te(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function Ua(e,t,r,n){let o=0n,i=!1;for(let a of e.instructions){if(oe(e.staticAccounts[a.programAddressIndex])!==dr)throw new Error("envelope: unsupported Solana program decoder");let c=a.accountIndices||[];if(c.length!==2||oe(e.staticAccounts[c[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let s=oe(e.staticAccounts[c[1]]);if(s!==t.destination||!ge(s,r.destinations))throw new Error("envelope: Solana destination mismatch");let d=Buffer.from(a.data||[]);if(d.length!==12||d.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=d.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>te(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function za(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!==wa)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!ge(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=xa(r);if(!ge(o.inputMint,i)||!ge(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=te(o.inAmount,"inAmount"),u=te(o.outAmount,"outAmount"),c=te(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>te(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>te(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(u<=0n||c<=0n||c>u)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let s=oe(o.jupiterProgram);if(!s||!ge(s,r.programs)||!n.includes(s))throw new Error("policy: Jupiter program not allowed or absent");let d=e.instructions.filter(v=>oe(e.staticAccounts[v.programAddressIndex])===s);if(d.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=d[0],f=$a(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(!ur(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(f.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(f.inAmount!==a)throw new Error("envelope: Jupiter route in_amount mismatch");if(f.quotedOutAmount!==u)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(f.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let p=f.quotedOutAmount-f.quotedOutAmount*BigInt(f.slippageBps)/10000n;if(c!==p)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(f.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let m=Ba(e,l,f),h=mt(l),g=f.instruction==="shared_accounts_route"?2:1;if(!In(e,h[g]))throw new Error("envelope: Jupiter transfer authority must be signer");if(m.program!==s)throw new Error("envelope: Jupiter program account mismatch");if(m.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(m.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(m.sourceMint!==void 0&&m.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let w=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[An];if(!ge(m.tokenProgram,w))throw new Error("policy: Solana token program not allowed");let E=fr(t.owner,o.outputMint,m.tokenProgram);if(m.userDestinationTokenAccount!==E)throw new Error("envelope: Jupiter destination token account is not owner ATA");let b=xn(m.destinationTokenAccount,s);if(b&&b!==E)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(xn(m.platformFeeAccount,s))throw new Error("policy: Jupiter platform fee account not allowed");if(!ur(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(En(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let S=$t(Buffer.from([f.instruction,f.routeId??"",f.routePlanHash,En(e,l)].join(`
|
|
3
|
+
`)));if(!ur(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(S))throw new Error("policy: Jupiter route review hash not allowed");let I=Da(e,t,r,l,m,a,m.tokenProgram),T=a+I;if(T>te(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:T,programs:n}}function pr(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(!ge(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=Ma(r),i=qa(o,e,t),a=e.action==="transfer"?Ua(o,e,t,i):za(o,e,t,i),u=ja(o,r,t);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+u).toString(),fee:u.toString(),programs:Object.freeze(a.programs)})}function mr(e,t){let{unit:r,value:n,notional:o,fee:i}=pr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}var Md=64*1024;var Ha=1e8;function wr(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=Ha+t;return Number.isSafeInteger(o)?{encoding:t,outcome:n,side:r,coin:`#${t}`,assetId:o}:null}var Ja=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),Ga=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),Va=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"}),Ka=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"}),Ae=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function Xa(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 kn(e,t){let r=F(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 de(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=>de(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)}:${de(e[n],t)}`).join(",")}}`}function Ya(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)||de(r,"declared order type")!==de({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(de(r,"declared order type")!==de({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||de(r,"declared order type")!==de({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 Qa(e,t,r){let n=kn(e.s,"signed size"),o=kn(e.p,"signed price"),i=n.decimals+o.decimals,a=n.raw*o.raw,u=P(t.notionalUsd,i,"hl: notionalUsd");if(u<=0n||a!==u)throw new Error("hl: signed notional must match");let c=P(r.maxNotionalUsd,i,"hl: maxNotionalUsd");if(a>c)throw new Error("hl: notional exceeds cap")}function Za(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=Ae(r.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("hl: order builder address required");if(H(e.builder||"","hl: builder").toLowerCase()!==n)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(u=>String(u).toLowerCase()):[]).includes(n))throw new Error("hl: order builder not allowed");let i=G(r.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let a=P(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>a)throw new Error("hl: order builder fee exceeds cap")}function Tn(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(F(e.s,"hl: signed size")!==F(t.size,"hl: size"))throw new Error("hl: signed size must match");if(F(e.p,"hl: signed price")!==F(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(de(e.t,"signed order type")!==de(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 On(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(F(e.s,"hl: bracket protection size")!==F(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(F(e.p,"hl: bracket protection price")!==F(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(F(i.triggerPx,"hl: triggerPx")!==F(n,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function es(e){let t=String(e||"").replace(/\/$/,"");if(!Ja.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function hr(e){return wr(e)!=null}function ts(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(hr(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 rs(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(a=>{if(typeof a=="string"){let[u,c]=String(a).split(":");return u===e&&Number(c)===t}return String(a?.coin)===e&&Number(a?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(hr(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 ve(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=Ae(r.kind,"kind",48),o=Va[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=es(r.submitTo);if(Object.prototype.hasOwnProperty.call(r,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let a=Number(r.nonce);if(!Number.isSafeInteger(a)||a<=0)throw new Error("hl: nonce must be a positive integer");if(!r.action||typeof r.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(r.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(r.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(r.action.type!==Ka[n])throw new Error("hl: action type must match kind");let u=r.notionalUsd??0;if(Ga.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let c=Ae(r.coin,"coin",64),s=r.assetId??r.assetIndex;if(!Number.isSafeInteger(s)||s<0)throw new Error("hl: assetId required");if(n==="hip4-order"||s>=1e8){let d=wr(c);if(!d||d.coin!==c)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(d.assetId!==s)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(ts(c,t),rs(c,s,t),n==="hip4-order"&&!hr(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");Ya(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");Tn(d[0],r,s);let m=1;l!=null&&On(d[m++],r,s,l,"tp"),f!=null&&On(d[m],r,s,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");Tn(d[0],r,s)}Qa(d[0],r,t),Za(r,t),u=F(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!==s)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(r.orderId)||r.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(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!==s)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(r.action.leverage)||r.action.leverage!==r.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(r.marginMode))throw new Error("hl: declared margin mode required");let 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!==s)throw new Error("hl: signed margin asset must match assetId");let d=Ae(r.usd,"margin usd",64),l=P(d,6,"hl: margin usd");if(G(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=P(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),m=l<0n?-l:l;if(m>p)throw new Error("hl: margin notional exceeds cap");u=Xa(m,6)}}if(n==="builder-fee-approval"){let c=Ae(r.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(Ae(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=Ae(r.maxFeeRate,"maxFeeRate",32);if(Ae(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=P(d.slice(0,-1),12,"hl: builder fee percent"),f=P(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(f<0n||l*100n>f)throw new Error("hl: builder fee exceeds cap");if(Number(r.action.nonce)!==a)throw new Error("hl: signed builder nonce must match");let p=i.includes("testnet")?"Testnet":"Mainnet";if(r.hyperliquidChain!==p||r.action.hyperliquidChain!==r.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(r.signatureChainId!=="0x66eee"||r.action.signatureChainId!==r.signatureChainId)throw new Error("hl: signed signature chain id must match")}if(n.startsWith("hype-stake")||n==="hype-delegate"||n==="hype-undelegate"){if(n==="hype-delegate"||n==="hype-undelegate"){let c=n==="hype-undelegate";if(typeof r.action.isUndelegate!="boolean"||r.action.isUndelegate!==c)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(t.maxHypeWei!=null&&BigInt(String(r.action.wei??r.caps?.amountHype??"0"))>BigInt(t.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(u??r.action.wei??0),notional:String(u??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??u??0),coin:r.coin||null,submitTo:i})}import{createHmac as ns}from"node:crypto";var Qe="0x"+"00".repeat(32);function gr(e={}){let t=e.polyApiKey||process.env.POLYMARKET_API_KEY||process.env.POLY_API_KEY,r=e.polyApiSecret||process.env.POLYMARKET_API_SECRET||process.env.POLY_API_SECRET,n=e.polyPassphrase||process.env.POLYMARKET_API_PASSPHRASE||process.env.POLY_API_PASSPHRASE;if(!t||!r||!n)throw new Error("signer: Polymarket L2 API credentials required (POLYMARKET_API_KEY / SECRET / PASSPHRASE)");return{key:String(t),secret:String(r),passphrase:String(n)}}function Cn({creds:e,address:t,method:r,path:n,body:o="",nowSec:i}={}){if(!e?.key||!e?.secret||!e?.passphrase)throw new Error("poly: L2 credentials required");if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("poly: L2 address required");let a=String(i??Math.floor(Date.now()/1e3)),u=String(r||"").toUpperCase(),c=String(n||"");if(u!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let s=a+u+c+String(o||""),d=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(d,"base64"),f=ns("sha256",l).update(s).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:f,POLY_TIMESTAMP:a,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function os(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 is(e){let t=typeof e=="bigint"?e:Q(e,"poly: atomicUsdc");if(t<=0n)throw new Error("poly: order amounts must be positive integer micro-units");let r=t/1000000n,n=(t%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return n?`${r.toString()}.${n}`:r.toString()}function Nn(e,t){let r=Q(e.makerAmount,"poly: makerAmount"),n=Q(e.takerAmount,"poly: takerAmount");return is(t==="BUY"?r:n)}function as(e){let t=typeof e=="bigint"?e.toString(10):F(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 Ln({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=os(e,t);if(H(e.metadata||Qe,"poly: metadata").toLowerCase()!==Qe)throw new Error("poly: metadata must be zero");if(H(e.builder||Qe,"poly: builder").toLowerCase()!==Qe)throw new Error("poly: builder must be zero");let a=as(e.salt);return{deferExec:!1,order:{builder:Qe,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:Qe,salt:String(a),side:i,signature:r,signatureType:Number(e.signatureType),signer:e.signer,takerAmount:String(e.takerAmount),timestamp:String(e.timestamp),tokenId:String(e.tokenId)},orderType:"GTC",owner:o}}var ss=new Set(["https://clob.polymarket.com/order"]),wt=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),tf=Object.freeze(wt.map(e=>e[0])),cs=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),us="0xe111180000d2663c0091e4f400237545b87b996b",ls="0xe2222d279d744050d28e00520010520000310f59",$n=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function Bn(e){let t=String(e||"").replace(/\/$/,"");if(!ss.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function Rn(e){let t=H(e,"poly: exchange").toLowerCase();if(!cs.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function Ie(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=$n(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(H(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(Bn(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(Rn(o.verifyingContract),Rn(r.exchange),H(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==H(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?ls:us;if(H(r.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let a=r.message||r.value;if(!a||typeof a!="object")throw new Error("poly: signed order message required");let u=r.types?.Order;if(!Array.isArray(u)||u.length!==wt.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let v=0;v<wt.length;v+=1)if(u[v]?.name!==wt[v][0]||u[v]?.type!==wt[v][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(H(a.maker,"poly: maker").toLowerCase()!==c)throw new Error("poly: maker must equal owner");if(H(a.signer,"poly: signer").toLowerCase()!==c)throw new Error("poly: signer must equal owner");if(a.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof a.builder!="string"||a.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(a.side!==0&&a.side!==1)throw new Error("poly: side must be BUY or SELL");let s=$n(r.tokenId,"tokenId",80);if(H(a.tokenId,"poly: tokenId")!==s)throw new Error("poly: tokenId mismatch");let d=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(d.length&&!d.includes(s)&&!d.includes("*"))throw new Error("poly: tokenId not allowed");let l=Number(a.side)===0?"BUY":"SELL";if(r.side&&r.side!==l)throw new Error("poly: side mismatch");let f=Q(a.makerAmount,"poly: makerAmount"),p=Q(a.takerAmount,"poly: takerAmount"),m=Q(r.makerAmount,"poly: prepared makerAmount"),h=Q(r.takerAmount,"poly: prepared takerAmount");if(f!==m)throw new Error("poly: signed makerAmount differs from prepared envelope");if(p!==h)throw new Error("poly: signed takerAmount differs from prepared envelope");let g=l==="BUY"?f:p,w=l==="BUY"?p:f,E=P(r.quantity,6,"poly: quantity");if(E<=0n||E!==w)throw new Error("poly: quantity must match CLOB v2 amounts");let b=P(r.price,6,"poly: price");if(b<=0n||b>=1000000n)throw new Error("poly: price must be within (0,1)");if(w*b!==g*1000000n)throw new Error("poly: price must match CLOB v2 amounts");if(P(r.notionalUsdc,6,"poly: notionalUsdc")!==g)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let I=Nn(a,l);if(P(I,6,"poly: displayed notionalUsdc")!==g)throw new Error("poly: displayed notionalUsdc must match CLOB v2 amounts");let T=t.maxNotionalUsd??t.maxNotionalUsdc;if(T!=null){let v=P(T,6,"poly: maxNotionalUsd");if(g>v)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:g.toString(),notional:g.toString(),fee:"0",kind:n,tokenId:s,side:l,makerAmount:f.toString(),takerAmount:p.toString(),price:String(r.price),quantity:String(r.quantity),notionalUsdc:I,submitTo:Bn(r.submitTo)})}var ds=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),yr=14,_n=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function Ze(e,t,r){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${r} must be exact numeric ${t}`)}function Er(e){let t=String(e||"").replace(/\/$/,"");if(!ds.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function ke(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=_n(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=Er(r.submitTo),i=r.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=Number(G(r.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: accountIndex required");let u=Number(G(r.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(u)||u<0)throw new Error("lighter: clientOrderIndex required");Ze(r.orderType,0,"orderType"),Ze(r.timeInForce,1,"timeInForce"),Ze(r.reduceOnly,0,"reduceOnly"),Ze(r.triggerPrice,0,"triggerPrice"),Ze(r.orderExpiry,-1,"orderExpiry");let c=_n(r.symbol||r.coin,"symbol",32),s=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(s.length&&!s.includes(c)&&!s.includes(String(i))&&!s.includes("*"))throw new Error("lighter: market not allowed");if(r.side!=="buy"&&r.side!=="sell")throw new Error("lighter: side must be buy or sell");let d=Q(r.baseAmount,"lighter: baseAmount"),l=Q(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),h=Number(r.priceDecimals??0);if(!Number.isInteger(m)||m<0||m>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(h)||h<0||h>12)throw new Error("lighter: priceDecimals required");let g=m+h,w=d*l,E=P(r.notionalUsd,g,"lighter: notionalUsd");if(E<=0n)throw new Error("lighter: notionalUsd required");if(w!==E)throw new Error("lighter: notionalUsd must match size and price");let b=P(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,g,"lighter: maxNotionalUsd");if(w>b)throw new Error("lighter: notional exceeds cap");let S=F(r.notionalUsd,"lighter: notionalUsd");return Ze(r.txType,yr,"txType"),Object.freeze({unit:"usd",value:String(S),notional:String(S),fee:"0",kind:n,symbol:c,marketIndex:i,side:r.side,baseAmount:f,price:p,submitTo:o,actionType:"create-order",amount:String(S)})}import{TypedDataEncoder as Dn,getAddress as ie}from"ethers";import{TypedDataEncoder as sf,getAddress as cf,isAddress as uf}from"ethers";var Pn=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),br=Object.freeze({Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"receiver",type:"address"},{name:"makerAsset",type:"address"},{name:"takerAsset",type:"address"},{name:"makingAmount",type:"uint256"},{name:"takingAmount",type:"uint256"},{name:"makerTraits",type:"uint256"}]});import{TypedDataEncoder as bf,getAddress as xf,isAddress as Sf}from"ethers";var ff=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});var Fn=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Cf=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"});var xr=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),Nf=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]});var ps=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"]),ms="0x0000000000000000000000000000000000000000";function Sr(e,t,r=256){if(typeof e!="string"||!e||e.length>r)throw new Error(`evm-order: bounded ${t} required`);return e}function Mn(e,t){let r=String(e||"").replace(/\/$/,"");if(!ps.some(o=>r===`${o}/v4.0/${t}`||r===`${o}/v4.1/${t}`))throw new Error("evm-order: submitTo must be the official 1inch orderbook");return r}function qn(e,t){let r={1:"https://api.cow.fi/mainnet/api/v1/orders",100:"https://api.cow.fi/xdai/api/v1/orders",42161:"https://api.cow.fi/arbitrum_one/api/v1/orders",8453:"https://api.cow.fi/base/api/v1/orders"}[Number(t)],n=String(e||"").replace(/\/$/,"");if(!r||n!==r)throw new Error("evm-order: cow submitTo must be official api.cow.fi");return n}function jn(e,t){let r=e?.Order,n=t.Order;return!Array.isArray(r)||r.length!==n.length?!1:r.every((o,i)=>o?.name===n[i].name&&o?.type===n[i].type)}function Un(e,...t){let r=Array.isArray(e.tokens)?e.tokens.map(n=>String(n).toLowerCase()):[];if(!r.length)throw new Error("evm-order: tokens allowlist is empty");if(!r.includes("*")){for(let n of t)if(!r.includes(String(n).toLowerCase()))throw new Error("evm-order: token not allowed")}}function zn(e,t,{allowZero:r=!1}={}){let n=String(t||"").toLowerCase();if(!n)throw new Error("evm-order: receiver required");if(n===ms){if(!r)throw new Error("evm-order: receiver must equal owner");return}if(n!==e)throw new Error("evm-order: receiver must equal owner")}function _e(e,t){if(e?.surface!=="evm-order")throw new Error("evm-order: surface evm-order required");if(e.action!=="order")throw new Error("evm-order: action must be order");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("evm-order: structured artifact required");let n=Sr(r.kind,"kind",32);if(n==="option")throw new Error("evm-order: option kind refused until official Derive/Lyra domain is pinned");if(n==="cow"){let l=Number(r.chainId??e.chainId);if(qn(r.submitTo,l),Sr(e.destination,"destination",32)!=="cowswap")throw new Error("evm-order: cow destination must be cowswap");let f=Fn[l];if(!f)throw new Error(`evm-order: unsupported cow chainId ${l}`);let p=r.domain||r.typedData?.domain,m=r.types||r.typedData?.types,h=r.message||r.typedData?.message;if(!p||!m?.Order||!h)throw new Error("evm-order: CoW EIP-712 Order required");if(!jn(m,xr))throw new Error("evm-order: cow types must be official GPv2 Order");if(Number(p.chainId)!==l)throw new Error("evm-order: cow domain chain mismatch");if(String(p.name)!=="Gnosis Protocol"||String(p.version)!=="v2")throw new Error("evm-order: cow domain must be official GPv2");if(ie(p.verifyingContract)!==ie(f))throw new Error("evm-order: cow verifyingContract must be official GPv2 settlement");let g=String(e.owner||"").toLowerCase();zn(g,h.receiver),Un(t,h.sellToken,h.buyToken);let w=ie(h.sellToken),E=String(h.feeAmount||"0"),b=(BigInt(h.sellAmount)+BigInt(E)).toString();return Object.freeze({unit:`erc20:${w.toLowerCase()}`,value:b,notional:b,fee:E,submitTo:qn(r.submitTo,l),digest:Dn.hash(p,{Order:xr.Order},h),chainId:l,kind:"cow",receiver:ie(h.receiver),sellAmount:String(h.sellAmount),buyAmount:String(h.buyAmount)})}if(n!=="1inch-limit")throw new Error("evm-order: unsupported kind");if(Sr(e.destination,"destination",32)!=="1inch-lop")throw new Error("evm-order: destination must be 1inch-lop");let o=Number(r.chainId??e.chainId),i=Pn[o];if(!i)throw new Error(`evm-order: unsupported chainId ${o}`);Mn(r.submitTo,o);let a=r.domain||r.typedData?.domain,u=r.types||r.typedData?.types,c=r.message||r.typedData?.message;if(!a||!u?.Order||!c)throw new Error("evm-order: EIP-712 Order required");if(!jn(u,br))throw new Error("evm-order: types must be official LOP v4 Order");if(Number(a.chainId)!==o)throw new Error("evm-order: domain chain mismatch");if(ie(a.verifyingContract)!==ie(i))throw new Error("evm-order: verifyingContract must be official LOP v4");if(a.name!=="1inch Limit Order Protocol"||String(a.version)!=="4")throw new Error("evm-order: EIP-712 domain must be official LOP v4");let s=String(e.owner||"").toLowerCase();if(ie(c.maker).toLowerCase()!==s)throw new Error("evm-order: maker must equal owner");zn(s,c.receiver,{allowZero:!0}),Un(t,c.makerAsset,c.takerAsset);let d=Dn.hash(a,{Order:br.Order},c);return Object.freeze({unit:`erc20:${ie(c.makerAsset).toLowerCase()}`,value:String(c.makingAmount),notional:String(c.makingAmount),fee:"0",submitTo:Mn(r.submitTo,o),digest:d,chainId:o,kind:"1inch-limit",receiver:ie(c.receiver),makerAsset:ie(c.makerAsset),takerAsset:ie(c.takerAsset),makingAmount:String(c.makingAmount),takingAmount:String(c.takingAmount)})}var Kn=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]);var Ar=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,delegate:0,identity:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0}),ws=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Xn=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),hs=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),Bt=new Vn(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Wn=new Vn(["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"]),gs=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 gt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},k=(e,t)=>{try{let r=BigInt(e);if(r<0n)throw 0;return r}catch{throw new Error(`envelope: ${t} must be a non-negative integer`)}},Hn=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},ys=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},q=(e,t,r)=>{if(!ys(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},ht=(e,t,r)=>{Array.isArray(t)&&t.length&&q(e,t,r)},$=(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},Pe=e=>String(e||"0x").slice(0,10).toLowerCase(),Yn=e=>k(e.gasLimit,"gasLimit")*k(e.maxFeePerGas??e.gasPrice,"feePerGas")+k(e.l1FeeWei??0,"l1FeeWei")+k(e.operatorFeeWei??0,"operatorFeeWei");function et(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 z(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function ae(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function Es(e){if(Pe(e)!=="0x095ea7b3")return null;let t=et(e,2,"approval");return{kind:"approval",spender:z(t.word(0),"approval spender"),amount:ae(t.word(1),"approval amount")}}function Qn(e,t){let r=t==="router02-exact-input-single"?7:8,n=et(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:z(n.word(0),"input token"),outputToken:z(n.word(1),"output token"),recipient:z(n.word(3),"recipient"),amountIn:ae(n.word(o),"amountIn"),minimumOut:ae(n.word(o+1),"amountOutMinimum")}}function bs(e){let t=et(e,12,"Across depositV3",{dynamicTail:!0}),r=ae(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:z(t.word(0),"depositor"),recipient:z(t.word(1),"recipient"),inputToken:z(t.word(2),"input token"),outputToken:z(t.word(3),"output token"),amountIn:ae(t.word(4),"inputAmount"),minimumOut:ae(t.word(5),"outputAmount"),destinationChainId:ae(t.word(6),"destinationChainId")}}function xs(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 Jn(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 g=10;g+64<=r.length;g+=64)n.push(r.slice(g,g+64));let o=(g,w)=>{if(!n[g])throw new Error(`envelope: malformed ${w}`);return BigInt(`0x${n[g]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let a=i/32,u=Number(o(a,"path offset")),c=n[a+1],s=o(a+(t?3:2),"amountIn"),d=o(a+(t?4:3),"amountOutMinimum"),l=a+u/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let f=Number(o(l,"path length")),p=r.slice(10+(l+1)*64,10+(l+1)*64+f*2),{inputToken:m,outputToken:h}=xs(`0x${p}`);return{kind:"action",action:"swap",inputToken:m,outputToken:h,recipient:z(c,"recipient"),amountIn:s,minimumOut:d}}function Ss(e){let t=et(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:z(t.word(0),"input token"),outputToken:z(t.word(1),"output token"),recipient:z(t.word(3),"recipient"),amountIn:ae(t.word(5),"amountIn"),minimumOut:ae(t.word(6),"amountOutMinimum")}}function As(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let f=10;f+64<=t.length;f+=64)r.push(t.slice(f,f+64));let n=Number(BigInt(`0x${r[1]}`));if(n%32!==0)throw new Error("envelope: malformed multicall data offset");let o=n/32;if(Number(BigInt(`0x${r[o]}`))!==1)throw new Error("envelope: multicall must wrap exactly one swap");let a=Number(BigInt(`0x${r[o+1]}`)),u=o+1+a/32,c=Number(BigInt(`0x${r[u]}`)),d=`0x${t.slice(10+(u+1)*64,10+(u+1)*64+c*2)}`,l=Pe(d);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return Qn(d,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function vs(e,t){let r=Pe(e),n=Xn[r];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(t).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed selector");if(n.layout==="router02-exact-input-single"||n.layout==="swap-router-exact-input-single")return{...Qn(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...Jn(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...Jn(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...As(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Ss(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...bs(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Is(e){let t=et(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",mintType:"public",contract:z(t.word(0),"mint NFT contract"),feeRecipient:z(t.word(1),"mint fee recipient"),recipient:z(t.word(2),"mint recipient"),quantity:ae(t.word(3),"mint quantity")}}function ks(e){let t;try{t=Wn.decodeFunctionData("mintAllowList",e)}catch{throw new Error("envelope: malformed SeaDrop mintAllowList calldata")}let r=t[4],n=[...t[5]].map(String);if(n.length<1||n.length>64||n.some(c=>!/^0x[0-9a-fA-F]{64}$/.test(c)))throw new Error("envelope: bounded canonical SeaDrop allowlist proof required");if(Wn.encodeFunctionData("mintAllowList",[t[0],t[1],t[2],t[3],r,n]).toLowerCase()!==String(e).toLowerCase())throw new Error("envelope: SeaDrop allowlist calldata must be canonical");let i=BigInt(r.startTime),a=BigInt(r.endTime);if(a<=i)throw new Error("envelope: SeaDrop allowlist stage time range is invalid");let u=BigInt(t[3]);if(BigInt(r.maxTotalMintableByWallet)<u)throw new Error("envelope: SeaDrop allowlist wallet cap is below quantity");return{kind:"mint",action:"mint",mintType:"allowlist",contract:$(t[0],"mint NFT contract"),feeRecipient:$(t[1],"mint fee recipient"),recipient:$(t[2],"mint recipient"),quantity:u,mintPrice:BigInt(r.mintPrice),startTime:i,endTime:a,dropStageIndex:BigInt(r.dropStageIndex),proof:n}}function Ts(e,t){let r=Pe(e);if(String(t).toLowerCase()==="nft-mint")return Os(e);let n=hs[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{...Is(e),selector:r,provider:n.provider};if(n.layout==="seadrop-mint-allowlist")return{...ks(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function Os(e){let t=Pe(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=gs[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=et(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:ae(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function Rt(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 Zn(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=$(e.owner,"owner"),u=e.artifact,c=Number(u?.chainId??Rt(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(q(c,t.chains,"chain"),u?.owner!==void 0&&$(u.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let s=Rt(e);if(!s.length||s.length>8)throw new Error("envelope: bounded EVM transaction batch required");let d=0n,l=0n,f=0n;for(let p of s){if(!p||typeof p!="object"||Array.isArray(p))throw new Error("envelope: structured EVM transaction required");if(Number(p.chainId)!==c)throw new Error("envelope: every batch leg must use the same chain");if($(p.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(q(Pe(p.data),t.selectors,"selector"),d+=k(p.value??0,"value"),l+=k(p.gasLimit,"gasLimit"),f+=Yn(p),ue(c)&&(p.l1FeeWei===void 0||p.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(d>k(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>k(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(f>k(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:s,chainId:c,owner:a,totalValue:d,totalGas:l,totalFee:f}}function eo(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=gt(e.provider,"provider",64).toLowerCase();q(i,t.providers,"provider");let a=Zn(e,t,o,{nowMs:r}),u=[],c=-1;for(let m=0;m<a.transactions.length;m++){let h=a.transactions[m],g=Es(h.data),w;if(g){if(c!==-1)throw new Error("envelope: approval must be before action");if(k(h.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let S=$(h.to,"approval token");if(q(S,t.tokens,"token"),q(g.spender,t.spenders,"spender"),g.amount>k(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");w={...g,token:S,index:m}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");q(h.to,t.destinations,"destination"),w={...vs(h.data,i),target:$(h.to,"action target"),index:m},c=m}let E=k(h.value??0,"value"),b=k(h.gasLimit,"gasLimit");u.push({...w,value:E,gas:b,fee:Yn(h)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let s=u[c],d=o==="evm-swap"?"swap":"bridge";if(s.action!==d||e.action!==d)throw new Error("envelope: surface/action/calldata mismatch");if($(e.destination,"destination")!==s.target)throw new Error("envelope: destination must equal decoded action target");if(s.recipient!==a.owner)throw new Error("envelope: decoded recipient must equal owner");if(s.depositor&&s.depositor!==a.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(q(s.inputToken,t.tokens,"input token"),q(s.outputToken,t.tokens,"output token"),s.amountIn<=0n||s.amountIn>k(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(s.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(nr(e.autoSlippage,{nowMs:r,chainId:a.chainId,venue:i,tx:a.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(s.minimumOut!==k(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(s.action==="bridge"&&k(e.toChainId,"toChainId")!==s.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=u.filter(m=>m.kind==="approval");if(!new Set([...ws,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(m=>String(m).toLowerCase()):[]]).has(s.inputToken))throw new Error("envelope: strict local signer swap/bridge requires native input token; use wallet signing for token-unit rails");if(l.length)throw new Error("envelope: native-value action must not include token approval");if(s.value!==s.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let p=Object.freeze({quoteAmountOut:k(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:k(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...a,decoded:u,action:s,provider:i,authenticatedQuote:p}}function Cs(e,t,{nowMs:r}){let n=e.anvilAttestation,o=e.artifact?.anvilAttestation;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("envelope: Anvil attestation is required");if(!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: Anvil attestation artifact mismatch");if(Number(n.version)!==1||n.source!=="anvil-snapshot-rpc-reviewed-runtime")throw new Error("envelope: unsupported Anvil attestation");if(Number(n.chainId)!==4663)throw new Error("envelope: Anvil attestation chain mismatch");let i=$(e.destination,"Anvil market"),a=$(e.contract,"NFT contract"),u=$(e.paymentToken,"payment token");if($(n.market,"attested Anvil market")!==i)throw new Error("envelope: Anvil attestation market mismatch");if($(n.collection,"attested NFT collection")!==a)throw new Error("envelope: Anvil attestation collection mismatch");if($(n.paymentToken,"attested payment token")!==u)throw new Error("envelope: Anvil attestation payment token mismatch");let c=Number(e.paymentTokenDecimals??e.artifact?.paymentTokenDecimals);if(!Number.isSafeInteger(c)||c<0||c>255||Number(n.paymentTokenDecimals)!==c)throw new Error("envelope: Anvil payment token decimals mismatch");let s=k(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei").toString();if(k(n.nativeSwapFeeWei,"attested nativeSwapFeeWei").toString()!==s)throw new Error("envelope: Anvil attestation native swap fee mismatch");let d=Number(n.snapshotFetchedAtMs),l=Number(n.snapshotExpiresAtMs);if(!Number.isFinite(d)||!Number.isFinite(l)||d>r||l<=r||l<=d)throw new Error("envelope: Anvil snapshot attestation is stale");let f=k(n.blockNumber,"attested blockNumber");if(f<=0n||!/^0x[0-9a-f]{64}$/.test(String(n.blockHash||"").toLowerCase()))throw new Error("envelope: Anvil block attestation is invalid");let p=String(n.runtimeCodeHash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(p))throw new Error("envelope: Anvil runtime code hash is invalid");let m=Object.entries(t.anvilRuntimeCodeHashes||{}).find(([g])=>g.toLowerCase()===i)?.[1];if(!m||String(m).toLowerCase()!==p)throw new Error("policy: Anvil runtime code hash is not reviewed");let h=Object.entries(t.nftPaymentTokenCaps||{}).find(([g])=>g.toLowerCase()===u)?.[1];if(!h||Number(h.decimals)!==c)throw new Error("policy: Anvil payment token decimals are not reviewed");return Object.freeze({...n,market:i,collection:a,paymentToken:u,paymentTokenDecimals:c,runtimeCodeHash:p,blockNumber:f})}function Gn(e,t){let r=e.artifact,n=e.anvilQuote,o=r?.anvilQuote;if(!n||typeof n!="object"||Array.isArray(n)||!o||JSON.stringify(o)!==JSON.stringify(n))throw new Error("envelope: exact Anvil quote artifact mismatch");if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("envelope: exact Anvil quote confirmation required");let i=t==="buy"?[[n.totalCostRaw,"anvilQuote.totalCostRaw"],[e.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw"],[r?.maxPaymentTokenAmountRaw,"artifact maxPaymentTokenAmountRaw"],[e.exactQuoteTotalCostRaw,"exactQuoteTotalCostRaw"],[r?.exactQuoteTotalCostRaw,"artifact exactQuoteTotalCostRaw"],[e.preconditions?.confirmedTotalCostRaw,"confirmedTotalCostRaw"]]:[[n.netPayoutRaw,"anvilQuote.netPayoutRaw"],[e.minPayoutRaw,"minPayoutRaw"],[r?.minPayoutRaw,"artifact minPayoutRaw"],[e.exactQuoteNetPayoutRaw,"exactQuoteNetPayoutRaw"],[r?.exactQuoteNetPayoutRaw,"artifact exactQuoteNetPayoutRaw"],[e.preconditions?.confirmedNetPayoutRaw,"confirmedNetPayoutRaw"]],a=k(i[0][0],i[0][1]);for(let[u,c]of i.slice(1))if(k(u,c)!==a)throw new Error(`envelope: Anvil ${t} exact settlement limit mismatch`);return a}function to(e,t,{nowMs:r=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint or NFT action");let n=gt(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();ht(n,t.providers,"provider");let o=Zn(e,t,"evm-nft",{nowMs:r});if(n==="anvil-nft"){if(e.action!=="nft")throw new Error("envelope: Anvil requires NFT action");if(o.chainId!==4663)throw new Error("envelope: Anvil requires chain 4663");if(t.confirmationMode!=="exact-human")throw new Error("policy: Anvil requires exact-human confirmation");if(o.transactions.length!==1)throw new Error("envelope: Anvil requires one atomic action with pre-existing approval");if(Number(e.slippageBps)!==0)throw new Error("envelope: Anvil exact limit requires zero slippageBps");let[p]=o.transactions,m=$(e.destination,"Anvil market");if($(p.to,"Anvil action target")!==m)throw new Error("envelope: Anvil action target mismatch");q(m,t.destinations,"destination");let h=$(e.contract??e.artifact?.contract,"NFT contract");if(ht(h,t.nftContracts,"NFT contract"),$(e.marketCollection??e.artifact?.marketCollection,"Anvil market collection")!==h)throw new Error("envelope: Anvil market collection mismatch");let w=$(e.paymentToken??e.artifact?.paymentToken,"payment token");ht(w,t.erc20Tokens,"ERC20 token");let E=Cs(e,t,{nowMs:r}),b=k(e.tokenId??e.artifact?.tokenId,"tokenId"),S=k(e.nativeSwapFeeWei??e.artifact?.nativeSwapFeeWei,"nativeSwapFeeWei");if(o.totalValue!==S||k(p.value??0,"Anvil action value")!==S)throw new Error("envelope: Anvil native swap fee mismatch");if(S>k(t.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"))throw new Error("policy: Anvil native swap fee exceeds cap");let I=gt(e.nftAction,"nftAction",8).toLowerCase(),T;if(I==="buy"){let v=Gn(e,I),C=Object.entries(t.nftPaymentTokenCaps||{}).find(([ce])=>ce.toLowerCase()===w)?.[1];if(!C)throw new Error("policy: Anvil payment-token cap required");if(v>k(C.maxPerTradeRaw,"maxPerTradeRaw"))throw new Error("policy: Anvil payment amount exceeds cap");if(e.preconditions?.allowanceVerified!==!0||k(e.preconditions?.allowanceRaw,"allowanceRaw")<v)throw new Error("envelope: Anvil pre-existing allowance proof required");let R=Bt.decodeFunctionData("buySpecificNFT",p.data);if(Bt.encodeFunctionData("buySpecificNFT",[R[0],R[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil buy calldata");if(BigInt(R[0])!==b)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(R[1])!==v)throw new Error("envelope: Anvil maxCost mismatch");T={kind:"nft",action:"buy",tokenId:b,maxPaymentTokenAmountRaw:v,target:m}}else if(I==="sell"){let v=e.preconditions||{},C=$(v.approvedAddress,"NFT approval address");if(v.nftApprovalVerified!==!0||C!==m&&v.approvedForAll!==!0)throw new Error("envelope: Anvil pre-existing NFT approval proof required");let R=Gn(e,I),j=Bt.decodeFunctionData("sellNFT",p.data);if(Bt.encodeFunctionData("sellNFT",[j[0],j[1]]).toLowerCase()!==String(p.data).toLowerCase())throw new Error("envelope: non-canonical Anvil sell calldata");if(BigInt(j[0])!==b)throw new Error("envelope: Anvil tokenId mismatch");if(BigInt(j[1])!==R)throw new Error("envelope: Anvil minPayout mismatch");T={kind:"nft",action:"sell",tokenId:b,minPayoutRaw:R,target:m}}else throw new Error("envelope: unsupported Anvil NFT action");return{...o,provider:n,nftAction:I,tokenId:b,paymentToken:w,paymentTokenDecimals:E.paymentTokenDecimals,anvilAttestation:E,decoded:[T]}}let i=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;if(i?.oraclePrepared===!0&&dn(i,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"}),o.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let a=o.transactions[0],u=Pe(a.data);q(u,t.selectors,"selector"),q(a.to,t.destinations,"destination");let c=Ts(a.data,n),s=$(e.contract??e.artifact?.contract,"NFT contract");if(ht(s,t.nftContracts,"NFT contract"),(c.contract||$(a.to,"NFT contract"))!==s)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==o.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&ht(c.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let l=k(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>k(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=k(e.totalWei??e.artifact?.totalWei,"totalWei");if(o.totalValue!==f)throw new Error("envelope: mint value does not match declared totalWei");if(c.mintType==="allowlist"){let p=BigInt(Math.floor(r/1e3));if(c.startTime>p||c.endTime<=p)throw new Error("policy: SeaDrop allowlist stage is not open");if(c.mintPrice*l!==f)throw new Error("envelope: SeaDrop allowlist price does not match declared totalWei")}if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&k(e.priceWei??e.artifact.priceWei,"priceWei")*l!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>k(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...o,provider:n,decoded:[{...c,target:$(a.to,"mint target"),value:o.totalValue,gas:o.totalGas,fee:o.totalFee}]}}function Ns(e,{localsWaiver:t=!1}={}){if(!(e in Ar))throw new Error("fee: unknown action");return t?0:Ar[e]}function yt(e,t,{nowMs:r=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:a=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let u=gt(e.surface,"surface",16);if(!Kn.has(u))throw new Error("envelope: unsupported public surface");let c=gt(e.action,"action",32);q(u,t.surfaces,"surface"),q(c,t.actions,"action"),q(e.owner,t.owners,"owner"),q(e.destination,t.destinations,"destination");let s=Hn(t.maxTtlMs,"maxTtlMs"),d=Hn(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>s)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>d)throw new Error("policy: slippage exceeds cap");let l=e.artifact;if(!l||typeof l!="object"||Array.isArray(l))throw new Error("envelope: structured artifact required");if(u==="evm-swap"||u==="evm-bridge")eo(e,t,{nowMs:r,routeAttestationSecret:o});else if(u==="evm-nft")to(e,t,{nowMs:r});else if(u==="evm"){if(!["transfer","approve","delegate","identity"].includes(c))throw new Error(c==="mint"?"envelope: generic evm requires transfer or approve; use strict evm-nft for mint action":"envelope: generic evm requires transfer, approve, delegate, or identity");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(Number(l.type)===4&&c!=="delegate")throw new Error("envelope: type-4 requires delegate");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");Nt({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:a});let m=String(l.data||"0x").toLowerCase(),h=k(l.value,"EVM value");if(c==="delegate"){if(Number(l.type)!==4)throw new Error("envelope: delegate requires type-4");if(m!=="0x")throw new Error("envelope: 7702 delegate calldata must be empty");if(h!==0n)throw new Error("envelope: 7702 delegate cannot transfer native value")}else if(c==="identity"){if(h!==0n)throw new Error("envelope: ERC-8004 identity cannot transfer native value");let g=m.slice(0,10);if(g!=="0xf2c298be"&&g!=="0x0af28bd3")throw new Error("envelope: ERC-8004 selector not allowed")}else if(m==="0x"){if(h===0n)throw new Error("envelope: native EVM transfer value required")}else if(J(m)){if(h!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else u==="btc"?cr(e,t):u==="sol"?mr(e,t):u==="hl"?ve(e,t):u==="poly"?Ie(e,t):u==="lighter"?ke(e,t):u==="evm-order"&&_e(e,t);let f=Number(e.fee?.oracleFeeBps)===0&&Ar[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=Ns(c,{localsWaiver:f});if(Number(e.fee?.oracleFeeBps)!==p)throw new Error("fee: final artifact fee mismatch");return!0}var vr=Object.freeze([...Kn]),Gf=Object.freeze({...Xn});function Ir(e,t){if(e.surface==="hl")return ve(e,t);if(e.surface==="poly")return Ie(e,t);if(e.surface==="lighter")return ke(e,t);if(e.surface==="evm-order")return _e(e,t);if(e.surface==="btc")return cr(e,t);if(e.surface==="sol")return mr(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=eo(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=to(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalFee.toString();if(r.provider==="anvil-nft"&&r.nftAction==="buy"){let i=k(e.maxPaymentTokenAmountRaw??e.artifact?.maxPaymentTokenAmountRaw,"maxPaymentTokenAmountRaw").toString(),a=r.totalValue.toString(),u=r.totalFee,c=[{unit:`erc20:${r.paymentToken}`,value:i,notional:i,fee:"0"},{unit:"wei",value:a,notional:(r.totalValue+u).toString(),fee:u.toString()}].sort((s,d)=>s.unit<d.unit?-1:s.unit>d.unit?1:0);return Object.freeze({units:c})}let o=r.totalValue.toString();return Object.freeze({unit:"wei",value:o,notional:(r.totalValue+r.totalFee).toString(),fee:n})}if(String(e.surface).startsWith("evm")){let r=k(e.artifact?.value,"EVM value"),n=k(e.artifact?.gasLimit,"EVM gasLimit"),o=k(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+k(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+k(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 ro(e={}){let t={};for(let r of vr){let n=e[r];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${r} requires simulate, sign, and broadcast functions`);t[r]=Object.freeze({simulate:(o,i)=>n.simulate(structuredClone(o),structuredClone(i)),sign:(o,i)=>n.sign(structuredClone(o),structuredClone(i)),broadcast:(o,i,a)=>n.broadcast(o,structuredClone(i),structuredClone(a))})}}return Object.freeze(t)}function _t(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 uo}from"node:crypto";import{ed25519 as js}from"@noble/curves/ed25519.js";import{base58 as fo}from"@scure/base";import{RawTx as Lr,SigHash as Fe,Transaction as $r}from"@scure/btc-signer";import{Transaction as Br,keccak256 as Cr,verifyTypedData as Nr}from"ethers";import{encode as Ls}from"@msgpack/msgpack";import{keccak256 as $s,verifyTypedData as Bs}from"ethers";var tt=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),kr=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function no(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 Rs(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Ls(e)),no(t)];if(r){let a=String(r).replace(/^0x/i,"");if(!/^[0-9a-fA-F]{40}$/.test(a))throw new Error("hl-l1: vaultAddress must be a 20-byte address");i.push(Buffer.from([1]),Buffer.from(a,"hex"))}else i.push(Buffer.from([0]));return n!=null&&i.push(Buffer.from([0]),no(n)),$s(Buffer.concat(i))}function Tr(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:Rs(e,t,{vaultAddress:n,expiresAfter:o})}}function oo(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=Tr(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==tt.name||String(t.domain?.version)!==tt.version||Number(t.domain?.chainId)!==tt.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(tt.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(kr.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 io({wallet:e,action:t,nonce:r,isMainnet:n=!0,vaultAddress:o=null,expiresAfter:i=null}){if(!e||typeof e.signTypedData!="function")throw new Error("hl-l1: wallet required");let a=Tr(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(tt,kr,a)}function ao({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:a=null}){try{let u=Tr(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:a}),c=Bs(tt,kr,u,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var _s=[["ApiKeyIndex","api_key_index","apiKeyIndex"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"],["L1Sig","l1_sig","l1Sig"]];function Or(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)Or(t);return}for(let t of Object.values(e))Or(t)}}}function Ps(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 Or(e),JSON.parse(JSON.stringify(e))}function Pt(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 Fs(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 so(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 nt(e,t,r,n={}){let o=t.filter(a=>e[a]!==void 0&&e[a]!==null);if(o.length===0)throw new Error(`lighter: ${r} required`);let i=o.map(a=>so(e[a],r,n));if(new Set(i).size>1)throw new Error(`lighter: conflicting ${r}`);return i[0]}function Ds(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 rt(e,t,r,n){let o=nt(e,t,n);if(BigInt(o)!==Pt(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function Ms(e,t,r,n){let o=nt(e,t,n,{signed:!0});if(BigInt(o)!==Fs(r,n))throw new Error(`lighter: signed ${n} must match the prepared order`);return o}function qs(e){let t={};for(let[r,n]of _s.entries()){let o=n.filter(a=>e[a]!==void 0&&e[a]!==null);if(!o.length)continue;let i=o.map(a=>{let u=e[a];if(r<3)return so(u,n[0]);if(typeof u!="string"||u.length===0)throw new Error(`lighter: signed ${n[0]} must be a non-empty string`);return u});if(new Set(i).size>1)throw new Error(`lighter: conflicting ${n[0]}`);t[n[0]]=i[0]}return t}function Et(e,t){let r=Ps(t),n=rt(r,["AccountIndex","account_index","accountIndex"],e.accountIndex,"AccountIndex"),o=rt(r,["ClientOrderIndex","client_order_index","clientOrderIndex"],e.clientOrderIndex,"ClientOrderIndex"),i=rt(r,["Type","type"],e.orderType,"Type"),a=rt(r,["TimeInForce","time_in_force","timeInForce"],e.timeInForce,"TimeInForce"),u=rt(r,["ReduceOnly","reduce_only","reduceOnly"],e.reduceOnly,"ReduceOnly"),c=rt(r,["TriggerPrice","trigger_price","triggerPrice"],e.triggerPrice,"TriggerPrice"),s=Ms(r,["OrderExpiry","order_expiry","orderExpiry"],e.orderExpiry,"OrderExpiry"),d=nt(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),l=nt(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),f=nt(r,["Price","price"],"Price");if(BigInt(d)!==Pt(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(BigInt(l)!==Pt(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(BigInt(f)!==Pt(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let p=Ds(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,h=e.side==="sell";if(m!==h)throw new Error("lighter: signed IsAsk must match the prepared side");let g=nt(r,["txType","tx_type","TxType"],"txType");if(g!==yr)throw new Error("lighter: signed txType must be official create-order");let w={...qs(r),AccountIndex:n,ClientOrderIndex:o,Type:i,TimeInForce:a,ReduceOnly:u,TriggerPrice:c,OrderExpiry:s,MarketIndex:Number(d),BaseAmount:Number(l),Price:Number(f),IsAsk:m?1:0,txType:g},E=JSON.stringify(w),b=JSON.parse(E);if(b.MarketIndex!==Number(d)||b.BaseAmount!==Number(l)||b.Price!==Number(f)||b.IsAsk!==(m?1:0)||b.txType!==g)throw new Error("lighter: canonical tx_info mutated");return{txType:g,txInfo:E,submitTo:Er(e.submitTo)}}function co(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var ot=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},Ft=e=>String(e||"").toLowerCase();function Us(e,t){if(typeof e!="string")return!1;let r,n;try{r=Br.from(e),n=Br.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce,type:t.type,accessList:t.accessList,authorizationList:t.authorizationList})}catch{return!1}return Ft(r.from)!==Ft(t.from)||Ft(r.to)!==Ft(t.to)?!1:r.unsignedHash===n.unsignedHash}function zs(e){let t=Buffer.from(Lr.encode(e)),r=uo("sha256").update(t).digest();return Buffer.from(uo("sha256").update(r).digest()).reverse().toString("hex")}function lo(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||zs(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 Ws(e,t){let r=ot(e),n=ot(t.psbt);if(!r||!n)return!1;try{let o=$r.fromPSBT(n),i=$r.fromPSBT(r);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let a=0;a<i.inputsLength;a++){let u=i.getInput(a),c=o.getInput(a);if(!lo(c)||!lo(u))return!1;let s=(w,E)=>{if(w==null&&E==null)return!0;if(w==null||E==null)return!1;try{return Buffer.from(w).equals(Buffer.from(E))}catch{return!1}},d=(w,E)=>{if(w==null&&E==null)return!0;if(w==null||E==null)return!1;try{return Buffer.from(Lr.encode(w)).equals(Buffer.from(Lr.encode(E)))}catch{return s(w,E)}};if(!!u.witnessUtxo!=!!c.witnessUtxo||u.witnessUtxo&&(BigInt(u.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!s(u.witnessUtxo.script,c.witnessUtxo.script))||!d(u.nonWitnessUtxo,c.nonWitnessUtxo)||!s(u.redeemScript,c.redeemScript)||!s(u.witnessScript,c.witnessScript)||u.sighashType!==void 0&&u.sighashType!==Fe.DEFAULT&&u.sighashType!==Fe.ALL)return!1;let l=w=>!(w instanceof Uint8Array)||w.length<9?!1:w[w.length-1]===Fe.ALL,f=w=>w instanceof Uint8Array?w.length===64?!0:w.length===65&&w[64]===Fe.ALL:!1;for(let w of u.partialSig||[]){let E=Array.isArray(w)?w[1]:w;if(!l(E))return!1}if(u.tapKeySig&&!f(u.tapKeySig))return!1;for(let w of u.tapScriptSig||[]){let E=Array.isArray(w)?w[1]:w;if(!f(E))return!1}let p=w=>w[w.length-1]===Fe.ALL,m=w=>w.length>=9&&w.length<=73&&w[1]===w.length-3&&w[2]===2,h=w=>{let E=!1;for(let b of w)if(b instanceof Uint8Array){if(b[0]===48){if(!m(b)||!p(b))return!1;E=!0;continue}if(b.length===64){E=!0;continue}if(b.length===65){if(b[64]!==Fe.ALL&&b[64]!==Fe.DEFAULT)return!1;E=!0}}return E};if(u.finalScriptWitness){let w;if(Array.isArray(u.finalScriptWitness))w=u.finalScriptWitness;else if(u.finalScriptWitness instanceof Uint8Array){let E=u.finalScriptWitness,b=T=>{let v=E[T];return v===void 0?null:v<253?{value:v,next:T+1}:v===253?{value:E[T+1]|E[T+2]<<8,next:T+3}:null},S=b(0);if(!S)return!1;w=[];let I=S.next;for(let T=0;T<S.value;T++){let v=b(I);if(!v||I+v.value>E.length)return!1;w.push(E.slice(v.next,v.next+v.value)),I=v.next+v.value}if(I!==E.length)return!1}else return!1;if(!w.length||!h(w))return!1}if(u.finalScriptSig instanceof Uint8Array&&u.finalScriptSig.length){let w=u.finalScriptSig,E=[],b=0;for(;b<w.length;){let S=w[b];if(S>=1&&S<=75){if(b+1+S>w.length)return!1;E.push(w.slice(b+1,b+1+S)),b+=1+S;continue}if(S===76){let I=w[b+1];if(I===void 0||b+2+I>w.length)return!1;E.push(w.slice(b+2,b+2+I)),b+=2+I;continue}return!1}if(!E.length||!h(E))return!1}if(![u.partialSig,u.tapKeySig,u.tapScriptSig,u.finalScriptSig,u.finalScriptWitness].some(w=>Array.isArray(w)||w instanceof Uint8Array?w.length>0:w!=null))return!1}return!0}catch{return!1}}function po(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 Hs(e,t,r){let n=ot(e),o=ot(t.messageBase64);if(!n||!o)return!1;let i=po(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let u=n.subarray(i.offset,a),c=n.subarray(a);if(!c.equals(o))return!1;try{let s=fo.decode(String(r));return s.length===32&&js.verify(u,c,s)}catch{return!1}}function mo(e,t,r,n){if(e==="evm-order"){let o=r?.domain||r?.typedData?.domain,i=r?.types||r?.typedData?.types,a=r?.message||r?.typedData?.message;if(!o||!i||!a)return!1;try{return String(Nr(o,i,a,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}}if(String(e).startsWith("evm"))return Us(t,r);if(e==="btc")return Ws(t,r);if(e==="sol")return Hs(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String(Nr(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return ao({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(Nr(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Et(r,t),!0}catch{return!1}return!1}function wo(e,t){try{if(e==="evm-order")return Cr(t);if(String(e).startsWith("evm"))return Br.from(t).hash;if(e==="btc"){let r=ot(t);if(!r)return null;let n=$r.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=ot(t);if(!r)return null;let n=po(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?fo.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return Cr(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return Cr(t)}catch{}return null}var Ks=e=>String(e||"").toLowerCase();function V(e){return Js("sha256").update(JSON.stringify(e)).digest("hex")}function qt(e,t,r={}){return Nt(e,t,r)}async function Xs(e,t={}){if(!ue(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 go(e,t,r=!1){if(!ue(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 Dt=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=Gs(32).toString("hex");return this.#e.set(o,{digest:V(t),owner:Ks(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(V(r),"hex");if(!Vs(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(t)),n}clear(){this.#e.clear()}};function Ys(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(J(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 Qs(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 Zs(e){return e==="evm"||e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Mt(e,t){let r=String(t||"");if(e==="evm-order"||String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(r);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(r);if(e==="sol")try{let n=ho.decode(r);return n.length===64&&ho.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 yo(e,t,r){return!Mt(e,t)||!Mt(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function ec(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 Rr({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:u}){let c=ec(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(t?.triggerAttestation,e,u())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(a)return n.confirmations.consume(r,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=u())throw new Error("confirmation: expired nonce");return i}function tc(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function rc(e,t){return e&&tc(e.surface)?Rt(e):[t]}function nc(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!yo(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function oc(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:Qs(r,n)}}async function _r(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:g,...w}=e||{};return w})(),i=rc(n,o),a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,u=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),c=await Rr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:null,consumeNonce:!0,nowMs:u}),s=V(e),d=(g={})=>{n?yt(n,a,g):(qt(o,a,{nowMs:g.nowMs,networkFees:g.networkFees,requireNetworkFees:g.requireNetworkFees}),Ys(o))},l=async g=>{let w=!n||Zs(n.surface),E=w?await Xs(g,r):void 0;return{nowMs:u(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:E,requireNetworkFees:w&&ue(g?.chainId)}};d({nowMs:u(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let g of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[g]!="function")throw new Error(`signer: ${g} is required`);let f=r.reserveLedger(n||e,a);if(!f)throw new Error("signer: ledger reservation required");let p=!1,m=[];try{for(let g of i){if(typeof r.simulate!="function"||await r.simulate(g,n)!==!0)throw new Error("signer: strict affirmative simulation required");let w=await l(g);if((w.requireNetworkFees||w.networkFees!=null)&&go(g,w.networkFees,w.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await Rr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:u}),d(w),r.validateReservation(f,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0),p=!0;let E=await r.sign(g,n);if(typeof r.verifySigned!="function"||await r.verifySigned(E,g,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!r.isArmed())throw new Error("signer: disarmed before broadcast");if(V(e)!==s)throw new Error("signer: artifact mutated after signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await Rr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:u});let b=await l(g);(b.requireNetworkFees||b.networkFees!=null)&&go(g,b.networkFees,b.requireNetworkFees),d(b),r.validateReservation(f,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0);let S=await r.broadcast(E,g,n),I=S?.status,T=n?.surface||"evm",v=nc(S,T),C=wo(T,E);if(!yo(T,v,C))throw new Error("signer: receipt transaction hash does not match signed bytes");if(I===0||I==="0x0")throw Mt(T,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(I!==1&&I!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Mt(T,v))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(oc(S,v))}}catch(g){throw p||r.releaseLedger(f),g}if(r.commitLedger(f),m.length===1){let g={receipt:m[0]};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}let h={receipts:m,status:"success"};return n?.surface==="evm-bridge"&&(h.originStatus="success",h.destinationStatus="unverified",h.destinationSuccess=!1,h.note="Origin-chain receipts do not prove destination-chain settlement."),h}var Eo=new Set(["127.0.0.1","::1","localhost"]),sc=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&ac(r,n)},O=(e,t,r)=>{let n=JSON.stringify(r);e.writeHead(t,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function cc(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 bt=e=>new Promise((t,r)=>{let n=0,o=[],i=!1;e.on("data",a=>{n+=a.length,n>64*1024&&!i?(i=!0,r(new Error("request refused")),e.resume()):i||o.push(a)}),e.on("end",()=>{if(!i)try{t(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{r(new Error("request refused"))}}),e.on("error",r)});function bo(e={}){let t=e.host||"127.0.0.1";if(!Eo.has(t))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let c of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[c]!="function")throw new Error(`signer: ${c} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Dt,n=e.pending||new Map;function o(c){let s=c.artifact?.version===1&&c.artifact?.surface?c.artifact:null,d=s?.artifact||c.artifact||{};return{id:c.digest.slice(0,8),digest:c.digest,surface:s?.surface||"evm",action:s?.action||"evm",chain:d.chainId??d.network??null,to:d.to||s?.destination||null,value:d.value??d.message?.sellAmount??d.message?.makingAmount??null,receiver:d.message?.receiver||d.typedData?.message?.receiver||null,maker:d.message?.maker||d.typedData?.message?.maker||null,makingAmount:d.message?.makingAmount||d.typedData?.message?.makingAmount||null,takingAmount:d.message?.takingAmount||d.typedData?.message?.takingAmount||null,sellAmount:d.message?.sellAmount||d.typedData?.message?.sellAmount||null,buyAmount:d.message?.buyAmount||d.typedData?.message?.buyAmount||null,kind:d.kind||null,type:d.type??null,authorizationList:d.authorizationList||null,feeAmount:d.message?.feeAmount||d.typedData?.message?.feeAmount||null,createdAtMs:c.createdAtMs}}function i(c){let s=String(c||"").trim().toLowerCase().replace(/^0x/,"");return s?[...n.values()].filter(d=>d.digest.toLowerCase().startsWith(s)||d.digest.slice(0,8)===s):[...n.values()]}let a=e.origin||`http://${t}`;return ic.createServer(async(c,s)=>{try{let d=String(c.headers.authorization||"").replace(/^Bearer /i,"");if(!sc(d,e.token))return O(s,401,{error:"unauthorized"});let l=cc(c.headers.host);if(!Eo.has(l))return O(s,403,{error:"host refused"});if(c.headers.origin&&c.headers.origin!==a)return O(s,403,{error:"origin refused"});if(c.method==="GET"&&c.url==="/status"){let f=typeof e.readPolicy=="function"?e.readPolicy():e.policy,p=new Set(vr),m=Array.isArray(f?.surfaces)?f.surfaces.filter(h=>typeof h=="string"&&p.has(h)):[];return O(s,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:m,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(c.method==="POST"&&c.url==="/disarm")return e.disarm(),r.clear(),n.clear(),O(s,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(c.method))return O(s,405,{error:"request refused"});if(c.method==="POST"&&String(c.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return O(s,415,{error:"request refused"});if(c.method==="GET"&&c.url==="/pending"){let f=[...n.values()].map(o);return O(s,200,{ok:!0,armed:e.isArmed?.()===!0,count:f.length,items:f})}if(c.method==="POST"&&c.url==="/pending"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not queue human approvals"});let p=(await bt(c)).artifact;if(!p||typeof p!="object")return O(s,400,{error:"artifact required"});let m=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(m?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});let h=typeof e.nowMs=="function"?e.nowMs():Date.now();if(p?.surface==="cex"){if(typeof e.inspectCex!="function")return O(s,403,{error:"cex execution unavailable"});e.inspectCex(p,m,h)}else if(p?.version===1&&p?.surface)yt(p,m,{nowMs:h,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:E,...b}=p||{};qt(b,m,{nowMs:h})}let g=V(p),w=p?.surface==="cex"?Object.freeze(structuredClone(p)):p;return n.set(g,{artifact:w,digest:g,createdAtMs:h}),O(s,200,{ok:!0,...o(n.get(g))})}if(c.method==="POST"&&c.url==="/ack"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not accept messaging acks"});let f=await bt(c),p=i(f.digest||f.id);if(p.length===0)return O(s,404,{error:"no pending artifact"});if(p.length>1)return O(s,409,{error:"ambiguous digest; pass more hex"});let m=p[0];if((typeof e.readPolicy=="function"?e.readPolicy():e.policy)?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});if(e.isArmed?.()!==!0)return O(s,403,{error:"signer is disarmed"});if(m.artifact?.surface==="cex"){if(typeof e.verifyCexOwnerProof!="function"||e.verifyCexOwnerProof(f.ownerProof,{digest:m.digest})!==!0)return O(s,403,{error:"exact owner Allow proof required"});if(typeof e.cexExecute!="function")return O(s,403,{error:"cex execution unavailable"});n.delete(m.digest);let E=await e.cexExecute(m.artifact);return O(s,200,{ok:!0,executed:!0,digest:m.digest,id:m.digest.slice(0,8),result:E})}n.delete(m.digest);let g=r.issue({artifact:m.artifact,owner:m.artifact?.owner??m.artifact?.from,ttlMs:f.ttlMs}),w=await _r(m.artifact,g,{...e,confirmations:r});return O(s,200,{ok:!0,executed:!0,confirmationNonce:g,digest:m.digest,id:m.digest.slice(0,8),result:w})}if(c.method==="POST"&&c.url==="/deny"){let f=await bt(c),p=i(f.digest||f.id);return p.length===0?O(s,404,{error:"no pending artifact"}):p.length>1?O(s,409,{error:"ambiguous digest; pass more hex"}):(n.delete(p[0].digest),O(s,200,{ok:!0,denied:!0,id:p[0].digest.slice(0,8)}))}if(c.method==="POST"&&c.url==="/confirm"){if(e.autonomous===!0)return O(s,403,{error:"autonomous signer does not issue human confirmation nonces"});let f=await bt(c);if(f.artifact?.surface==="cex")return O(s,403,{error:"cex requires pending owner ack"});let p=V(f.artifact),m=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(m?.confirmationMode!=="exact-human")return O(s,403,{error:"exact-human policy required"});let h=typeof e.nowMs=="function"?e.nowMs():Date.now();if(f.artifact?.version===1&&f.artifact?.surface)yt(f.artifact,m,{nowMs:h,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:g,...w}=f.artifact||{};qt(w,m,{nowMs:h})}return typeof e.confirmArtifact!="function"?O(s,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(f.artifact,p,m)!==!0?O(s,400,{error:"exact human confirmation refused"}):O(s,200,{confirmationNonce:r.issue({artifact:f.artifact,owner:f.artifact?.owner??f.artifact?.from,ttlMs:f.ttlMs})})}if(c.method==="POST"&&c.url==="/execute"){let f=await bt(c);if(f.artifact?.surface==="cex")return O(s,403,{error:"cex requires pending owner ack"});let p=await _r(f.artifact,f.confirmationNonce,{...e,confirmations:r});return O(s,200,p)}return O(s,404,{error:"not found"})}catch(d){e.onError?.(String(d?.message||d));let l=String(c.url||"");return l==="/pending"||l==="/ack"||l==="/deny"?O(s,400,{error:String(d?.message||"request refused").slice(0,300)}):O(s,400,{error:"request refused"})}})}import{createCipheriv as xp,createDecipheriv as uc,randomBytes as lc,scryptSync as dc}from"node:crypto";import B from"node:fs";import it from"node:path";var fc="ORACLE-LOCAL-VAULT",pc=1,Ut=Object.freeze({N:1<<17,r:8,p:1}),mc=256*1024*1024,wc=16*1024;function jt(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 hc(e,t,r=Ut){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return dc(n,t,32,{...r,maxmem:mc})}function xo(e,t){if(e?.magic!==fc||e?.version!==pc)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!==Ut.N||e.kdf.r!==Ut.r||e.kdf.p!==Ut.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=jt(e.kdf.salt,32,"salt"),o=jt(e.cipher.iv,12,"iv"),i=jt(e.tag,16,"tag"),a=jt(e.ciphertext,1,"ciphertext",{max:wc}),{ciphertext:u,tag:c,...s}=e,d=hc(t,n);try{let l=uc("aes-256-gcm",d,o);return l.setAAD(Buffer.from(JSON.stringify(s))),l.setAuthTag(i),Buffer.concat([l.update(a),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{d.fill(0)}}function gc(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 yc(e){let t=it.dirname(e),r=B.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=B.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 N(e){let t;try{t=B.openSync(e,B.constants.O_RDONLY|B.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=B.fstatSync(t);if(gc(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=B.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 B.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{B.closeSync(t)}}function So(e){return JSON.parse(N(e))}function se(e,t){B.mkdirSync(it.dirname(e),{recursive:!0,mode:448}),yc(e);let r=it.join(it.dirname(e),`.${it.basename(e)}.${process.pid}.${lc(6).toString("hex")}.tmp`);try{let n=B.openSync(r,B.constants.O_CREAT|B.constants.O_EXCL|B.constants.O_WRONLY|B.constants.O_NOFOLLOW,384);try{B.writeFileSync(n,String(t)),B.fsyncSync(n)}finally{B.closeSync(n)}B.renameSync(r,e),B.chmodSync(e,384);let o=B.openSync(it.dirname(e),"r");try{B.fsyncSync(o)}finally{B.closeSync(o)}}catch(n){try{B.unlinkSync(r)}catch{}throw n}}var Ao=/^0x[0-9a-fA-F]+$/,Ec=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});function bc(e){let t=process.env[`ORACLE_PRIVATE_RELAY_${Number(e)}`];if(!t)return null;let r=t.split(",").map(n=>n.trim()).filter(Boolean);return r.length?r:null}function xc(e,{requirePrivate:t=!1}={}){let r=Number(e);if(!Number.isInteger(r))throw new Error("resolvePrivateRelay: chainId must be an integer");let n=Ec[r]||{name:`chain-${r}`,mode:"public-only",endpoints:[]},o=bc(r),i=o||n.endpoints,a=o&&n.mode==="public-only"?"mempool-private":n.mode,u=i.length>0&&a!=="public-only";if(t&&!u)throw new Error(`private relay: no keyless private endpoint for chain ${r} (${n.name}); set ORACLE_PRIVATE_RELAY_${r} to force one, or allow public fallback`);return{chainId:r,name:n.name,mode:a,endpoints:[...i],source:o?"env":"builtin",hasPrivate:u}}async function vo(e,{chainId:t,requirePrivate:r=!1,allowPublicFallback:n=!0,fetchImpl:o,timeoutMs:i=8e3}={}){if(typeof e!="string"||!Ao.test(e))throw new Error("submitPrivate: signedRawTx must be a 0x-hex string");let a=xc(t,{requirePrivate:r}),u=o||globalThis.fetch;if(!u)throw new Error("submitPrivate: no fetch implementation available");let c=[];for(let s of a.endpoints){let d=new AbortController,l=setTimeout(()=>d.abort(),i);try{let f=await u(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_sendRawTransaction",params:[e]}),signal:d.signal}),p=await f.text(),m=null;try{m=JSON.parse(p)}catch{}if(m&&m.result&&Ao.test(m.result))return{hash:m.result,endpoint:s,mode:a.mode,chainId:a.chainId,fellBack:!1};c.push({endpoint:s,error:m&&m.error&&m.error.message||`http ${f.status}`})}catch(f){c.push({endpoint:s,error:String(f&&f.message||f).slice(0,160)})}finally{clearTimeout(l)}}if(n&&!r)return{fellBack:!0,mode:a.mode,chainId:a.chainId,attempts:c};throw new Error(`submitPrivate: all private endpoints failed for chain ${a.chainId} (${c.map(s=>`${s.endpoint}:${s.error}`).join("; ")||"none configured"})`)}import{createHmac as Ac,randomBytes as vc,timingSafeEqual as Ic}from"node:crypto";import W from"node:fs";import De from"node:path";import{homedir as Pr}from"node:os";import{join as Fr}from"node:path";var Io=process.env.ORACLE_PUBLIC_DESKTOP==="1",Sc=Io?process.env.ORACLE_CONFIG_DIR||Fr(Pr(),".config","oracle"):Fr(Pr(),".config","oracle"),Op=Io?Sc:Fr(Pr(),".config","mad-desk");var Bp="0".repeat(64),Rp=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 zt(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(zt).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+zt(e[r])).join(",")+"}"}var _p=Promise.resolve();function Me(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=a=>{try{return W.realpathSync(a)}catch{return De.resolve(a)}},n=r(De.dirname(De.resolve(e))),o=r(De.dirname(De.resolve(t))),i=(a,u)=>u===a||u.startsWith(a+De.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var kc=864e5,K=(e,t)=>Ac("sha256",t).update(zt(e)).digest("hex"),fe=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Ic(r,n)},Tc=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Oc(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!fe(e.integrity.mac,K(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Ht(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=N(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!fe(n?.integrity?.mac,K(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 Cc(e,t,r,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let u=Ht(e,r);i=u.present&&u.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(t),policyMac:String(n)};i&&(a.ledgerInitialized=!0),se(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:K(a,r)}})+`
|
|
4
|
+
`)}function Nc(e,t){let r=Ht(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 Cc(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function Jt(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=N(t),o;try{o=JSON.parse(N(e))}catch(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=Oc(o,n);Me(r,e);let a=Ht(r,n),u=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(u!==a.sequence)throw new Error("policy: rolled back to a superseded policy");if(a.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!fe(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function at(e,t,r,n,o){let i=`${e}.continuity`,a;try{let u=JSON.parse(N(e));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!fe(u?.integrity?.mac,K(u.ledger,t)))throw new Error("integrity verification failed");if(a=u.ledger,!Number.isFinite(a?.windowStartMs)||!Array.isArray(a?.entries)||a.sequence!==void 0&&(!Number.isSafeInteger(a.sequence)||a.sequence<0))throw new Error("invalid ledger")}catch(u){if(u?.code==="ENOENT"){if(W.existsSync(i)||W.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=Ht(o,t);if(c.present&&c.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:r,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}try{let u=JSON.parse(N(i));if(u?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!fe(u?.integrity?.mac,K(u.marker,t)))throw new Error("continuity verification failed");if(u.marker?.version===2&&(u.marker.sequence!==a.sequence||!fe(u.marker.ledgerMac,K(a,t))))throw new Error("continuity rollback detected");if(u.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(W.existsSync(n)&&(u.marker?.version!==2||a.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(u.marker?.version===2){let c=JSON.parse(N(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!fe(c?.integrity?.mac,K(c.marker,t))||c.marker?.version!==1||c.marker.sequence!==a.sequence||!fe(c.marker.ledgerMac,K(a,t)))throw new Error("checkpoint rollback detected")}}catch(u){throw new Error(`ledger: corrupt or unreadable: ${u?.message||u}`)}if(r-a.windowStartMs>=kc){let u=new Date(r).toISOString().slice(0,10),c=d=>String(d||"").startsWith("cex:")&&String(d).endsWith(`:${u}`),s=a.entries.map(d=>{if(d.state==="reserved"||d.state==="consumed")return d;if(Array.isArray(d.units)){let l=d.units.map(p=>c(p.unit)?p:{...p,value:"0",notional:"0"}),f=l.some(p=>BigInt(p.value??0)>0n||BigInt(p.notional??0)>0n);return{...d,state:f?d.state:"consumed",units:l}}return c(d.unit)?d:{...d,state:"consumed",value:"0",notional:"0"}});return{windowStartMs:r,entries:s,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function Lc(e){return Array.isArray(e.units)?e.units:[{unit:e.unit||"wei",value:e.value,notional:e.notional,fee:e.fee}]}function Te(e,t,r){return e.reduce((n,o)=>{let i=Lc(o).find(a=>a.unit===r);return i?n+BigInt(i[t]??0):n},0n)}function Dr(e){if(!Array.isArray(e)||e.length===0)throw new Error("ledger: units array required");let t=new Set,r=e.map(n=>{let o=String(n?.unit||"");if(!o)throw new Error("ledger: unit required");if(t.has(o))throw new Error("ledger: duplicate unit in units array");t.add(o);let i=BigInt(n.value??0),a=BigInt(n.notional??0);if(i<0n||a<0n)throw new Error("ledger: unit value/notional must be non-negative");let u=n.fee===void 0?0n:BigInt(n.fee);if(u<0n)throw new Error("ledger: unit fee must be non-negative");return{unit:o,value:i.toString(),notional:a.toString(),fee:u.toString()}});return r.sort((n,o)=>n.unit<o.unit?-1:n.unit>o.unit?1:0),r}function $c(e,t){let r=e[t];if(r==null||r==="")throw new Error(`ledger: ${t} required`);return G(r,`ledger: ${t}`)}function Wt(e,t){if(String(t).startsWith("cex:")){let[,n,o,i,a,u]=String(t).split(":");if(!/^[A-Za-z0-9._-]{1,64}$/.test(n||"")||!/^[A-Za-z0-9._-]{1,64}$/.test(o||"")||!/^[a-z0-9._-]{1,32}$/.test(i||"")||!/^[A-Z0-9._-]{1,24}$/.test(a||"")||!/^\d{4}-\d{2}-\d{2}$/.test(u||""))throw new Error("ledger: invalid CEX accounting unit");let c=e.cexAccounts?.[n];if(!c||String(c.accountId)!==o||!Array.isArray(c.venues)||!c.venues.includes(i))throw new Error("ledger: CEX account/venue policy required");if(!c.symbolQuotes||!Object.values(c.symbolQuotes).includes(a))throw new Error("ledger: CEX quote policy required");let s=G(c.dailyGrossQuoteCap,"ledger: dailyGrossQuoteCap"),d=G(c.perOrderQuoteCap,"ledger: perOrderQuoteCap");return[s,s,d]}if(String(t).startsWith("erc20:")){let n=String(t).slice(6).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw new Error("ledger: invalid ERC20 accounting unit");let o=Object.entries(e.tokenCaps||e.nftPaymentTokenCaps||{}).find(([a])=>String(a).toLowerCase()===n)?.[1];if(!o)throw new Error("ledger: ERC-20 token caps required");let i=["maxDailyValueRaw","maxDailyNotionalRaw","maxPerTradeRaw"];for(let a of i)if(o[a]===void 0||o[a]===null||o[a]==="")throw new Error(`ledger: ${a} required`);return i.map(a=>BigInt(o[a]))}let r=t==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:t==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:t==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:t==="usdc"?["maxDailyValueUsdc","maxDailyNotionalUsdc","maxPerTradeUsdc"]:null;if(!r)throw new Error("ledger: unsupported accounting unit");if(t==="usdc"){let n=r.filter(c=>e[c]!==void 0&&e[c]!==null&&e[c]!=="");if(n.length===r.length)return r.map(c=>$c(e,c));if(n.length>0){let c=r.filter(s=>!n.includes(s));throw new Error(`ledger: ${c[0]} required`)}let o=e.maxDailyNotionalUsd??e.maxNotionalUsd??e.maxNotionalUsdc,i=e.maxPerTradeUsd??e.maxNotionalUsd??e.maxNotionalUsdc;if(o==null||o==="")throw new Error("ledger: maxDailyValueUsdc required");if(i==null||i==="")throw new Error("ledger: maxPerTradeUsdc required");let a=P(o,6,"ledger: maxDailyNotionalUsdc"),u=P(i,6,"ledger: maxPerTradeUsdc");return[a,a,u]}for(let n of r)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return r.map(n=>BigInt(e[n]))}function st(e,t){let r=`${e}.lock`,n=vc(16).toString("hex"),o;try{o=W.openSync(r,W.constants.O_CREAT|W.constants.O_EXCL|W.constants.O_WRONLY|(W.constants.O_NOFOLLOW||0),384),W.writeFileSync(o,n),W.fsyncSync(o)}catch(i){throw o!==void 0&&W.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return t()}finally{W.closeSync(o);try{N(r)===n&&W.unlinkSync(r)}catch{}}}function Oe(e,t,r,n,o){let i=`${e}.continuity`,a={...t,sequence:(t.sequence??0)+1},u=K(a,r);se(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:u}})+`
|
|
5
|
+
`);let c={version:2,sequence:a.sequence,ledgerMac:u};se(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:K(c,r)}})+`
|
|
6
|
+
`);let s={version:1,sequence:a.sequence,ledgerMac:u};W.mkdirSync(De.dirname(n),{recursive:!0,mode:448}),se(n,JSON.stringify({marker:s,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:K(s,r)}})+`
|
|
7
|
+
`),o&&Nc(o,r)}function xt({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:u=0,fee:c,units:s,policy:d,nowMs:l=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");Me(r,e);let p=N(t);return st(e,()=>{let m=at(e,p,l,r,n);if(m.entries.some(g=>String(g.tradeId)===f))throw new Error("ledger: replayed tradeId");let h;if(s!==void 0){let g=Dr(s);for(let w of g){let[E,b,S]=Wt(d,w.unit),I=BigInt(w.value),T=BigInt(w.notional);if(T>S)throw new Error("ledger: per-trade cap exceeded");if(Te(m.entries,"value",w.unit)+I>E||Te(m.entries,"notional",w.unit)+T>b)throw new Error("ledger: daily cap exceeded")}h={tradeId:f,units:g,state:"reserved",atMs:l}}else{let g=BigInt(a),w=BigInt(u),[E,b,S]=Wt(d,i);if(g<0n||w<0n||w>S)throw new Error("ledger: per-trade cap exceeded");if(Te(m.entries,"value",i)+g>E||Te(m.entries,"notional",i)+w>b)throw new Error("ledger: daily cap exceeded");h={tradeId:f,unit:i,value:g.toString(),notional:w.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:l}}return m.entries.push(h),Oe(e,m,p,r,n),structuredClone(h)})}function ko({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:u=Date.now()}){Me(r,e);let c=N(t);return st(e,()=>{let s=at(e,c,u,r,n),d=s.entries.find(h=>String(h.tradeId)===String(o?.tradeId??"")&&h.state==="reserved");if(!d)throw new Error("ledger: reservation unavailable");if(Array.isArray(o?.units)||Array.isArray(d.units)){if(!Array.isArray(o?.units)||!Array.isArray(d.units))throw new Error("ledger: reservation unavailable");let h=Dr(o.units);if(JSON.stringify(h)!==JSON.stringify(d.units))throw new Error("ledger: reservation unavailable");if(a){if(!Array.isArray(a.units))throw new Error("ledger: reserved units no longer match decoded economics");let g=Dr(a.units);if(g.length!==d.units.length||g.some((w,E)=>w.unit!==d.units[E].unit))throw new Error("ledger: reserved units no longer match decoded economics");for(let w=0;w<g.length;w++)if(BigInt(g[w].value)>BigInt(d.units[w].value)||BigInt(g[w].notional)>BigInt(d.units[w].notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}for(let g of d.units){let[w,E,b]=Wt(i,g.unit);if(BigInt(g.notional)>b)throw new Error("ledger: per-trade cap exceeded");if(Te(s.entries,"value",g.unit)>w||Te(s.entries,"notional",g.unit)>E)throw new Error("ledger: daily cap exceeded")}return structuredClone(d)}if(d.unit!==o.unit||d.value!==o.value||d.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==d.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(d.value)||BigInt(a.notional)>BigInt(d.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=d.unit||"wei",[f,p,m]=Wt(i,l);if(BigInt(d.notional)>m)throw new Error("ledger: per-trade cap exceeded");if(Te(s.entries,"value",l)>f||Te(s.entries,"notional",l)>p)throw new Error("ledger: daily cap exceeded");return structuredClone(d)})}function To({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(r,e);let a=N(t);return st(e,()=>{let u=at(e,a,i,r,n),c=u.entries.find(s=>String(s.tradeId)===String(o??"")&&s.state==="reserved");if(!c||c.state!=="reserved")throw new Error("ledger: reservation unavailable");return c.state="committed",c.committedAtMs=i,Oe(e,u,a,r,n),structuredClone(c)})}function Oo({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(r,e);let a=N(t);return st(e,()=>{let u=at(e,a,i,r,n),c=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");let s=structuredClone(c);return c.state="consumed",c.releasedAtMs=i,Array.isArray(c.units)?c.units=c.units.map(d=>({...d,value:"0",notional:"0",fee:"0"})):(c.value="0",c.notional="0",c.fee="0"),Oe(e,u,a,r,n),s})}function Bc(e,t){if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(e)))throw new Error("ledger: authoritative CEX fill invalid");let[r,n=""]=String(e).split("."),o=n.length;return BigInt(r+n)>BigInt(t)*10n**BigInt(o)}function Co({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,expectedUnit:i,filledQuote:a,disposition:u,nowMs:c=Date.now()}){if(Me(r,e),!/^cex:/.test(String(i||""))||!["release","commit"].includes(u))throw new Error("ledger: CEX settlement binding refused");let s=N(t);return st(e,()=>{let d=at(e,s,c,r,n),l=d.entries.find(f=>f.tradeId===o&&f.state==="reserved"&&f.unit===i);if(!l)throw new Error("ledger: exact held CEX reservation unavailable");if(Bc(a,l.notional))throw new Error("ledger: CEX overfill refused; reservation retained");if(u==="release"){if(!/^0(?:\.0+)?$/.test(a))throw new Error("ledger: nonzero CEX fill cannot release");let f=structuredClone(l);return l.state="consumed",l.releasedAtMs=c,l.value="0",l.notional="0",l.fee="0",Oe(e,d,s,r,n),f}return l.state="committed",l.committedAtMs=c,l.filledQuote=a,Oe(e,d,s,r,n),structuredClone(l)})}function No({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){Me(r,e);let a=N(t);return st(e,()=>{let u=at(e,a,i,r,n),c=u.entries.find(d=>String(d.tradeId)===String(o??"")&&d.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");if(Array.isArray(c.units))return c.state="committed",c.committedAtMs=i,c.units=c.units.map(d=>{let l=BigInt(d.fee??0);return{...d,value:"0",notional:l.toString()}}),c.settledAs=c.units.some(d=>BigInt(d.notional)>0n)?"fee-only":"no-fee",Oe(e,u,a,r,n),structuredClone(c);let s=BigInt(c.fee??0);return s<=0n?(c.state="committed",c.committedAtMs=i,c.value="0",c.notional="0",c.settledAs="no-fee",Oe(e,u,a,r,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=s.toString(),c.settledAs="fee-only",Oe(e,u,a,r,n),structuredClone(c))})}function Lo(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:V(Tc(t))};return fe(e.mac,K(o,N(r)))}function Rc(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function $o(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:V(Rc(t))};return fe(e.mac,K(o,N(r)))}import{spawnSync as _c}from"node:child_process";function Bo(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=_c(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}var Pc=/^0x[0-9a-f]{40}$/,Fc=/^0x(?:[0-9a-f]{2})*$/,Dc=/^(?:0x)?[0-9a-f]{64}$/,Mc=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,qc=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,jc=new Set([12,15,18,21,24]),Gt=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function Mr(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(qc.test(e)||jc.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new Gt(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,i)=>Mr(o,`${t}[${i}]`,r));qe(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(Mc.test(i))throw new Gt(`${t}.${o}`);e[o]!==void 0&&(n[o]=Mr(e[o],`${t}.${o}`,o))}return n}function qe(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function St(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function ct(e,t){let r=String(St(e,t)).toLowerCase();if(!Pc.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function ye(e,t,{positive:r=!1}={}){try{let n=BigInt(St(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function qr(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function Ro(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Ro(t);Object.freeze(e)}return e}function Uc(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};qe(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:qr(String(n),`${t}.reason`)}}function zc(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Uc(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function Wc(e){if(e==null)return null;if(qe(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:qr(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=ye(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=ye(e.gasLimit,"simulation.gasLimit")),t}function Hc(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{qe(t,`assetDeltas[${r}]`);let n=ye(t.before,`assetDeltas[${r}].before`),o=ye(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),a;try{a=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(a!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:qr(String(St(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:a}})}function Jc(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{qe(t,`approvalDeltas[${r}]`);let n=ye(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:ct(t.token,`approvalDeltas[${r}].token`),spender:ct(t.spender,`approvalDeltas[${r}].spender`),owner:ct(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function _o(e={}){qe(e,"input");let t=Mr(e),r=t.tx==null?t:qe(t.tx,"tx"),n=ye(t.chainId??r.chainId,"chainId",{positive:!0}),o=ct(t.account??t.from??r.from,"account/from"),i=ct(t.destination??t.to??r.to,"destination/to"),a=String(St(t.prepareHash,"prepareHash")).toLowerCase();if(!Dc.test(a))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let u=t.route??t.venue;if(u==null)throw new TypeError("sign-time review: route/venue required");let c=t.decodedCalldata??t.decodedAction;if(c==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let s=String(St(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Fc.test(s))throw new TypeError("sign-time review: calldata/data must be even-length hex");let d=t.policyChecks!==void 0&&t.policyChecks!==null,l=zc(d?t.policyChecks:[]),f=Wc(t.simulation),p=Hc(t.assetDeltas),m=Jc(t.approvalDeltas),h=t.allowlistHits??[];if(!Array.isArray(h))throw new TypeError("sign-time review: allowlistHits must be an array");let g=f?.willRevert===!0||["failed","error"].includes(f?.status),w=f!=null&&f.willRevert===!1&&["ok","success"].includes(f.status),E=g||l.failed>0?"BLOCKED":w&&d&&l.checks.length>0&&p!=null?"READY":"UNKNOWN",b=typeof c=="string"?c:c.method??c.action??c.type??"transaction",S=`${E}: review ${b} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${p?.length??0} asset delta${p?.length===1?"":"s"}; local signature required`,I={reviewVersion:1,status:E,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:u,venue:t.venue??(typeof u=="string"?u:u.venue??u.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:ct(t.spender,"spender")},prepareHash:a,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:s,data:s,selector:s.length>=10?s.slice(0,10):null,value:ye(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:ye(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:ye(t.gasLimit??r.gasLimit,"gasLimit")},simulation:f,policyChecks:l,allowlistHits:h,assetDeltas:p,approvalDeltas:m,summary:S};return Ro(I)}import{readFileSync as Gc,readdirSync as Vc,existsSync as Kc}from"node:fs";import{dirname as Xc,join as Do}from"node:path";import{fileURLToPath as Yc}from"node:url";var Qc=Xc(Yc(import.meta.url)),Zc=Do(Qc,"descriptors"),eu=/^0x[0-9a-f]{8}/,tu=/^0x[0-9a-fA-F]{40}$/;function ru(e=Zc){if(!Kc(e))return[];let t=[];for(let r of Vc(e).filter(n=>n.endsWith(".json")).sort()){let n=Gc(Do(e,r),"utf8"),o;try{o=JSON.parse(n)}catch(i){throw new Error(`clear-sign descriptor ${r} is not valid JSON: ${i.message}`)}t.push({file:r,doc:o})}return t}function nu(e,{to:t=null,chainId:r=null}={},n=ru()){let o=String(e||"").toLowerCase(),i=eu.test(o)?o.slice(0,10):null;if(!i)return null;let a=t&&tu.test(String(t))?String(t).toLowerCase():null;for(let{file:u,doc:c}of n){let s=c?.display?.formats||{};for(let[d,l]of Object.entries(s)){if(String(l?.$selector||"").toLowerCase()!==i)continue;let f=c?.context?.contract?.deployments||[],p=f.length===0,m=f.some(h=>(r==null||Number(h.chainId)===Number(r))&&a&&String(h.address||"").toLowerCase()===a);if(p||m)return{file:u,signature:d,format:l,doc:c,selector:i,generic:p}}}return null}function Mo(e,t){let r=e.slice(t*64,t*64+64);return r.length===64?r:null}function ou(e,t){let r=Mo(e,t);return r?`0x${r.slice(24)}`:null}function Po(e,t){let r=Mo(e,t);return r?BigInt(`0x${r}`).toString():null}var iu=(1n<<256n)-1n;function Fo(e){if(e==null)return"unknown";let t=BigInt(e);return t>=iu/2n?"UNLIMITED":t.toString()}function qo(e,{to:t=null,chainId:r=null}={},n=void 0){let o=nu(e,{to:t,chainId:r},n);if(!o)return null;let i=String(e||"").toLowerCase(),a=i.slice(10),u=[],c=[];for(let s of o.format.fields||[]){if(s.visible==="never")continue;let d=s.$wordIndex,l=null;Number.isInteger(d)&&(l=s.format==="addressName"||s.format==="raw-address"?ou(a,d):s.format==="amount"||s.format==="tokenAmount"?Fo(Po(a,d)):Po(a,d)),l!=null&&(c.push({label:s.label,value:l}),u.push(`${s.label}: ${l}`))}if(J(i)){let s=null,d=null;try{s=he(i)}catch(l){let f=String(l?.message||l);if(/unlimited approvals are refused/i.test(f))d="ORACLE POLICY: unlimited approval \u2014 Oracle refuses to prepare this; bound the amount";else return{ok:!1,refused:`descriptor matched but reviewed decoder refused: ${f}`,intent:o.format.intent}}if(s){let l=c.find(m=>/spender/i.test(m.label))?.value?.toLowerCase();if(l&&s.spender&&l!==s.spender.toLowerCase())return{ok:!1,refused:"descriptor spender disagrees with reviewed decoder",intent:o.format.intent};let f=c.find(m=>/amount|allowance/i.test(m.label))?.value,p=Fo(s.amount);if(f!=null&&s.amount!=null&&String(f)!==p)return{ok:!1,refused:"descriptor amount disagrees with reviewed decoder",intent:o.format.intent}}return d&&u.push(d),{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:c,lines:u,...d?{policyNote:d}:{}}}return{ok:!0,intent:o.format.intent,signature:o.signature,selector:o.selector,descriptor:o.file,generic:o.generic,fields:c,lines:u}}var au=/^0x[0-9a-f]{40}$/;function At(e){let t=String(e??"").toLowerCase();return au.test(t)?t:null}function su(e,{token:t,owner:r}){if(!J(e))return[];let n;try{n=he(e)}catch{return[]}let o={token:At(n.token??t),spender:At(n.spender),owner:At(r),amount:n.amount};return o.token&&o.spender&&o.owner&&o.amount!=null?[o]:[]}function cu(e,t,r={}){let n=e?.version===1&&e?.surface?e:null,o=n?.surface||"evm";if(o!=="evm"&&o!=="evm-nft")return null;let i=n?.artifact||e||{},a=At(n?.owner??i.from),u=At(i.to??n?.destination),c=String(i.data??"0x").toLowerCase();if(!a||!u)return null;let s=[],d=r?.destinationAllowlist;if(Array.isArray(d)&&d.length){let l=d.map(f=>String(f).toLowerCase()).includes(u);s.push({name:"destination-allowlist",passed:l,reason:l?"destination is allowlisted":"destination is not on the allowlist"})}try{return _o({chainId:i.chainId,account:a,destination:u,calldata:c,value:i.value??0,prepareHash:t,route:n?.provider??n?.venue??o,decodedAction:n?.action??"transaction",...i.gasLimit==null?{}:{gasLimit:i.gasLimit},...s.length?{policyChecks:s}:{},approvalDeltas:su(c,{token:u,owner:a})})}catch{return null}}function jo(e,t,r={}){let n=cu(e,t,r);if(!n)return[];let o=[`REVIEW status=${n.status} action=${n.decodedAction??"transaction"} selector=${n.selector??"none"}`,`REVIEW route=${typeof n.route=="string"?n.route:n.venue??"n/a"} value=${n.value} signing=local custody=${n.custody}`];n.policyChecks.checks.length&&o.push(`REVIEW policy passed=${n.policyChecks.passed} failed=${n.policyChecks.failed}${n.policyChecks.failed?` reasons=${n.policyChecks.reasons.join("; ")}`:""}`);for(let i of n.approvalDeltas)o.push(`REVIEW APPROVAL token=${i.token} spender=${i.spender} amount=${i.amount} revokeLike=${i.revokeLike}`);n.assetDeltas==null&&o.push("REVIEW assetDeltas=unavailable (no simulated balance change supplied)"),n.status!=="READY"&&o.push("REVIEW status is not READY: these facts are decoded, not proven safe.");try{let i=e?.artifact||e||{},a=qo(String(i.data??"0x"),{to:i.to??null,chainId:i.chainId??null});if(a?.ok){o.push(`CLEAR-SIGN intent=${a.intent} [${a.descriptor}]`);for(let u of a.lines)o.push(`CLEAR-SIGN ${u}`)}else a&&a.refused&&o.push(`CLEAR-SIGN REFUSED: ${a.refused}`)}catch{}return o}import{Wallet as jr}from"ethers";import{base58 as Ur}from"@scure/base";import{ed25519 as Jo}from"@noble/curves/ed25519.js";import{NETWORK as Go,TEST_NETWORK as Vo,WIF as uu,p2wpkh as Uo}from"@scure/btc-signer";import{pubECDSA as lu}from"@scure/btc-signer/utils.js";var Vt=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},du=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},zo=e=>{let t=String(e||"").trim();try{let r=Buffer.from(Ur.decode(t));return Ur.encode(r)===t?r:null}catch{return null}},zr=e=>{if(!(e instanceof Uint8Array))throw new Error("sol: key bytes required");if(e.length!==32&&e.length!==64)throw new Error("sol: expected 32-byte private key material");let t=Buffer.from(e.subarray(0,32));if(e.length===64){let r=Buffer.from(e.subarray(32,64)),n=Buffer.from(Jo.getPublicKey(t));if(!r.equals(n))throw new Error("sol: supplied public key does not match seed")}return t},Wo=e=>!(e instanceof Uint8Array)||e.length!==32&&e.length!==64?null:Buffer.from(e.subarray(0,32)),Ee=(e,t)=>{if(t==="sol")return zr(e);if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)},fu=(e,t)=>{if(!Array.isArray(e))throw new Error(`${t}: expected byte array`);let r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>255)throw new Error(`${t}: expected integer bytes in 0..255`);r[n]=o}return Ee(r,t)};function Wr(e,t){let r=String(t||"").trim();if(e==="evm")return new jr(r).privateKey;if(e==="btc")for(let i of[Go,Vo])try{return Buffer.from(uu(i).decode(r))}catch{}if(e==="sol"){if(/^hex:/i.test(r)){let s=Vt(r.slice(4));if(!s)throw new Error("sol: invalid explicit hex private key");return Ee(s,"sol")}if(/^base58:/i.test(r)){let s=zo(r.slice(7));if(!Wo(s))throw new Error("sol: invalid explicit base58 private key");return zr(s)}if(/^0x/i.test(r)){let s=Vt(r);if(!s)throw new Error("sol: invalid explicit hex private key");return Ee(s,"sol")}let i=Vt(r),a=i&&(i.length===32||i.length===64)?Ee(i,"sol"):null,u=zo(r),c=Wo(u);if(a&&c&&!a.equals(c))throw new Error("sol: ambiguous private key format; prefix with hex: or base58:");if(c)return zr(u);if(i)return Ee(i,"sol")}let n=Vt(r);if(n)return e==="evm"?new jr(`0x${n.toString("hex")}`).privateKey:Ee(n,e);let o=du(r);if(o)return Ee(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return fu(i,e);let a=i.privateKey??i.secretKey??i.key;if(a)return Wr(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function Ho(e,t){if(e==="evm"){let r=new jr(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=Ee(t,"btc"),n=lu(r);return{kind:e,secret:r.toString("hex"),addresses:[Uo(n,Go).address,Uo(n,Vo).address]}}if(e==="sol"){let r=Ee(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[Ur.encode(Jo.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function Ko(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:Ho(t.kind||"evm",Wr(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Ho(i,Wr(i,n[i])));if(n.cex!==void 0){if(!n.cex||typeof n.cex!="object"||Array.isArray(n.cex))throw new Error("local-vault: cex credential records invalid");o.cex={};for(let[i,a]of Object.entries(n.cex)){if(!/^[A-Za-z0-9._-]{1,64}$/.test(i)||!a||typeof a!="object")throw new Error("local-vault: cex credential record invalid");if(!/^(?:binance|bybit|okx|coinbase)$/.test(a.venue)||!/^[A-Za-z0-9._-]{1,64}$/.test(a.accountId||""))throw new Error("local-vault: cex credential binding invalid");let u=(s,d=!0)=>{let l=a[s];if(!(!d&&l===void 0)){if(!Array.isArray(l)||l.length<4||l.some(f=>!Number.isInteger(f)||f<0||f>255))throw new Error("local-vault: cex credential bytes invalid");return Buffer.from(l)}},c=a.apiSecretEncoding;if(c!==(a.venue==="coinbase"?"base64":"raw"))throw new Error("local-vault: explicit cex secret encoding refused");o.cex[i]=Object.freeze({venue:a.venue,accountId:a.accountId,apiKeyBytes:u("apiKeyBytes"),apiSecretBytes:u("apiSecretBytes"),apiSecretEncoding:c,passphraseBytes:u("passphraseBytes",!1)})}if(!Object.keys(o.cex).length)throw new Error("local-vault: empty cex credential records refused");Object.freeze(o.cex)}if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function Hr(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}var pu=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),mu=Object.freeze(["binance","bybit","okx","coinbase"]),wu=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),hu=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),gu=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),lm=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),yu=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),dm=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),fm=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),pm=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),mm=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"});function Jr(e,t){let r=String(e??"");if(!/^\d+$/.test(r))throw new Error(`cex-policy: ${t} must be an integer string`);return BigInt(r)}function X(e,t,r){let n=String(e??"");if(!r.test(n))throw new Error(`cex-policy: bounded ${t} required`);return n}function Xo(e,t){let r=String(e??"");if(!/^(?:0|[1-9]\d{0,29})(?:\.\d{1,18})?$/.test(r))throw new Error(`cex-policy: positive decimal ${t} required`);let[n,o=""]=r.split("."),i=BigInt(`${n}${o}`);if(i<=0n)throw new Error(`cex-policy: positive decimal ${t} required`);return{text:r,numerator:i,scale:o.length}}function Eu(e,t){let r=e.numerator*t.numerator,n=10n**BigInt(e.scale+t.scale);return(r+n-1n)/n}function bu(e){return new Date(e).toISOString().slice(0,10)}function xu(e,t){let r=X(e.credentialRef,"credentialRef",/^[A-Za-z0-9._-]{1,64}$/),n=t.cexAccounts?.[r];if(!n||typeof n!="object")throw new Error("cex-policy: sealed account policy required");return{credentialRef:r,account:n}}function Kt(e={},t={},r=Date.now()){for(let R of Object.keys(e)){let j=R.toLowerCase();if(yu.some(ce=>ce.toLowerCase()===j))throw new Error(`cex-policy: envelope field ${R} forbidden`);if(!gu.includes(R))throw new Error(`cex-policy: envelope field ${R} not in allowlist`)}if(e.version!==1)throw new Error("cex-policy: version 1 required");if(e.surface!=="cex")throw new Error("cex-policy: surface cex required");let n=String(e.kind||"");if(!pu.includes(n))throw new Error(`cex-policy: kind ${n||"(none)"} refused`);let o=X(e.venue,"venue",/^[a-z0-9._-]{1,32}$/);if(!mu.includes(o)||!wu[o]||!hu[o])throw new Error(`cex-policy: venue ${o} unknown`);let{credentialRef:i,account:a}=xu(e,t);if(!Array.isArray(a.venues)||!a.venues.includes(o))throw new Error(`cex-policy: venue ${o} not allowlisted`);let u=X(e.symbol,"symbol",/^[A-Z0-9._/-]{1,32}$/);if(!Array.isArray(a.symbols)||!a.symbols.includes(u))throw new Error(`cex-policy: symbol ${u} not allowlisted`);let c=X(e.quote,"quote",/^[A-Z0-9._-]{1,24}$/);if(!a.symbolQuotes||typeof a.symbolQuotes!="object"||a.symbolQuotes[u]!==c)throw new Error("cex-policy: quote does not match sealed symbol policy");let s=X(a.accountId,"accountId",/^[A-Za-z0-9._-]{1,64}$/);if(!Array.isArray(a.allowedOperations)||!a.allowedOperations.includes(n))throw new Error("cex-policy: operation not in sealed allowlist");let d=X(e.base,"base",/^[A-Z0-9._-]{1,24}$/);if(a.base!==d||a.quote!==c)throw new Error("cex-policy: base/quote do not match sealed account policy");if(a.credentialRecordRef!==i)throw new Error("cex-policy: credential record reference mismatch");let l=a.filters?.[u];if(!l||typeof l.tickSize!="string"||typeof l.stepSize!="string"||typeof l.minNotional!="string")throw new Error("cex-policy: sealed symbol filters required");X(e.nonce,"nonce",/^[A-Za-z0-9._:-]{1,128}$/),X(e.grantId,"grantId",/^[A-Za-z0-9._:-]{1,128}$/),X(e.artifactHash,"artifactHash",/^[A-Za-z0-9._:-]{1,128}$/);let f=e.clientOrderId===void 0?void 0:X(e.clientOrderId,"clientOrderId",/^[A-Za-z0-9._-]{1,64}$/),p,m,h,g,w=0n,E=0n,b;if(n==="spot-limit-create"){if(p=X(e.side,"side",/^(?:buy|sell)$/),m=X(e.timeInForce,"timeInForce",/^GTC$/),h=Xo(e.baseSize,"baseSize"),g=Xo(e.limitPrice,"limitPrice"),!f)throw new Error("cex-policy: clientOrderId required");if(w=Jr(e.maxQuoteNotional,"maxQuoteNotional"),E=Eu(h,g),w<E)throw new Error("cex-policy: maxQuoteNotional understates baseSize times limitPrice")}else{for(let R of["side","baseSize","limitPrice","maxQuoteNotional","timeInForce"])if(e[R]!==void 0)throw new Error(`cex-policy: ${R} forbidden for cancel/status`);if(b=e.venueOrderId===void 0?void 0:X(e.venueOrderId,"venueOrderId",/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/),!b&&!f)throw new Error("cex-policy: exact prior order id required")}let S=Jr(a.perOrderQuoteCap,"sealed perOrderQuoteCap"),I=Jr(a.dailyGrossQuoteCap,"sealed dailyGrossQuoteCap");if(w>S)throw new Error("cex-policy: maxQuoteNotional exceeds sealed perOrderQuoteCap");if(w>I)throw new Error("cex-policy: maxQuoteNotional exceeds sealed dailyGrossQuoteCap");let T=Number(e.expiresAtMs);if(!Number.isSafeInteger(T)||T<=r||T-r>12e4)throw new Error("cex-policy: bounded expiry required");let v=`cex:${i}:${o}:${s}:${f||b}`,C=`cex:${i}:${s}:${o}:${c}:${bu(r)}`;return Object.freeze({kind:n,venue:o,symbol:u,base:d,quote:c,side:p,timeInForce:m,baseSize:h?.text,limitPrice:g?.text,clientOrderId:f,venueOrderId:b,filter:Object.freeze({...l}),accountId:s,credentialRef:i,tradeId:v,unit:C,notional:w.toString(),impliedNotional:E.toString()})}function Yo({envelope:e,paths:t,nowMs:r=Date.now()}){let n=Jt(t.policy,t.policyKey,{sequenceAnchorFile:t.policyAnchor}),o=Kt(e,n,r);return xt({file:t.ledger,keyFile:t.policyKey,anchorFile:t.ledgerAnchor,policyAnchorFile:t.policyAnchor,tradeId:o.tradeId,unit:o.unit,value:o.notional,notional:o.notional,policy:n,nowMs:r})}import D from"node:fs";import je from"node:path";import{createHmac as Su,randomBytes as Au,timingSafeEqual as vu}from"node:crypto";var Xt=(e,t)=>Su("sha256",e).update(JSON.stringify(t)).digest("hex"),Qo=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&vu(r,n)},Zo=e=>Buffer.from(N(e));function ei({file:e,keyFile:t,anchorFile:r}){if(!e||!t||!r)throw new Error("cex-state: protected paths required");if(je.dirname(je.resolve(e))===je.dirname(je.resolve(r)))throw new Error("cex-state: external rollback anchor required");let n=`${e}.lock`,o=(()=>{try{return D.readFileSync(`/proc/${process.pid}/stat`,"utf8").trim().split(/\s+/)[21]}catch{return null}})(),i=d=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,d),a=d=>{if(!Number.isSafeInteger(d.pid)||d.pid<1||typeof d.processStart!="string"||!d.processStart)return null;try{process.kill(d.pid,0)}catch(l){return l?.code==="ESRCH"?!1:null}try{return D.readFileSync(`/proc/${d.pid}/stat`,"utf8").trim().split(/\s+/)[21]===d.processStart}catch{return null}},u=d=>{D.mkdirSync(je.dirname(n),{recursive:!0,mode:448});let l=Au(16).toString("hex"),f=Date.now()+5e3,p=`${n}.${process.pid}.${l}.tmp`,m=JSON.stringify({version:1,pid:process.pid,processStart:o,token:l,createdAtMs:Date.now()})+`
|
|
8
|
+
`;for(;;)try{let h=D.openSync(p,"wx",384);try{D.writeFileSync(h,m),D.fsyncSync(h)}finally{D.closeSync(h)}try{D.linkSync(p,n)}finally{D.unlinkSync(p)}break}catch(h){try{D.existsSync(p)&&D.unlinkSync(p)}catch{}if(h?.code!=="EEXIST")throw new Error("cex-state: lock refused");let g;try{g=D.readFileSync(n,"utf8")}catch(b){if(b?.code==="ENOENT")continue;throw new Error("cex-state: corrupt lock refused")}let w;try{w=JSON.parse(g)}catch{throw new Error("cex-state: corrupt lock refused")}if(w?.version!==1||!/^[0-9a-f]{32}$/.test(w.token||"")||!Number.isSafeInteger(w.createdAtMs))throw new Error("cex-state: corrupt lock refused");if(a(w)===!1&&Date.now()-w.createdAtMs>3e4){try{D.unlinkSync(n)}catch{throw new Error("cex-state: stale lock recovery refused")}continue}if(Date.now()>=f)throw new Error("cex-state: lock busy");i(10)}try{return d()}finally{let h;try{h=JSON.parse(D.readFileSync(n,"utf8"))}catch{throw new Error("cex-state: lock ownership lost")}if(h.token!==l||h.pid!==process.pid||h.processStart!==o)throw new Error("cex-state: lock ownership lost");D.unlinkSync(n)}},c=()=>{let d=Zo(t);try{if(!D.existsSync(e)){if(D.existsSync(r))throw new Error("cex-state: rollback detected");return{version:1,sequence:0,orders:[]}}let l=JSON.parse(N(e));if(!Qo(l.mac,Xt(d,l.state)))throw new Error("cex-state: integrity failed");let f=JSON.parse(N(r));if(!Qo(f.mac,Xt(d,f.marker))||f.marker.sequence!==l.state.sequence||f.marker.stateMac!==l.mac)throw new Error("cex-state: rollback detected");return l.state}finally{d.fill(0)}},s=d=>{let l=Zo(t);try{let f={...d,sequence:d.sequence+1},p=Xt(l,f),m={version:1,sequence:f.sequence,stateMac:p};return D.mkdirSync(je.dirname(e),{recursive:!0,mode:448}),D.mkdirSync(je.dirname(r),{recursive:!0,mode:448}),se(r,JSON.stringify({marker:m,mac:Xt(l,m)})+`
|
|
9
9
|
`),se(e,JSON.stringify({state:f,mac:p})+`
|
|
10
|
-
`),f}finally{l.fill(0)}};return Object.freeze({getByTradeId(d){return u(()=>c().orders.find(l=>l.tradeId===d)||null)},prepare(d){return u(()=>{let l=c(),f=l.orders.find(m=>m.tradeId===d.tradeId||m.requestDigest===d.requestDigest);if(f)throw new Error(`cex-state: ${f.state} order requires status reconciliation; create not resent`);let p={...d,state:"prepared",preparedAtMs:d.nowMs};return s({...l,orders:[...l.orders,p]}),Object.freeze(p)})},transition(d,l,f,p={}){return u(()=>{let m=c(),h=m.orders.findIndex(w=>w.tradeId===d);if(h<0)throw new Error("cex-state: durable prior order required");if(![].concat(l).includes(m.orders[h].state))throw new Error(`cex-state: ${m.orders[h].state} status requires reconciliation`);let g={...m.orders[h],...p,state:f};return m.orders[h]=g,s(m),Object.freeze(g)})},requirePrior({venue:d,accountId:l,credentialRef:f,symbol:p,venueOrderId:m}){return u(()=>{let h=c().orders.find(g=>g.venue===d&&g.accountId===l&&g.credentialRef===f&&g.symbol===p&&g.venueOrderId===m);if(!h)throw new Error("cex-state: exact durable prior order required");return Object.freeze(h)})}})}import{createHash as gu}from"node:crypto";import{createHash as su}from"node:crypto";var Kr=Object.freeze({binance:Object.freeze({create:["POST","/api/v3/order"],cancel:["DELETE","/api/v3/order"],status:["GET","/api/v3/order"]}),bybit:Object.freeze({create:["POST","/v5/order/create"],cancel:["POST","/v5/order/cancel"],status:["GET","/v5/order/realtime"]}),okx:Object.freeze({create:["POST","/api/v5/trade/order"],cancel:["POST","/api/v5/trade/cancel-order"],status:["GET","/api/v5/trade/order"]}),coinbase:Object.freeze({create:["POST","/orders"],cancel:["DELETE","/orders/{order_id}"],status:["GET","/orders/{order_id}"]})}),vt=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),cu=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,uu=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/,Xo=(e,t)=>{let r=String(e??"");if(!cu.test(r))throw new Error(`cex: ${t} must be a decimal string`);let[n,o=""]=r.split(".");return{text:r,integer:BigInt(n+o),scale:o.length}};var Gr=(e,t)=>{let r=String(e??"");if(!uu.test(r))throw new Error(`cex: bounded ${t} required`);return r},Vr=e=>{if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Vr).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Vr(e[t])}`).join(",")}}`;throw new Error("cex: non-canonical request fact refused")};function lu(e){if(!e||!["create","cancel","status"].includes(e.operation))throw new Error("cex: operation refused");if(!/^[A-Z0-9._/-]{1,32}$/.test(String(e.symbol||"")))throw new Error("cex: symbol required");if(e.operation==="create"){if(!/^(?:buy|sell)$/.test(e.side)||e.timeInForce!==void 0&&e.timeInForce!=="GTC")throw new Error("cex: LIMIT GTC spot order required");Xo(e.baseSize,"baseSize"),Xo(e.limitPrice,"limitPrice"),Gr(e.clientOrderId,"clientOrderId")}else Gr(e.venueOrderId,"venueOrderId");return e}function du(e,t){let r=t.side==="buy"?"BUY":"SELL";if(e==="binance")return t.operation==="create"?{params:{symbol:t.symbol,side:r,type:"LIMIT",timeInForce:"GTC",quantity:t.baseSize,price:t.limitPrice,newClientOrderId:t.clientOrderId}}:{params:{symbol:t.symbol,orderId:t.venueOrderId}};if(e==="bybit"){let n=t.operation==="create"?{category:"spot",symbol:t.symbol,side:r==="BUY"?"Buy":"Sell",orderType:"Limit",qty:t.baseSize,price:t.limitPrice,timeInForce:"GTC",orderLinkId:t.clientOrderId,isLeverage:0}:{category:"spot",symbol:t.symbol,orderId:t.venueOrderId};return t.operation==="status"?{params:n}:{body:n}}if(e==="okx"){let n=t.operation==="create"?{instId:t.symbol,tdMode:"cash",clOrdId:t.clientOrderId,side:t.side,ordType:"limit",sz:t.baseSize,px:t.limitPrice}:{instId:t.symbol,ordId:t.venueOrderId};return t.operation==="status"?{params:n}:{body:n}}if(e==="coinbase")return{body:t.operation==="create"?{type:"limit",side:t.side,product_id:t.symbol,size:t.baseSize,price:t.limitPrice,time_in_force:"GTC",client_oid:t.clientOrderId}:void 0};throw new Error("cex: venue refused")}function Yo({venue:e,order:t,timestamp:r,recvWindow:n=5e3}){lu(t);let o=Kr[e]?.[t.operation];if(!o)throw new Error("cex: venue or operation refused");if(!Number.isSafeInteger(n)||n<1||n>5e3)throw new Error("cex: recvWindow refused");let i=String(r??"");if(!(e==="okx"?/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(i):e==="coinbase"?/^\d{10}(?:\.\d{1,3})?$/.test(i):/^\d{13}$/.test(i)))throw new Error("cex: timestamp refused");let[a,u]=o;u.includes("{order_id}")&&(u=u.replace("{order_id}",encodeURIComponent(Gr(t.venueOrderId,"venueOrderId"))));let c={venue:e,operation:t.operation,method:a,path:u,timestamp:i,recvWindow:n,...du(e,t)};return Object.freeze({...c,params:c.params&&Object.freeze(c.params),body:c.body&&Object.freeze(c.body),requestDigest:su("sha256").update(Vr(c)).digest("hex")})}import{createHmac as fu}from"node:crypto";var Yt=(e,t,r="hex")=>fu("sha256",e).update(t).digest(r),Qo=e=>new URLSearchParams(Object.entries(e||{})).toString(),pu=e=>e===void 0?"":JSON.stringify(e),Xr=(e,t)=>{if(!(Array.isArray(e)||e instanceof Uint8Array)||e.length<4||[...e].some(r=>!Number.isInteger(r)||r<0||r>255))throw new Error(`cex: invalid ${t}`);return Buffer.from(e)};function mu(e,t){let r=Xr(e.apiSecretBytes,"credential"),n=t==="coinbase"?"base64":"raw";if(e.apiSecretEncoding!==n)throw r.fill(0),new Error("cex: explicit secret encoding refused");if(n==="raw")return r;try{let o=r.toString("ascii");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o))throw new Error("base64");let i=Buffer.from(o,"base64");if(i.length<4||i.toString("base64")!==o)throw i.fill(0),new Error("base64");return i}finally{r.fill(0)}}var Ue=e=>Buffer.from(e).toString("utf8");function Zo(e,t){if(t?.venue!==e.venue)throw new Error("cex: credential venue mismatch");let r=Xr(t.apiKeyBytes,"credential"),n=mu(t,e.venue),o=t.passphraseBytes?Xr(t.passphraseBytes,"credential"):null;try{let i={accept:"application/json"},a=pu(e.body);a&&(i["content-type"]="application/json");let u=Qo(e.params),c=e.path;if(e.venue==="binance"){let s=Qo({...e.params,timestamp:e.timestamp,recvWindow:String(e.recvWindow)});u=`${s}&signature=${Yt(n,s)}`,i["X-MBX-APIKEY"]=Ue(r)}else if(e.venue==="bybit"){let s=e.method==="GET"?u:a;Object.assign(i,{"X-BAPI-API-KEY":Ue(r),"X-BAPI-TIMESTAMP":e.timestamp,"X-BAPI-RECV-WINDOW":String(e.recvWindow),"X-BAPI-SIGN":Yt(n,e.timestamp+Ue(r)+e.recvWindow+s)})}else if(e.venue==="okx"){let s=c+(u?`?${u}`:"");Object.assign(i,{"OK-ACCESS-KEY":Ue(r),"OK-ACCESS-SIGN":Yt(n,e.timestamp+e.method+s+a,"base64"),"OK-ACCESS-TIMESTAMP":e.timestamp,"OK-ACCESS-PASSPHRASE":Ue(o||Buffer.alloc(0))})}else Object.assign(i,{"CB-ACCESS-KEY":Ue(r),"CB-ACCESS-SIGN":Yt(n,e.timestamp+e.method+c+a,"base64"),"CB-ACCESS-TIMESTAMP":e.timestamp,"CB-ACCESS-PASSPHRASE":Ue(o||Buffer.alloc(0))});return{url:vt[e.venue]+c+(u?`?${u}`:""),method:e.method,headers:i,body:a||void 0}}finally{r.fill(0),n.fill(0),o?.fill(0)}}var ei=256*1024,wu=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/;function hu(e,t,r){if(!t.includes("{order_id}"))return r===t;let[n,o]=t.split("{order_id}");if(!r.startsWith(n)||!r.endsWith(o))return!1;let i=r.slice(n.length,r.length-o.length||void 0),a;try{a=decodeURIComponent(i)}catch{return!1}if(!wu.test(a)||encodeURIComponent(a)!==i)return!1;try{return new URL(r,e).pathname===r&&r===`${n}${i}${o}`}catch{return!1}}async function Yr(e,t){let r=Kr[e.venue]?.[e.operation],n=vt[e.venue];if(!r||!n||r[0]!==e.method||!hu(n,r[1],e.path))throw new Error("cex transport refused");let o=Zo(e,t),i=new AbortController,a=setTimeout(()=>i.abort(),5e3);try{let u=await fetch(o.url,{method:o.method,headers:o.headers,body:o.body,redirect:"manual",signal:i.signal});if(u.status<200||u.status>=300)throw new Error("http status");if(u.status>=300&&u.status<400)throw new Error("redirect");let c=new URL(u.url||o.url),s=new URL(vt[e.venue]);if(c.origin!==s.origin)throw new Error("origin");if(!String(u.headers.get("content-type")||"").toLowerCase().startsWith("application/json"))throw new Error("content type");let d=Number(u.headers.get("content-length"));if(Number.isFinite(d)&&d>ei)throw new Error("size");let l=new Uint8Array(await u.arrayBuffer());if(l.length>ei)throw new Error("size");let f;try{f=JSON.parse(new TextDecoder().decode(l))}catch{throw new Error("json")}return{statusCode:u.status,value:f,responseBodyBytes:l}}catch{throw new Error("cex transport refused")}finally{clearTimeout(a);for(let u of Object.values(o.headers));o.headers=null,o.body=void 0}}var yu=e=>gu("sha256").update(e).digest("hex"),Eu=(e,t)=>e==="okx"?new Date(t).toISOString():String(e==="coinbase"?t/1e3:t),Qr=e=>/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/.test(String(e||""))?String(e):null,It=e=>typeof e=="string"&&/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e)?e:null;var ti=e=>/^0(?:\.0+)?$/.test(String(e));function bu(e,t){if(!It(e)||!It(t))throw new Error("cex authoritative decimal refused");let[r,n=""]=e.split("."),[o,i=""]=t.split("."),a=n.length+i.length,u=BigInt(r+n)*BigInt(o+i);if(!a)return u.toString();let c=u.toString().padStart(a+1,"0");return`${c.slice(0,-a)}.${c.slice(-a)}`}function xu(e,t,r){let n,o,i;return e==="binance"&&t?.code===void 0?(n=t?.orderId,o=t?.symbol,i=t?.clientOrderId):e==="bybit"&&t?.retCode===0?(n=t?.result?.orderId,o=t?.result?.symbol,i=t?.result?.orderLinkId):e==="okx"&&t?.code==="0"&&t?.data?.length===1&&t.data[0]?.sCode==="0"?(n=t.data[0].ordId,o=t.data[0].instId,i=t.data[0].clOrdId):e==="coinbase"&&!t?.message&&(n=t?.id,o=t?.product_id,i=t?.client_oid),o!==void 0&&o!==r.symbol||i!==void 0&&i!==r.clientOrderId?null:Qr(n)}function Su(e,t,r){let n=null;return e==="binance"&&t&&typeof t=="object"&&t.code===void 0?n=t.orderId:e==="bybit"&&t?.retCode===0?n=t?.result?.orderId:e==="okx"&&t?.code==="0"&&t?.data?.length===1&&t.data[0]?.sCode==="0"?n=t.data[0].ordId:e==="coinbase"&&typeof t=="string"&&(n=t),Qr(n)===r.venueOrderId}function Au(e,t,r){let n=t,o,i,a,u,c;if(e==="binance"?(o=t?.orderId,i=t?.clientOrderId,a=t?.symbol,u={CANCELED:"cancelled",REJECTED:"rejected",FILLED:"filled",PARTIALLY_FILLED:"partial",NEW:"open",PENDING_CANCEL:"open"}[t?.status],c=t?.cummulativeQuoteQty):e==="bybit"&&t?.retCode===0&&t?.result?.list?.length===1?(n=t.result.list[0],o=n.orderId,i=n.orderLinkId,a=n.symbol,u={Cancelled:"cancelled",Rejected:"rejected",Filled:"filled",PartiallyFilled:"partial",New:"open"}[n.orderStatus],c=n.cumExecValue):e==="okx"&&t?.code==="0"&&t?.data?.length===1?(n=t.data[0],o=n.ordId,i=n.clOrdId,a=n.instId,u={canceled:"cancelled",filled:"filled",partially_filled:"partial",live:"open"}[n.state],It(n.accFillSz)&&It(n.avgPx)&&(ti(n.accFillSz)||!ti(n.avgPx))&&(c=bu(n.accFillSz,n.avgPx))):e==="coinbase"&&(o=t?.id,i=t?.client_oid,a=t?.product_id,u=t?.status==="done"?t?.done_reason==="canceled"?"cancelled":"filled":{rejected:"rejected",open:"open",pending:"open",active:"open"}[t?.status],c=t?.executed_value),Qr(o)!==r.venueOrderId||String(a||"")!==r.symbol||r.clientOrderId&&String(i||"")!==r.clientOrderId||!u||!It(c))throw new Error("cex authoritative status identity refused");return{status:u,filledQuote:c}}async function vu(e,t){let r=t?.nowMs?.()??Date.now(),n=t?.transport||Yr,o=t.credential(e.credentialRef);if(!o||o.accountId!==e.accountId||o.venue!==e.venue)throw new Error("cex: credential binding refused");let i=e.order.operation!=="create"?e.store.requirePrior({...e,...e.order}):null,a=i?.tradeId||e.tradeId,u=Yo({venue:e.venue,order:e.order,timestamp:Eu(e.venue,r),recvWindow:5e3}),c;e.order.operation==="create"?c=e.store.prepare({tradeId:e.tradeId,venue:e.venue,accountId:e.accountId,credentialRef:e.credentialRef,symbol:e.order.symbol,clientOrderId:e.order.clientOrderId,reservedNotional:e.reservedNotional,requestDigest:u.requestDigest,nowMs:r}):c=e.store.transition(a,["open","uncertain","sent","cancel-pending","settlement-pending"],"prepared",{operation:e.order.operation,requestDigest:u.requestDigest,nowMs:r}),e.store.transition(a,"prepared","sent",{sentAtMs:r});let s;try{s=await n(u,o)}catch{throw e.store.transition(a,"sent","uncertain",{uncertainAtMs:r}),new Error("cex transport refused; order is uncertain and requires status reconciliation")}let d=yu(s.responseBodyBytes);if(e.order.operation==="create"){let p=xu(e.venue,s.value,e.order);if(!p)throw e.store.transition(a,"sent","uncertain",{responseDigest:d}),new Error("cex response refused; order is uncertain and requires status reconciliation");return e.store.transition(a,"sent","open",{venueOrderId:p,responseDigest:d,openedAtMs:r})}if(e.order.operation==="cancel")return e.store.transition(a,"sent",Su(e.venue,s.value,i)?"cancel-pending":"uncertain",{responseDigest:d,observedAtMs:r});let l;try{l=Au(e.venue,s.value,i)}catch{return e.store.transition(a,"sent","uncertain",{responseDigest:d,observedAtMs:r})}let f=["cancelled","rejected","filled"].includes(l.status);if(f||l.status==="partial"){e.store.transition(a,"sent","settlement-pending",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote});let p=f&&(l.status==="cancelled"||l.status==="rejected")&&/^0(?:\.0+)?$/.test(l.filledQuote)?"release":"commit";return await t.settleLedger({tradeId:i.tradeId,filledQuote:l.filledQuote,disposition:p}),e.store.transition(a,"settlement-pending","terminal",{settledAtMs:r})}return e.store.transition(a,"sent","open",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote})}function ri(e){if(!e||typeof e.credential!="function"||typeof e.settleLedger!="function")throw new Error("cex: sealed runtime dependencies required");let t=Object.freeze({credential:e.credential,transport:e.transport||Yr,nowMs:e.nowMs||Date.now,settleLedger:e.settleLedger});return Object.freeze({execute:r=>vu(r,t)})}import{createHash as Iu,createHmac as ni,randomBytes as ku,timingSafeEqual as Tu}from"node:crypto";var oi="oracle-local-signer-cex-owner-allow-v1",ut=e=>/^(?:0|[1-9]\d{0,19})$/.test(String(e||""))?String(e):null,ii=e=>JSON.stringify(e),Ou=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Tu(r,n)};function ai({keyFile:e,approvedTelegramOwners:t,nowMs:r=Date.now}={}){if(!e)throw new Error("cex owner proof: signer policy key required");let n=new Set((t||[]).map(ut).filter(Boolean));if(!n.size)throw new Error("cex owner proof: approved owner context required");let o=new Set,i=u=>{let c=Buffer.from(N(e));try{return u(c)}finally{c.fill(0)}},a=i(u=>Iu("sha256").update("cex-owner-instance\0").update(u).digest("hex"));return Object.freeze({mint({digest:u,senderId:c,chatId:s,platform:d,ttlMs:l=15e3}={}){let f=ut(c),p=ut(s),m=r();if(d!=="telegram"||!f||p!==f||!n.has(f))throw new Error("cex owner proof: exact Telegram owner DM required");if(!/^[0-9a-f]{64}$/.test(String(u||""))||!Number.isSafeInteger(l)||l<1||l>3e4)throw new Error("cex owner proof: binding refused");let h={version:1,decision:"Allow",digest:u,ownerSenderId:f,telegramChatId:p,audience:oi,instance:a,nonce:ku(16).toString("hex"),issuedAtMs:m,expiresAtMs:m+l},g=i(w=>ni("sha256",w).update(ii(h)).digest("hex"));return{claims:h,mac:g}},verify(u,{digest:c}={}){let s=u?.claims,d=r();if(!s||s.version!==1||s.decision!=="Allow"||s.digest!==c||s.audience!==oi||s.instance!==a||!/^[0-9a-f]{32}$/.test(s.nonce||"")||ut(s.ownerSenderId)!==ut(s.telegramChatId)||!n.has(ut(s.ownerSenderId))||!Number.isSafeInteger(s.issuedAtMs)||!Number.isSafeInteger(s.expiresAtMs)||s.expiresAtMs<=d||s.issuedAtMs>d||s.expiresAtMs-s.issuedAtMs>3e4||o.has(s.nonce))return!1;let l=i(f=>ni("sha256",f).update(ii(s)).digest("hex"));return Ou(u.mac,l)?(o.add(s.nonce),!0):!1}})}var me=new rn(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),ci=new rn(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),en=new rn(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function _u(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||X.join(process.env.XDG_STATE_HOME||X.join(Cu.homedir(),".local","state"),"oracle"),r=Nu("sha256").update(X.resolve(e)).digest("hex").slice(0,16);return{vault:X.join(e,"vault.json"),policy:X.join(e,"signer-policy.json"),policyKey:X.join(e,"policy-integrity-key"),policyAnchor:X.join(t,`signer-policy-${r}.high-water`),ledger:X.join(e,"signer-ledger.json"),ledgerAnchor:X.join(t,`signer-ledger-${r}.high-water`),cexOrders:X.join(e,"cex-orders.json"),cexOrdersAnchor:X.join(t,`cex-orders-${r}.high-water`),token:X.join(e,"signer-token"),lock:X.join(t,`signer-${r}.lock`)}}function Fu(e){try{return N(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=Lu(32).toString("hex");return se(e,t+`
|
|
11
|
-
`),t}function tn(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 ui(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function M(e,t){return e.surfaces.includes(t)}function pe(e,t){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`signer: invalid ${t}`);return r}function li(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function Du(e,t){let r=e?.anvilQuote;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("signer: exact prepared Anvil quote is required");if(!e?.artifact?.anvilQuote||JSON.stringify(e.artifact.anvilQuote)!==JSON.stringify(r))throw new Error("signer: exact prepared Anvil quote artifact mismatch");return Object.freeze(t==="buy"?{totalCostRaw:BigInt(r.totalCostRaw).toString(),baseCostRaw:BigInt(r.baseCostRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString(),available:r.available===!0}:{netPayoutRaw:BigInt(r.netPayoutRaw).toString(),grossPayoutRaw:BigInt(r.grossPayoutRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString()})}function Mu(e,t,r){if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("signer: exact prepared Anvil quote confirmation required");let n=e.artifact,o=t==="buy"?[r.totalCostRaw,e.maxPaymentTokenAmountRaw,n?.maxPaymentTokenAmountRaw,e.exactQuoteTotalCostRaw,n?.exactQuoteTotalCostRaw,e.preconditions?.confirmedTotalCostRaw]:[r.netPayoutRaw,e.minPayoutRaw,n?.minPayoutRaw,e.exactQuoteNetPayoutRaw,n?.exactQuoteNetPayoutRaw,e.preconditions?.confirmedNetPayoutRaw],i;try{i=BigInt(o[0]);for(let s of o.slice(1))if(BigInt(s)!==i)throw new Error("mismatch")}catch{throw new Error(`signer: exact Anvil ${t} settlement limit mismatch`)}let a=n?.transactions;if(!Array.isArray(a)||a.length!==1)throw new Error("signer: exact Anvil action transaction required");let u=t==="buy"?"buySpecificNFT":"sellNFT",c;try{if(c=me.decodeFunctionData(u,a[0].data),me.encodeFunctionData(u,[c[0],c[1]]).toLowerCase()!==String(a[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${t} calldata required`)}if(BigInt(c[0])!==BigInt(e.tokenId)||BigInt(c[1])!==i)throw new Error(`signer: exact Anvil ${t} calldata limit mismatch`);return i}async function Ee(e,t,r,n,o,i=[]){let a=await e.send("eth_call",[{to:t,data:r.encodeFunctionData(n,i)},o]);return r.decodeFunctionResult(n,a)[0]}async function qu(e,t,r,{nowMs:n=Date.now(),signerAddress:o}={}){if(t?.surface!=="evm-nft"||String(t?.provider).toLowerCase()!=="anvil-nft")return null;if(!e||typeof e.send!="function")throw new Error("signer: trusted RPC cannot attest Anvil market");let i=pe(t.destination,"Anvil market"),a=pe(t.contract,"Anvil collection"),u=pe(t.paymentToken,"Anvil payment token"),c=BigInt(t.nativeSwapFeeWei),s=Number(t.paymentTokenDecimals),d=pe(o,"Anvil signer identity"),l=pe(t.owner,"Anvil envelope owner");if(d!==l)throw new Error("signer: Anvil signer identity mismatch");let f=BigInt(t.tokenId);if(f<0n)throw new Error("signer: invalid Anvil tokenId");let p=String(t.nftAction||"").toLowerCase();if(p!=="buy"&&p!=="sell")throw new Error("signer: unsupported Anvil NFT action");let m=Du(t,p),h=Mu(t,p,m),g=t.anvilAttestation;if(!g||typeof g!="object"||Number(g.snapshotExpiresAtMs)<=Number(n))throw new Error("signer: fresh provider Anvil attestation required");let w=String(li(r.anvilRuntimeCodeHashes,i)||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(w)||w!==String(g.runtimeCodeHash||"").toLowerCase())throw new Error("signer: Anvil runtime is not reviewed by policy");let E=li(r.nftPaymentTokenCaps,u);if(!E||Number(E.decimals)!==s)throw new Error("signer: Anvil payment token decimals are not reviewed by policy");let b=String(await e.send("eth_chainId",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(b)||BigInt(b)!==4663n)throw new Error("signer: trusted RPC Anvil chain mismatch");let S=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(S))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let I=BigInt(S),T=await e.send("eth_getBlockByNumber",[S,!1]),v=String(T?.hash||"").toLowerCase();if(String(T?.number||"").toLowerCase()!==S||!/^0x[0-9a-f]{64}$/.test(v))throw new Error("signer: trusted RPC returned an invalid Anvil block attestation");let C=Object.freeze({blockHash:v,requireCanonical:!0}),R=String(await e.send("eth_getCode",[i,C])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(R)||R==="0x")throw new Error("signer: Anvil market runtime is empty");let j=Ru(R).toLowerCase();if(j!==w)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[ce,lt,tr]=await Promise.all([Ee(e,i,me,"collection",C),Ee(e,i,me,"token",C),Ee(e,i,me,"robinhoodSwapFeeWei",C)]),Oe=pe(ce,"live Anvil collection"),Ce=pe(lt,"live Anvil payment token"),kt=BigInt(tr).toString();if(Oe!==a)throw new Error("signer: live Anvil collection mismatch");if(Ce!==u)throw new Error("signer: live Anvil payment token mismatch");if(kt!==c.toString())throw new Error("signer: live Anvil native swap fee mismatch");let ze=Number(await Ee(e,Ce,ci,"decimals",C));if(!Number.isSafeInteger(ze)||ze!==s)throw new Error("signer: live Anvil payment token decimals mismatch");let Ne=pe(await Ee(e,Oe,en,"ownerOf",C,[f]),"live Anvil token owner"),We=null,Le=null,He=null,Je=null,P;if(p==="buy"){let[Ge,y,A]=await Promise.all([Ee(e,i,me,"inventory",C,[f]),Ee(e,Ce,ci,"allowance",C,[d,i]),e.send("eth_call",[{to:i,data:me.encodeFunctionData("quoteSpecificBuy",[f])},C])]);We=!!Ge,Le=BigInt(y).toString();let x=me.decodeFunctionResult("quoteSpecificBuy",A);if(P=Object.freeze({totalCostRaw:BigInt(x[0]).toString(),baseCostRaw:BigInt(x[1]).toString(),feeRaw:BigInt(x[2]).toString(),protocolFeeRaw:BigInt(x[3]).toString(),available:!!x[4]}),JSON.stringify(P)!==JSON.stringify(m))throw new Error("signer: exact Anvil buy quote changed after preparation");if(Ne!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!We)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt(Le)!==BigInt(t.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt(Le)<h)throw new Error("signer: live Anvil ERC20 allowance is insufficient");if(!P.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(P.totalCostRaw)!==h)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(P.totalCostRaw)!==BigInt(P.baseCostRaw)+BigInt(P.feeRaw)+BigInt(P.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[Ge,y,A]=await Promise.all([Ee(e,Oe,en,"getApproved",C,[f]),Ee(e,Oe,en,"isApprovedForAll",C,[d,i]),e.send("eth_call",[{to:i,data:me.encodeFunctionData("quoteSellNFT")},C])]);He=pe(Ge,"live Anvil token approval"),Je=!!y;let x=me.decodeFunctionResult("quoteSellNFT",A);if(P=Object.freeze({netPayoutRaw:BigInt(x[0]).toString(),grossPayoutRaw:BigInt(x[1]).toString(),feeRaw:BigInt(x[2]).toString(),protocolFeeRaw:BigInt(x[3]).toString()}),JSON.stringify(P)!==JSON.stringify(m))throw new Error("signer: exact Anvil sell quote changed after preparation");if(Ne!==d)throw new Error("signer: exact Anvil token owner does not match signer");if(He!==i&&!Je)throw new Error("signer: live Anvil NFT approval is insufficient");if(He!==pe(t.preconditions?.approvedAddress,"prepared Anvil token approval")||Je!==!!t.preconditions?.approvedForAll)throw new Error("signer: live Anvil NFT approval changed after preparation");if(BigInt(P.netPayoutRaw)!==h)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(P.netPayoutRaw)+BigInt(P.feeRaw)+BigInt(P.protocolFeeRaw)!==BigInt(P.grossPayoutRaw))throw new Error("signer: exact Anvil sell quote fee arithmetic mismatch")}return Object.freeze({source:"local-signer-trusted-rpc",chainId:4663,market:i,collection:Oe,paymentToken:Ce,paymentTokenDecimals:ze,nativeSwapFeeWei:kt,signerAddress:d,nftAction:p,tokenId:f.toString(),tokenOwner:Ne,inventoryMember:We,allowanceRaw:Le,approvedAddress:He,approvedForAll:Je,quote:P,blockNumber:I.toString(),blockHash:v,runtimeCodeHash:j,verifiedAtMs:Number(n)})}function di(e,t,r="execution"){if(!e||!t)throw new Error("signer: complete Anvil revalidation evidence required");for(let n of["runtimeCodeHash","market","collection","paymentToken","paymentTokenDecimals","nativeSwapFeeWei","signerAddress","nftAction","tokenId","tokenOwner","inventoryMember","allowanceRaw","approvedAddress","approvedForAll"])if(String(t[n]).toLowerCase()!==String(e[n]).toLowerCase())throw new Error(`signer: Anvil ${n} changed after simulation at ${r}`);if(JSON.stringify(t.quote)!==JSON.stringify(e.quote))throw new Error(`signer: Anvil quote changed after simulation at ${r}`);return!0}function ju(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:a}={}){let u=Bu(new URL("./anvil-attestation-worker.mjs",import.meta.url)),c={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},s;try{s=$u(process.execPath,[u],{input:JSON.stringify({rpcUrl:e,chainId:t,envelope:r,policy:c,nowMs:Number(o),signerAddress:a}),encoding:"utf8",timeout:i,maxBuffer:64e3,env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_OPTIONS:""},stdio:["pipe","pipe","pipe"]})}catch{throw new Error("signer: fresh independent Anvil attestation failed before reservation")}let d;try{d=JSON.parse(s)}catch{throw new Error("signer: invalid Anvil reservation attestation result")}if(!d||d.source!=="local-signer-trusted-rpc"||!/^0x[0-9a-f]{64}$/.test(String(d.blockHash||"")))throw new Error("signer: invalid Anvil reservation attestation result");return Object.freeze(d)}function Uu(e,t,r,n=null){let o=e?.version===1&&e?.surface?e:null,i=o?.artifact||e||{},a=[`surface=${o?.surface||"evm"} action=${o?.action||"evm"}`,`chain=${i.chainId??i.network??i.cluster??"n/a"} owner=${o?.owner||i.from||"n/a"}`,`to=${i.to||o?.destination||"n/a"} calldata=${String(i.data||"0x")} value=${i.value??"n/a"}`,`gas=${i.gasLimit??"n/a"} maxFeePerGas=${i.maxFeePerGas??i.gasPrice??"n/a"} maxPriorityFeePerGas=${i.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${i.l1FeeWei??"n/a"} operatorFeeWei=${i.operatorFeeWei??"n/a"}`,`nonce=${i.nonce??"n/a"} type=${i.type??"n/a"} accessList=${Array.isArray(i.accessList)?i.accessList.length:0}`,`slippageBps=${o?.slippageBps??i.slippageBps??"n/a"} expiresAtMs=${o?.expiresAtMs??i.expiresAtMs??"n/a"}`],u=(s,d)=>{if(a.push(`LEG ${d} chain=${s.chainId??"n/a"} from=${s.from??"n/a"} to=${s.to??"n/a"}`),a.push(`LEG ${d} calldata=${String(s.data||"0x")} value=${s.value??"n/a"}`),a.push(`LEG ${d} gas=${s.gasLimit??"n/a"} maxFeePerGas=${s.maxFeePerGas??s.gasPrice??"n/a"} maxPriorityFeePerGas=${s.maxPriorityFeePerGas??"n/a"}`),a.push(`LEG ${d} l1FeeWei=${s.l1FeeWei??"n/a"} operatorFeeWei=${s.operatorFeeWei??"n/a"} nonce=${s.nonce??"n/a"} type=${s.type??"n/a"}`),Q(String(s.data||"0x")))try{let l=Be(String(s.data||"0x"));a.push(`LEG ${d} APPROVAL token=${l.token||s.to||"n/a"} spender=${l.spender} amount=${l.amount}`)}catch{a.push(`LEG ${d} APPROVAL spender=undecodable amount=undecodable`)}},c=String(i.data||"0x");if(Q(c))try{let s=Be(c);a.push(`APPROVAL token=${s.token||i.to||"n/a"} spender=${s.spender} amount=${s.amount}`)}catch{a.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(i.transactions)&&(a.push(`batchLegs=${i.transactions.length}`),i.transactions.forEach((s,d)=>u(s,d))),o?.surface==="btc"){let s=sr(o,r);a.push(`amount=${s.value} sats fee=${s.fee} sats outputs=${s.outputs.join(",")}`)}if(o?.surface==="sol"){let s=pr(o,r);a.push(`amount=${s.value} lamports fee=${s.fee} lamports programs=${s.programs.join(",")}`)}if(o?.surface==="hl"){let s=Ae(o,r);a.push(`hlKind=${s.kind} actionType=${s.actionType} coin=${s.coin||"n/a"} amount=${s.amount} notionalUsd=${s.notional} submitTo=${s.submitTo}`)}if(o?.surface==="poly"){let s=ve(o,r);a.push(`polyKind=${s.kind} tokenId=${s.tokenId} side=${s.side} price=${s.price} quantity=${s.quantity} notionalUsdc=${s.notionalUsdc} submitTo=${s.submitTo}`)}if(o?.surface==="evm-nft"&&o?.provider==="anvil-nft"&&(a.push(`anvilAction=${o.nftAction} collection=${o.contract} tokenId=${o.tokenId} market=${o.destination}`),a.push(`paymentToken=${o.paymentToken} paymentTokenDecimals=${o.paymentTokenDecimals} maxPaymentTokenAmountRaw=${o.maxPaymentTokenAmountRaw??"n/a"} minPayoutRaw=${o.minPayoutRaw??"n/a"} nativeSwapFeeWei=${o.nativeSwapFeeWei}`),n&&(a.push(`SIGNER VERIFIED block=${n.blockNumber} blockHash=${n.blockHash} runtimeCodeHash=${n.runtimeCodeHash} signer=${n.signerAddress} collection=${n.collection} paymentToken=${n.paymentToken} paymentTokenDecimals=${n.paymentTokenDecimals} nativeSwapFeeWei=${n.nativeSwapFeeWei}`),a.push(`SIGNER DYNAMIC tokenId=${n.tokenId} owner=${n.tokenOwner} inventory=${n.inventoryMember} allowanceRaw=${n.allowanceRaw} approved=${n.approvedAddress} approvedForAll=${n.approvedForAll} quote=${JSON.stringify(n.quote)}`))),o?.surface==="lighter"){let s=Ie(o,r);a.push(`lighterKind=${s.kind} actionType=${s.actionType} market=${s.symbol} amount=${s.amount} submitTo=${s.submitTo}`)}return`
|
|
10
|
+
`),f}finally{l.fill(0)}};return Object.freeze({getByTradeId(d){return u(()=>c().orders.find(l=>l.tradeId===d)||null)},prepare(d){return u(()=>{let l=c(),f=l.orders.find(m=>m.tradeId===d.tradeId||m.requestDigest===d.requestDigest);if(f)throw new Error(`cex-state: ${f.state} order requires status reconciliation; create not resent`);let p={...d,state:"prepared",preparedAtMs:d.nowMs};return s({...l,orders:[...l.orders,p]}),Object.freeze(p)})},transition(d,l,f,p={}){return u(()=>{let m=c(),h=m.orders.findIndex(w=>w.tradeId===d);if(h<0)throw new Error("cex-state: durable prior order required");if(![].concat(l).includes(m.orders[h].state))throw new Error(`cex-state: ${m.orders[h].state} status requires reconciliation`);let g={...m.orders[h],...p,state:f};return m.orders[h]=g,s(m),Object.freeze(g)})},requirePrior({venue:d,accountId:l,credentialRef:f,symbol:p,venueOrderId:m}){return u(()=>{let h=c().orders.find(g=>g.venue===d&&g.accountId===l&&g.credentialRef===f&&g.symbol===p&&g.venueOrderId===m);if(!h)throw new Error("cex-state: exact durable prior order required");return Object.freeze(h)})}})}import{createHash as _u}from"node:crypto";import{createHash as Iu}from"node:crypto";var Kr=Object.freeze({binance:Object.freeze({create:["POST","/api/v3/order"],cancel:["DELETE","/api/v3/order"],status:["GET","/api/v3/order"]}),bybit:Object.freeze({create:["POST","/v5/order/create"],cancel:["POST","/v5/order/cancel"],status:["GET","/v5/order/realtime"]}),okx:Object.freeze({create:["POST","/api/v5/trade/order"],cancel:["POST","/api/v5/trade/cancel-order"],status:["GET","/api/v5/trade/order"]}),coinbase:Object.freeze({create:["POST","/orders"],cancel:["DELETE","/orders/{order_id}"],status:["GET","/orders/{order_id}"]})}),vt=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),ku=/^(?:0|[1-9]\d*)(?:\.\d+)?$/,Tu=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/,ti=(e,t)=>{let r=String(e??"");if(!ku.test(r))throw new Error(`cex: ${t} must be a decimal string`);let[n,o=""]=r.split(".");return{text:r,integer:BigInt(n+o),scale:o.length}};var Gr=(e,t)=>{let r=String(e??"");if(!Tu.test(r))throw new Error(`cex: bounded ${t} required`);return r},Vr=e=>{if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Vr).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${Vr(e[t])}`).join(",")}}`;throw new Error("cex: non-canonical request fact refused")};function Ou(e){if(!e||!["create","cancel","status"].includes(e.operation))throw new Error("cex: operation refused");if(!/^[A-Z0-9._/-]{1,32}$/.test(String(e.symbol||"")))throw new Error("cex: symbol required");if(e.operation==="create"){if(!/^(?:buy|sell)$/.test(e.side)||e.timeInForce!==void 0&&e.timeInForce!=="GTC")throw new Error("cex: LIMIT GTC spot order required");ti(e.baseSize,"baseSize"),ti(e.limitPrice,"limitPrice"),Gr(e.clientOrderId,"clientOrderId")}else Gr(e.venueOrderId,"venueOrderId");return e}function Cu(e,t){let r=t.side==="buy"?"BUY":"SELL";if(e==="binance")return t.operation==="create"?{params:{symbol:t.symbol,side:r,type:"LIMIT",timeInForce:"GTC",quantity:t.baseSize,price:t.limitPrice,newClientOrderId:t.clientOrderId}}:{params:{symbol:t.symbol,orderId:t.venueOrderId}};if(e==="bybit"){let n=t.operation==="create"?{category:"spot",symbol:t.symbol,side:r==="BUY"?"Buy":"Sell",orderType:"Limit",qty:t.baseSize,price:t.limitPrice,timeInForce:"GTC",orderLinkId:t.clientOrderId,isLeverage:0}:{category:"spot",symbol:t.symbol,orderId:t.venueOrderId};return t.operation==="status"?{params:n}:{body:n}}if(e==="okx"){let n=t.operation==="create"?{instId:t.symbol,tdMode:"cash",clOrdId:t.clientOrderId,side:t.side,ordType:"limit",sz:t.baseSize,px:t.limitPrice}:{instId:t.symbol,ordId:t.venueOrderId};return t.operation==="status"?{params:n}:{body:n}}if(e==="coinbase")return{body:t.operation==="create"?{type:"limit",side:t.side,product_id:t.symbol,size:t.baseSize,price:t.limitPrice,time_in_force:"GTC",client_oid:t.clientOrderId}:void 0};throw new Error("cex: venue refused")}function ri({venue:e,order:t,timestamp:r,recvWindow:n=5e3}){Ou(t);let o=Kr[e]?.[t.operation];if(!o)throw new Error("cex: venue or operation refused");if(!Number.isSafeInteger(n)||n<1||n>5e3)throw new Error("cex: recvWindow refused");let i=String(r??"");if(!(e==="okx"?/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(i):e==="coinbase"?/^\d{10}(?:\.\d{1,3})?$/.test(i):/^\d{13}$/.test(i)))throw new Error("cex: timestamp refused");let[a,u]=o;u.includes("{order_id}")&&(u=u.replace("{order_id}",encodeURIComponent(Gr(t.venueOrderId,"venueOrderId"))));let c={venue:e,operation:t.operation,method:a,path:u,timestamp:i,recvWindow:n,...Cu(e,t)};return Object.freeze({...c,params:c.params&&Object.freeze(c.params),body:c.body&&Object.freeze(c.body),requestDigest:Iu("sha256").update(Vr(c)).digest("hex")})}import{createHmac as Nu}from"node:crypto";var Yt=(e,t,r="hex")=>Nu("sha256",e).update(t).digest(r),ni=e=>new URLSearchParams(Object.entries(e||{})).toString(),Lu=e=>e===void 0?"":JSON.stringify(e),Xr=(e,t)=>{if(!(Array.isArray(e)||e instanceof Uint8Array)||e.length<4||[...e].some(r=>!Number.isInteger(r)||r<0||r>255))throw new Error(`cex: invalid ${t}`);return Buffer.from(e)};function $u(e,t){let r=Xr(e.apiSecretBytes,"credential"),n=t==="coinbase"?"base64":"raw";if(e.apiSecretEncoding!==n)throw r.fill(0),new Error("cex: explicit secret encoding refused");if(n==="raw")return r;try{let o=r.toString("ascii");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o))throw new Error("base64");let i=Buffer.from(o,"base64");if(i.length<4||i.toString("base64")!==o)throw i.fill(0),new Error("base64");return i}finally{r.fill(0)}}var Ue=e=>Buffer.from(e).toString("utf8");function oi(e,t){if(t?.venue!==e.venue)throw new Error("cex: credential venue mismatch");let r=Xr(t.apiKeyBytes,"credential"),n=$u(t,e.venue),o=t.passphraseBytes?Xr(t.passphraseBytes,"credential"):null;try{let i={accept:"application/json"},a=Lu(e.body);a&&(i["content-type"]="application/json");let u=ni(e.params),c=e.path;if(e.venue==="binance"){let s=ni({...e.params,timestamp:e.timestamp,recvWindow:String(e.recvWindow)});u=`${s}&signature=${Yt(n,s)}`,i["X-MBX-APIKEY"]=Ue(r)}else if(e.venue==="bybit"){let s=e.method==="GET"?u:a;Object.assign(i,{"X-BAPI-API-KEY":Ue(r),"X-BAPI-TIMESTAMP":e.timestamp,"X-BAPI-RECV-WINDOW":String(e.recvWindow),"X-BAPI-SIGN":Yt(n,e.timestamp+Ue(r)+e.recvWindow+s)})}else if(e.venue==="okx"){let s=c+(u?`?${u}`:"");Object.assign(i,{"OK-ACCESS-KEY":Ue(r),"OK-ACCESS-SIGN":Yt(n,e.timestamp+e.method+s+a,"base64"),"OK-ACCESS-TIMESTAMP":e.timestamp,"OK-ACCESS-PASSPHRASE":Ue(o||Buffer.alloc(0))})}else Object.assign(i,{"CB-ACCESS-KEY":Ue(r),"CB-ACCESS-SIGN":Yt(n,e.timestamp+e.method+c+a,"base64"),"CB-ACCESS-TIMESTAMP":e.timestamp,"CB-ACCESS-PASSPHRASE":Ue(o||Buffer.alloc(0))});return{url:vt[e.venue]+c+(u?`?${u}`:""),method:e.method,headers:i,body:a||void 0}}finally{r.fill(0),n.fill(0),o?.fill(0)}}var ii=256*1024,Bu=/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/;function Ru(e,t,r){if(!t.includes("{order_id}"))return r===t;let[n,o]=t.split("{order_id}");if(!r.startsWith(n)||!r.endsWith(o))return!1;let i=r.slice(n.length,r.length-o.length||void 0),a;try{a=decodeURIComponent(i)}catch{return!1}if(!Bu.test(a)||encodeURIComponent(a)!==i)return!1;try{return new URL(r,e).pathname===r&&r===`${n}${i}${o}`}catch{return!1}}async function Yr(e,t){let r=Kr[e.venue]?.[e.operation],n=vt[e.venue];if(!r||!n||r[0]!==e.method||!Ru(n,r[1],e.path))throw new Error("cex transport refused");let o=oi(e,t),i=new AbortController,a=setTimeout(()=>i.abort(),5e3);try{let u=await fetch(o.url,{method:o.method,headers:o.headers,body:o.body,redirect:"manual",signal:i.signal});if(u.status<200||u.status>=300)throw new Error("http status");if(u.status>=300&&u.status<400)throw new Error("redirect");let c=new URL(u.url||o.url),s=new URL(vt[e.venue]);if(c.origin!==s.origin)throw new Error("origin");if(!String(u.headers.get("content-type")||"").toLowerCase().startsWith("application/json"))throw new Error("content type");let d=Number(u.headers.get("content-length"));if(Number.isFinite(d)&&d>ii)throw new Error("size");let l=new Uint8Array(await u.arrayBuffer());if(l.length>ii)throw new Error("size");let f;try{f=JSON.parse(new TextDecoder().decode(l))}catch{throw new Error("json")}return{statusCode:u.status,value:f,responseBodyBytes:l}}catch{throw new Error("cex transport refused")}finally{clearTimeout(a);for(let u of Object.values(o.headers));o.headers=null,o.body=void 0}}var Pu=e=>_u("sha256").update(e).digest("hex"),Fu=(e,t)=>e==="okx"?new Date(t).toISOString():String(e==="coinbase"?t/1e3:t),Qr=e=>/^(?=[A-Za-z0-9._-]{1,128}$)(?=.*[A-Za-z0-9])[A-Za-z0-9._-]+$/.test(String(e||""))?String(e):null,It=e=>typeof e=="string"&&/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e)?e:null;var ai=e=>/^0(?:\.0+)?$/.test(String(e));function Du(e,t){if(!It(e)||!It(t))throw new Error("cex authoritative decimal refused");let[r,n=""]=e.split("."),[o,i=""]=t.split("."),a=n.length+i.length,u=BigInt(r+n)*BigInt(o+i);if(!a)return u.toString();let c=u.toString().padStart(a+1,"0");return`${c.slice(0,-a)}.${c.slice(-a)}`}function Mu(e,t,r){let n,o,i;return e==="binance"&&t?.code===void 0?(n=t?.orderId,o=t?.symbol,i=t?.clientOrderId):e==="bybit"&&t?.retCode===0?(n=t?.result?.orderId,o=t?.result?.symbol,i=t?.result?.orderLinkId):e==="okx"&&t?.code==="0"&&t?.data?.length===1&&t.data[0]?.sCode==="0"?(n=t.data[0].ordId,o=t.data[0].instId,i=t.data[0].clOrdId):e==="coinbase"&&!t?.message&&(n=t?.id,o=t?.product_id,i=t?.client_oid),o!==void 0&&o!==r.symbol||i!==void 0&&i!==r.clientOrderId?null:Qr(n)}function qu(e,t,r){let n=null;return e==="binance"&&t&&typeof t=="object"&&t.code===void 0?n=t.orderId:e==="bybit"&&t?.retCode===0?n=t?.result?.orderId:e==="okx"&&t?.code==="0"&&t?.data?.length===1&&t.data[0]?.sCode==="0"?n=t.data[0].ordId:e==="coinbase"&&typeof t=="string"&&(n=t),Qr(n)===r.venueOrderId}function ju(e,t,r){let n=t,o,i,a,u,c;if(e==="binance"?(o=t?.orderId,i=t?.clientOrderId,a=t?.symbol,u={CANCELED:"cancelled",REJECTED:"rejected",FILLED:"filled",PARTIALLY_FILLED:"partial",NEW:"open",PENDING_CANCEL:"open"}[t?.status],c=t?.cummulativeQuoteQty):e==="bybit"&&t?.retCode===0&&t?.result?.list?.length===1?(n=t.result.list[0],o=n.orderId,i=n.orderLinkId,a=n.symbol,u={Cancelled:"cancelled",Rejected:"rejected",Filled:"filled",PartiallyFilled:"partial",New:"open"}[n.orderStatus],c=n.cumExecValue):e==="okx"&&t?.code==="0"&&t?.data?.length===1?(n=t.data[0],o=n.ordId,i=n.clOrdId,a=n.instId,u={canceled:"cancelled",filled:"filled",partially_filled:"partial",live:"open"}[n.state],It(n.accFillSz)&&It(n.avgPx)&&(ai(n.accFillSz)||!ai(n.avgPx))&&(c=Du(n.accFillSz,n.avgPx))):e==="coinbase"&&(o=t?.id,i=t?.client_oid,a=t?.product_id,u=t?.status==="done"?t?.done_reason==="canceled"?"cancelled":"filled":{rejected:"rejected",open:"open",pending:"open",active:"open"}[t?.status],c=t?.executed_value),Qr(o)!==r.venueOrderId||String(a||"")!==r.symbol||r.clientOrderId&&String(i||"")!==r.clientOrderId||!u||!It(c))throw new Error("cex authoritative status identity refused");return{status:u,filledQuote:c}}async function Uu(e,t){let r=t?.nowMs?.()??Date.now(),n=t?.transport||Yr,o=t.credential(e.credentialRef);if(!o||o.accountId!==e.accountId||o.venue!==e.venue)throw new Error("cex: credential binding refused");let i=e.order.operation!=="create"?e.store.requirePrior({...e,...e.order}):null,a=i?.tradeId||e.tradeId,u=ri({venue:e.venue,order:e.order,timestamp:Fu(e.venue,r),recvWindow:5e3}),c;e.order.operation==="create"?c=e.store.prepare({tradeId:e.tradeId,venue:e.venue,accountId:e.accountId,credentialRef:e.credentialRef,symbol:e.order.symbol,clientOrderId:e.order.clientOrderId,reservedNotional:e.reservedNotional,requestDigest:u.requestDigest,nowMs:r}):c=e.store.transition(a,["open","uncertain","sent","cancel-pending","settlement-pending"],"prepared",{operation:e.order.operation,requestDigest:u.requestDigest,nowMs:r}),e.store.transition(a,"prepared","sent",{sentAtMs:r});let s;try{s=await n(u,o)}catch{throw e.store.transition(a,"sent","uncertain",{uncertainAtMs:r}),new Error("cex transport refused; order is uncertain and requires status reconciliation")}let d=Pu(s.responseBodyBytes);if(e.order.operation==="create"){let p=Mu(e.venue,s.value,e.order);if(!p)throw e.store.transition(a,"sent","uncertain",{responseDigest:d}),new Error("cex response refused; order is uncertain and requires status reconciliation");return e.store.transition(a,"sent","open",{venueOrderId:p,responseDigest:d,openedAtMs:r})}if(e.order.operation==="cancel")return e.store.transition(a,"sent",qu(e.venue,s.value,i)?"cancel-pending":"uncertain",{responseDigest:d,observedAtMs:r});let l;try{l=ju(e.venue,s.value,i)}catch{return e.store.transition(a,"sent","uncertain",{responseDigest:d,observedAtMs:r})}let f=["cancelled","rejected","filled"].includes(l.status);if(f||l.status==="partial"){e.store.transition(a,"sent","settlement-pending",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote});let p=f&&(l.status==="cancelled"||l.status==="rejected")&&/^0(?:\.0+)?$/.test(l.filledQuote)?"release":"commit";return await t.settleLedger({tradeId:i.tradeId,filledQuote:l.filledQuote,disposition:p}),e.store.transition(a,"settlement-pending","terminal",{settledAtMs:r})}return e.store.transition(a,"sent","open",{responseDigest:d,observedAtMs:r,status:l.status,filledQuote:l.filledQuote})}function si(e){if(!e||typeof e.credential!="function"||typeof e.settleLedger!="function")throw new Error("cex: sealed runtime dependencies required");let t=Object.freeze({credential:e.credential,transport:e.transport||Yr,nowMs:e.nowMs||Date.now,settleLedger:e.settleLedger});return Object.freeze({execute:r=>Uu(r,t)})}import{createHash as zu,createHmac as ci,randomBytes as Wu,timingSafeEqual as Hu}from"node:crypto";var ui="oracle-local-signer-cex-owner-allow-v1",ut=e=>/^(?:0|[1-9]\d{0,19})$/.test(String(e||""))?String(e):null,li=e=>JSON.stringify(e),Ju=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&Hu(r,n)};function di({keyFile:e,approvedTelegramOwners:t,nowMs:r=Date.now}={}){if(!e)throw new Error("cex owner proof: signer policy key required");let n=new Set((t||[]).map(ut).filter(Boolean));if(!n.size)throw new Error("cex owner proof: approved owner context required");let o=new Set,i=u=>{let c=Buffer.from(N(e));try{return u(c)}finally{c.fill(0)}},a=i(u=>zu("sha256").update("cex-owner-instance\0").update(u).digest("hex"));return Object.freeze({mint({digest:u,senderId:c,chatId:s,platform:d,ttlMs:l=15e3}={}){let f=ut(c),p=ut(s),m=r();if(d!=="telegram"||!f||p!==f||!n.has(f))throw new Error("cex owner proof: exact Telegram owner DM required");if(!/^[0-9a-f]{64}$/.test(String(u||""))||!Number.isSafeInteger(l)||l<1||l>3e4)throw new Error("cex owner proof: binding refused");let h={version:1,decision:"Allow",digest:u,ownerSenderId:f,telegramChatId:p,audience:ui,instance:a,nonce:Wu(16).toString("hex"),issuedAtMs:m,expiresAtMs:m+l},g=i(w=>ci("sha256",w).update(li(h)).digest("hex"));return{claims:h,mac:g}},verify(u,{digest:c}={}){let s=u?.claims,d=r();if(!s||s.version!==1||s.decision!=="Allow"||s.digest!==c||s.audience!==ui||s.instance!==a||!/^[0-9a-f]{32}$/.test(s.nonce||"")||ut(s.ownerSenderId)!==ut(s.telegramChatId)||!n.has(ut(s.ownerSenderId))||!Number.isSafeInteger(s.issuedAtMs)||!Number.isSafeInteger(s.expiresAtMs)||s.expiresAtMs<=d||s.issuedAtMs>d||s.expiresAtMs-s.issuedAtMs>3e4||o.has(s.nonce))return!1;let l=i(f=>ci("sha256",f).update(li(s)).digest("hex"));return Ju(u.mac,l)?(o.add(s.nonce),!0):!1}})}var me=new rn(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),pi=new rn(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),en=new rn(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function el(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||Y.join(process.env.XDG_STATE_HOME||Y.join(Gu.homedir(),".local","state"),"oracle"),r=Vu("sha256").update(Y.resolve(e)).digest("hex").slice(0,16);return{vault:Y.join(e,"vault.json"),policy:Y.join(e,"signer-policy.json"),policyKey:Y.join(e,"policy-integrity-key"),policyAnchor:Y.join(t,`signer-policy-${r}.high-water`),ledger:Y.join(e,"signer-ledger.json"),ledgerAnchor:Y.join(t,`signer-ledger-${r}.high-water`),cexOrders:Y.join(e,"cex-orders.json"),cexOrdersAnchor:Y.join(t,`cex-orders-${r}.high-water`),token:Y.join(e,"signer-token"),lock:Y.join(t,`signer-${r}.lock`)}}function tl(e){try{return N(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=Ku(32).toString("hex");return se(e,t+`
|
|
11
|
+
`),t}function tn(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 mi(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function M(e,t){return e.surfaces.includes(t)}function pe(e,t){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error(`signer: invalid ${t}`);return r}function wi(e,t){return Object.entries(e||{}).find(([r])=>r.toLowerCase()===t)?.[1]}function rl(e,t){let r=e?.anvilQuote;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("signer: exact prepared Anvil quote is required");if(!e?.artifact?.anvilQuote||JSON.stringify(e.artifact.anvilQuote)!==JSON.stringify(r))throw new Error("signer: exact prepared Anvil quote artifact mismatch");return Object.freeze(t==="buy"?{totalCostRaw:BigInt(r.totalCostRaw).toString(),baseCostRaw:BigInt(r.baseCostRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString(),available:r.available===!0}:{netPayoutRaw:BigInt(r.netPayoutRaw).toString(),grossPayoutRaw:BigInt(r.grossPayoutRaw).toString(),feeRaw:BigInt(r.feeRaw).toString(),protocolFeeRaw:BigInt(r.protocolFeeRaw).toString()})}function nl(e,t,r){if(e.preconditions?.exactQuoteConfirmed!==!0)throw new Error("signer: exact prepared Anvil quote confirmation required");let n=e.artifact,o=t==="buy"?[r.totalCostRaw,e.maxPaymentTokenAmountRaw,n?.maxPaymentTokenAmountRaw,e.exactQuoteTotalCostRaw,n?.exactQuoteTotalCostRaw,e.preconditions?.confirmedTotalCostRaw]:[r.netPayoutRaw,e.minPayoutRaw,n?.minPayoutRaw,e.exactQuoteNetPayoutRaw,n?.exactQuoteNetPayoutRaw,e.preconditions?.confirmedNetPayoutRaw],i;try{i=BigInt(o[0]);for(let s of o.slice(1))if(BigInt(s)!==i)throw new Error("mismatch")}catch{throw new Error(`signer: exact Anvil ${t} settlement limit mismatch`)}let a=n?.transactions;if(!Array.isArray(a)||a.length!==1)throw new Error("signer: exact Anvil action transaction required");let u=t==="buy"?"buySpecificNFT":"sellNFT",c;try{if(c=me.decodeFunctionData(u,a[0].data),me.encodeFunctionData(u,[c[0],c[1]]).toLowerCase()!==String(a[0].data).toLowerCase())throw new Error("non-canonical")}catch{throw new Error(`signer: exact Anvil ${t} calldata required`)}if(BigInt(c[0])!==BigInt(e.tokenId)||BigInt(c[1])!==i)throw new Error(`signer: exact Anvil ${t} calldata limit mismatch`);return i}async function be(e,t,r,n,o,i=[]){let a=await e.send("eth_call",[{to:t,data:r.encodeFunctionData(n,i)},o]);return r.decodeFunctionResult(n,a)[0]}async function ol(e,t,r,{nowMs:n=Date.now(),signerAddress:o}={}){if(t?.surface!=="evm-nft"||String(t?.provider).toLowerCase()!=="anvil-nft")return null;if(!e||typeof e.send!="function")throw new Error("signer: trusted RPC cannot attest Anvil market");let i=pe(t.destination,"Anvil market"),a=pe(t.contract,"Anvil collection"),u=pe(t.paymentToken,"Anvil payment token"),c=BigInt(t.nativeSwapFeeWei),s=Number(t.paymentTokenDecimals),d=pe(o,"Anvil signer identity"),l=pe(t.owner,"Anvil envelope owner");if(d!==l)throw new Error("signer: Anvil signer identity mismatch");let f=BigInt(t.tokenId);if(f<0n)throw new Error("signer: invalid Anvil tokenId");let p=String(t.nftAction||"").toLowerCase();if(p!=="buy"&&p!=="sell")throw new Error("signer: unsupported Anvil NFT action");let m=rl(t,p),h=nl(t,p,m),g=t.anvilAttestation;if(!g||typeof g!="object"||Number(g.snapshotExpiresAtMs)<=Number(n))throw new Error("signer: fresh provider Anvil attestation required");let w=String(wi(r.anvilRuntimeCodeHashes,i)||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(w)||w!==String(g.runtimeCodeHash||"").toLowerCase())throw new Error("signer: Anvil runtime is not reviewed by policy");let E=wi(r.nftPaymentTokenCaps,u);if(!E||Number(E.decimals)!==s)throw new Error("signer: Anvil payment token decimals are not reviewed by policy");let b=String(await e.send("eth_chainId",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(b)||BigInt(b)!==4663n)throw new Error("signer: trusted RPC Anvil chain mismatch");let S=String(await e.send("eth_blockNumber",[])).toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(S))throw new Error("signer: trusted RPC returned an invalid Anvil block number");let I=BigInt(S),T=await e.send("eth_getBlockByNumber",[S,!1]),v=String(T?.hash||"").toLowerCase();if(String(T?.number||"").toLowerCase()!==S||!/^0x[0-9a-f]{64}$/.test(v))throw new Error("signer: trusted RPC returned an invalid Anvil block attestation");let C=Object.freeze({blockHash:v,requireCanonical:!0}),R=String(await e.send("eth_getCode",[i,C])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(R)||R==="0x")throw new Error("signer: Anvil market runtime is empty");let j=Qu(R).toLowerCase();if(j!==w)throw new Error("signer: Anvil market runtime mismatch with reviewed policy");let[ce,lt,tr]=await Promise.all([be(e,i,me,"collection",C),be(e,i,me,"token",C),be(e,i,me,"robinhoodSwapFeeWei",C)]),Ce=pe(ce,"live Anvil collection"),Ne=pe(lt,"live Anvil payment token"),kt=BigInt(tr).toString();if(Ce!==a)throw new Error("signer: live Anvil collection mismatch");if(Ne!==u)throw new Error("signer: live Anvil payment token mismatch");if(kt!==c.toString())throw new Error("signer: live Anvil native swap fee mismatch");let ze=Number(await be(e,Ne,pi,"decimals",C));if(!Number.isSafeInteger(ze)||ze!==s)throw new Error("signer: live Anvil payment token decimals mismatch");let Le=pe(await be(e,Ce,en,"ownerOf",C,[f]),"live Anvil token owner"),We=null,$e=null,He=null,Je=null,_;if(p==="buy"){let[Ge,y,A]=await Promise.all([be(e,i,me,"inventory",C,[f]),be(e,Ne,pi,"allowance",C,[d,i]),e.send("eth_call",[{to:i,data:me.encodeFunctionData("quoteSpecificBuy",[f])},C])]);We=!!Ge,$e=BigInt(y).toString();let x=me.decodeFunctionResult("quoteSpecificBuy",A);if(_=Object.freeze({totalCostRaw:BigInt(x[0]).toString(),baseCostRaw:BigInt(x[1]).toString(),feeRaw:BigInt(x[2]).toString(),protocolFeeRaw:BigInt(x[3]).toString(),available:!!x[4]}),JSON.stringify(_)!==JSON.stringify(m))throw new Error("signer: exact Anvil buy quote changed after preparation");if(Le!==i)throw new Error("signer: exact Anvil token owner is not the market");if(!We)throw new Error("signer: exact Anvil token is not in market inventory");if(BigInt($e)!==BigInt(t.preconditions?.allowanceRaw))throw new Error("signer: live Anvil ERC20 allowance changed after preparation");if(BigInt($e)<h)throw new Error("signer: live Anvil ERC20 allowance is insufficient");if(!_.available)throw new Error("signer: exact Anvil buy quote is unavailable");if(BigInt(_.totalCostRaw)!==h)throw new Error("signer: live Anvil buy quote does not equal exact payment limit");if(BigInt(_.totalCostRaw)!==BigInt(_.baseCostRaw)+BigInt(_.feeRaw)+BigInt(_.protocolFeeRaw))throw new Error("signer: exact Anvil buy quote fee arithmetic mismatch")}else{let[Ge,y,A]=await Promise.all([be(e,Ce,en,"getApproved",C,[f]),be(e,Ce,en,"isApprovedForAll",C,[d,i]),e.send("eth_call",[{to:i,data:me.encodeFunctionData("quoteSellNFT")},C])]);He=pe(Ge,"live Anvil token approval"),Je=!!y;let x=me.decodeFunctionResult("quoteSellNFT",A);if(_=Object.freeze({netPayoutRaw:BigInt(x[0]).toString(),grossPayoutRaw:BigInt(x[1]).toString(),feeRaw:BigInt(x[2]).toString(),protocolFeeRaw:BigInt(x[3]).toString()}),JSON.stringify(_)!==JSON.stringify(m))throw new Error("signer: exact Anvil sell quote changed after preparation");if(Le!==d)throw new Error("signer: exact Anvil token owner does not match signer");if(He!==i&&!Je)throw new Error("signer: live Anvil NFT approval is insufficient");if(He!==pe(t.preconditions?.approvedAddress,"prepared Anvil token approval")||Je!==!!t.preconditions?.approvedForAll)throw new Error("signer: live Anvil NFT approval changed after preparation");if(BigInt(_.netPayoutRaw)!==h)throw new Error("signer: live Anvil sell quote does not equal exact payout limit");if(BigInt(_.netPayoutRaw)+BigInt(_.feeRaw)+BigInt(_.protocolFeeRaw)!==BigInt(_.grossPayoutRaw))throw new Error("signer: exact Anvil sell quote fee arithmetic mismatch")}return Object.freeze({source:"local-signer-trusted-rpc",chainId:4663,market:i,collection:Ce,paymentToken:Ne,paymentTokenDecimals:ze,nativeSwapFeeWei:kt,signerAddress:d,nftAction:p,tokenId:f.toString(),tokenOwner:Le,inventoryMember:We,allowanceRaw:$e,approvedAddress:He,approvedForAll:Je,quote:_,blockNumber:I.toString(),blockHash:v,runtimeCodeHash:j,verifiedAtMs:Number(n)})}function hi(e,t,r="execution"){if(!e||!t)throw new Error("signer: complete Anvil revalidation evidence required");for(let n of["runtimeCodeHash","market","collection","paymentToken","paymentTokenDecimals","nativeSwapFeeWei","signerAddress","nftAction","tokenId","tokenOwner","inventoryMember","allowanceRaw","approvedAddress","approvedForAll"])if(String(t[n]).toLowerCase()!==String(e[n]).toLowerCase())throw new Error(`signer: Anvil ${n} changed after simulation at ${r}`);if(JSON.stringify(t.quote)!==JSON.stringify(e.quote))throw new Error(`signer: Anvil quote changed after simulation at ${r}`);return!0}function il(e,t,r,n,{nowMs:o=Date.now(),timeoutMs:i=15e3,signerAddress:a}={}){let u=Yu(new URL("./anvil-attestation-worker.mjs",import.meta.url)),c={anvilRuntimeCodeHashes:n?.anvilRuntimeCodeHashes,nftPaymentTokenCaps:n?.nftPaymentTokenCaps},s;try{s=Xu(process.execPath,[u],{input:JSON.stringify({rpcUrl:e,chainId:t,envelope:r,policy:c,nowMs:Number(o),signerAddress:a}),encoding:"utf8",timeout:i,maxBuffer:64e3,env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_OPTIONS:""},stdio:["pipe","pipe","pipe"]})}catch{throw new Error("signer: fresh independent Anvil attestation failed before reservation")}let d;try{d=JSON.parse(s)}catch{throw new Error("signer: invalid Anvil reservation attestation result")}if(!d||d.source!=="local-signer-trusted-rpc"||!/^0x[0-9a-f]{64}$/.test(String(d.blockHash||"")))throw new Error("signer: invalid Anvil reservation attestation result");return Object.freeze(d)}function al(e,t,r,n=null){let o=e?.version===1&&e?.surface?e:null,i=o?.artifact||e||{},a=[`surface=${o?.surface||"evm"} action=${o?.action||"evm"}`,`chain=${i.chainId??i.network??i.cluster??"n/a"} owner=${o?.owner||i.from||"n/a"}`,`to=${i.to||o?.destination||"n/a"} calldata=${String(i.data||"0x")} value=${i.value??"n/a"}`,`gas=${i.gasLimit??"n/a"} maxFeePerGas=${i.maxFeePerGas??i.gasPrice??"n/a"} maxPriorityFeePerGas=${i.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${i.l1FeeWei??"n/a"} operatorFeeWei=${i.operatorFeeWei??"n/a"}`,`nonce=${i.nonce??"n/a"} type=${i.type??"n/a"} accessList=${Array.isArray(i.accessList)?i.accessList.length:0}`,`slippageBps=${o?.slippageBps??i.slippageBps??"n/a"} expiresAtMs=${o?.expiresAtMs??i.expiresAtMs??"n/a"}`],u=(s,d)=>{if(a.push(`LEG ${d} chain=${s.chainId??"n/a"} from=${s.from??"n/a"} to=${s.to??"n/a"}`),a.push(`LEG ${d} calldata=${String(s.data||"0x")} value=${s.value??"n/a"}`),a.push(`LEG ${d} gas=${s.gasLimit??"n/a"} maxFeePerGas=${s.maxFeePerGas??s.gasPrice??"n/a"} maxPriorityFeePerGas=${s.maxPriorityFeePerGas??"n/a"}`),a.push(`LEG ${d} l1FeeWei=${s.l1FeeWei??"n/a"} operatorFeeWei=${s.operatorFeeWei??"n/a"} nonce=${s.nonce??"n/a"} type=${s.type??"n/a"}`),J(String(s.data||"0x")))try{let l=he(String(s.data||"0x"));a.push(`LEG ${d} APPROVAL token=${l.token||s.to||"n/a"} spender=${l.spender} amount=${l.amount}`)}catch{a.push(`LEG ${d} APPROVAL spender=undecodable amount=undecodable`)}},c=String(i.data||"0x");if(J(c))try{let s=he(c);a.push(`APPROVAL token=${s.token||i.to||"n/a"} spender=${s.spender} amount=${s.amount}`)}catch{a.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(i.transactions)&&(a.push(`batchLegs=${i.transactions.length}`),i.transactions.forEach((s,d)=>u(s,d))),o?.surface==="btc"){let s=sr(o,r);a.push(`amount=${s.value} sats fee=${s.fee} sats outputs=${s.outputs.join(",")}`)}if(o?.surface==="sol"){let s=pr(o,r);a.push(`amount=${s.value} lamports fee=${s.fee} lamports programs=${s.programs.join(",")}`)}if(o?.surface==="hl"){let s=ve(o,r);a.push(`hlKind=${s.kind} actionType=${s.actionType} coin=${s.coin||"n/a"} amount=${s.amount} notionalUsd=${s.notional} submitTo=${s.submitTo}`)}if(o?.surface==="poly"){let s=Ie(o,r);a.push(`polyKind=${s.kind} tokenId=${s.tokenId} side=${s.side} price=${s.price} quantity=${s.quantity} notionalUsdc=${s.notionalUsdc} submitTo=${s.submitTo}`)}if(o?.surface==="evm-nft"&&o?.provider==="anvil-nft"&&(a.push(`anvilAction=${o.nftAction} collection=${o.contract} tokenId=${o.tokenId} market=${o.destination}`),a.push(`paymentToken=${o.paymentToken} paymentTokenDecimals=${o.paymentTokenDecimals} maxPaymentTokenAmountRaw=${o.maxPaymentTokenAmountRaw??"n/a"} minPayoutRaw=${o.minPayoutRaw??"n/a"} nativeSwapFeeWei=${o.nativeSwapFeeWei}`),n&&(a.push(`SIGNER VERIFIED block=${n.blockNumber} blockHash=${n.blockHash} runtimeCodeHash=${n.runtimeCodeHash} signer=${n.signerAddress} collection=${n.collection} paymentToken=${n.paymentToken} paymentTokenDecimals=${n.paymentTokenDecimals} nativeSwapFeeWei=${n.nativeSwapFeeWei}`),a.push(`SIGNER DYNAMIC tokenId=${n.tokenId} owner=${n.tokenOwner} inventory=${n.inventoryMember} allowanceRaw=${n.allowanceRaw} approved=${n.approvedAddress} approvedForAll=${n.approvedForAll} quote=${JSON.stringify(n.quote)}`))),o?.surface==="lighter"){let s=ke(o,r);a.push(`lighterKind=${s.kind} actionType=${s.actionType} market=${s.symbol} amount=${s.amount} submitTo=${s.submitTo}`)}return`
|
|
12
12
|
Confirm exact action
|
|
13
|
-
${[...a,...
|
|
13
|
+
${[...a,...jo(e,t,r)].join(`
|
|
14
14
|
`)}
|
|
15
|
-
Type digest ${t}: `}async function Qt(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 fi(e,t){return Buffer.concat([Buffer.from([1]),Buffer.from(t),Buffer.from(e)]).toString("base64")}async function mi(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 Qt(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function zu(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let a=await fetch(`${o}/tx/${t}/outspend/${r}`);if(a.ok){let u=await a.json();if(u?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(u?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await mi(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Wu(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 Hu(e,t){return{simulate:async(r,n)=>(Ae(n,e()),!0),sign:async(r,n)=>{Ae(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return r?.typedData?(oo(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):io({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{Ae(o,e());let{Signature:i,keccak256:a}=await import("ethers"),u=i.from(r);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:u.r,s:u.s,v:u.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(r),status:1}}}}function Ju(e){return{simulate:async(t,r)=>(Ie(r,e()),!0),sign:async(t,r)=>{Ie(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 Et(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=Ie(n,e()),i=Et(r,t),a=co(i),u=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),c=await u.json().catch(()=>({}));if(!u.ok||Number(c?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(c?.tx_hash||c?.txHash||"lighter"),status:1}}}}function Gu(e,t){return{simulate:async(r,n)=>(Pe(n,e()),!0),sign:async(r,n)=>{Pe(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: order wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: order wallet must match envelope owner");let a=r.domain||r.typedData.domain,u=r.types||r.typedData.types,c=r.message||r.typedData.message;return t.signTypedData(a,u,c)},broadcast:async(r,n,o)=>{let i=Pe(o,e()),{keccak256:a}=await import("ethers"),u=n.message||n.typedData.message,c=i.kind==="cow"?{sellToken:u.sellToken,buyToken:u.buyToken,receiver:u.receiver,sellAmount:u.sellAmount,buyAmount:u.buyAmount,validTo:u.validTo,appData:u.appData,feeAmount:u.feeAmount,kind:u.kind,partiallyFillable:u.partiallyFillable,sellTokenBalance:u.sellTokenBalance,buyTokenBalance:u.buyTokenBalance,from:o.owner,signature:r,signingScheme:"eip712",quoteId:n.quoteId??void 0}:{orderHash:i.digest,signature:r,data:u},s=await fetch(i.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(c)}),d=await s.json().catch(()=>({}));if(!s.ok||d?.error||d?.success===!1)throw new Error(i.kind==="cow"?"signer: CoW orderbook rejected the order":"signer: 1inch orderbook rejected the order");return{hash:a(r),status:1,orderHash:i.digest,uid:typeof d=="string"?d:d?.uid||null}}}}function Vu(e,t){return{simulate:async(r,n)=>(ve(n,e()),!0),sign:async(r,n)=>{ve(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),a=ve(o,i),u=gr(i),{keccak256:c}=await import("ethers"),s=Ln({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:u.key}),d=JSON.stringify(s),l=Cn({creds:u,address:o.owner,method:"POST",path:"/order",body:d}),f=await fetch(a.submitTo,{method:"POST",headers:l,body:d}),p=await f.json().catch(()=>({}));if(!f.ok||p?.success===!1||p?.error||p?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:c(r),status:1}}}}function Ku(e,t){let r=Hr(t);return{simulate:async n=>{let o=e(),i=Zr.fromPSBT(Buffer.from(n.psbt,"base64"));return await Promise.all(Array.from({length:i.inputsLength},(a,u)=>{let c=i.getInput(u),s=Buffer.from(c.txid||[]).toString("hex");return zu(o,s,c.index)})),!0},sign:n=>{let o=Zr.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(r),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let a=Zr.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let u;try{let s=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(u=(await s.text()).trim(),!s.ok)throw new Error(`signer: Bitcoin broadcast failed ${s.status}`)}catch(s){if(!/Bitcoin broadcast failed 404/.test(String(s?.message||s)))throw s;u=await mi(o,"sendrawtransaction",[a.hex])}if(u&&String(u).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let s=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${s}/tx/${a.id}/status`);d.ok&&(c=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:c}}}}function Xu(e,t){let r=Hr(t);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let a=Buffer.from(n.messageBase64,"base64"),u=fi(a,new Uint8Array(64)),c=await Qt(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[u,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Wu(c)},sign:n=>fi(Buffer.from(n.messageBase64,"base64"),Pu.sign(Buffer.from(n.messageBase64,"base64"),r)),broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let a=await Qt(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await Qt(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:a,status:0};let s=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:a,status:s?1:null}}}}function Yu(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 Qu(e,t,r,n,{submitPrivate:o}={}){if((await e.getNetwork()).chainId!==BigInt(r.chainId))throw new Error("signer: RPC chain mismatch");let a={native:(await e.getBalance(r.from)).toString()},u=n&&n.privateRelay;if(u&&typeof o=="function"){let l=u==="require"||u?.mode==="require";try{let f=await o(t,{chainId:Number(r.chainId),requirePrivate:l,allowPublicFallback:!l});if(!f.fellBack&&f.hash){let p=await e.waitForTransaction(f.hash),m={native:(await e.getBalance(r.from)).toString()};return{hash:f.hash,status:p?.status??null,verifiedBefore:a,verifiedAfter:m,submission:{path:"private",mode:f.mode,endpoint:f.endpoint}}}}catch(f){if(l)throw f}}let c=await e.broadcastTransaction(t),s=await c.wait(),d={native:(await e.getBalance(r.from)).toString()};return{hash:s?.hash??c.hash,status:s?.status??null,verifiedBefore:a,verifiedAfter:d,submission:{path:"public"}}}async function wi({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:u,Wallet:c}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(a<1e3||a>12e4)throw new Error("signer: session must be at most 120 seconds");let s=_u(e),d=()=>Object.freeze(Jt(s.policy,s.policyKey,{sequenceAnchorFile:s.policyAnchor})),l=d(),f=M(l,"cex")?ai({keyFile:s.policyKey,approvedTelegramOwners:String(process.env.ORACLE_OWNER_TELEGRAM||"").split(",").map(y=>y.trim()).filter(Boolean)}):null;if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let p=["surfaces","actions","destinations","owners"];l.surfaces.some(y=>String(y).startsWith("evm"))&&p.push("chains","spenders");for(let y of p)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"||y==="evm-order")){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"||y==="evm-order")&&(!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")&&y!=="evm-order")&&(!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(M(l,"poly")&&(gr(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(M(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(M(l,"cex")&&(!l.cexAccounts||Object.keys(l.cexAccounts).length===0))throw new Error("signer: cexAccounts allowlist is empty");if(M(l,"hl")){let y=Array.isArray(l.coins)?l.coins.map(String):[],A=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(y.filter(L=>L!=="*"&&L!=="#*").length&&!y.includes("*")&&A.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let m=r?Bo(r):N(t),h=So(s.vault),g=xo(h,m),w;try{w=Wo(g,h.meta)}finally{g.fill(0)}if((ui(l)||M(l,"hl")||M(l,"poly"))&&tn("evm",w.evm,l.owners),M(l,"btc")&&tn("btc",w.btc,l.owners),M(l,"sol")&&tn("sol",w.sol,l.owners),M(l,"cex")){if(!w.cex||Object.keys(w.cex).length===0)throw new Error("signer: local CEX credential records required");for(let[y,A]of Object.entries(l.cexAccounts)){let x=w.cex[y];if(!x||x.accountId!==A.accountId||!A.venues.includes(x.venue)||A.credentialRecordRef!==y)throw new Error("signer: CEX credential venue/account binding refused")}}let E=Array.isArray(l.chains)?l.chains.filter(y=>Number.isInteger(Number(y))&&String(y).trim()!==""):[],b=ui(l);if(b&&(E.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(M(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(M(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let S=b?new u(l.rpcUrl,Number(E[0])):null,I=w.evm&&(b||M(l,"hl")||M(l,"poly"))?S?new c(w.evm.secret).connect(S):new c(w.evm.secret):null,T=S?{simulate:async y=>{if((await S.getNetwork()).chainId!==BigInt(y.chainId))throw new Error("signer: RPC chain mismatch");return await S.call(y),!0},sign:y=>I.signTransaction(y),broadcast:(y,A,x)=>Qu(S,y,A,x,{submitPrivate:vo})}:null,v=S?async y=>Zu(S,y):void 0,C=new Map,R=y=>y?.surface==="evm-nft"&&String(y?.provider).toLowerCase()==="anvil-nft",j=async(y,A=d(),x="execution")=>{if(!R(y))return null;let L=await qu(S,y,A,{nowMs:Date.now(),signerAddress:I.address}),ne=C.get(G(y));return ne&&di(ne,L,x),L},ce={...T?{evm:T,"evm-swap":T,"evm-bridge":T,"evm-nft":T}:{},...I&&M(l,"evm-order")?{"evm-order":Gu(d,I)}:{},...w.btc?{btc:Ku(d,w.btc)}:{},...w.sol?{sol:Xu(d,w.sol)}:{},...I&&M(l,"hl")?{hl:Hu(d,I)}:{},...I&&M(l,"poly")?{poly:Vu(d,I)}:{},...M(l,"lighter")?{lighter:Ju(d)}:{}};Yu(ce,n);let lt=ro({...ce,...n}),tr=new Set(Object.keys(ce)),Oe=new Set(Object.keys(n||{})),Ce=l.surfaces.filter(y=>y!=="cex"&&!tr.has(y)&&!Oe.has(y));if(Ce.length)throw new Error(`signer: ${Ce.join(",")} require local keys or injected surface transports`);let kt=Date.now(),ze=kt+a,Ne=!1,We=!1,Le=()=>{if(!We){We=!0;for(let y of Object.values(w.cex||{}))for(let A of["apiKeyBytes","apiSecretBytes","passphraseBytes"])y[A]?.fill?.(0)}},He=()=>Ne?!1:si.existsSync(s.lock)?(Ne=!0,!1):si.existsSync(s.vault)&&Date.now()<ze,Je=()=>(Ne=!0,Le(),se(s.lock,`disarmed ${new Date().toISOString()}
|
|
16
|
-
`),!0),
|
|
17
|
-
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,er=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function
|
|
18
|
-
`),0;let r=er(e,"--passphrase-file"),n=await
|
|
19
|
-
`),await new Promise(o=>n.on("close",o)),0}var
|
|
15
|
+
Type digest ${t}: `}async function Qt(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 gi(e,t){return Buffer.concat([Buffer.from([1]),Buffer.from(t),Buffer.from(e)]).toString("base64")}async function Ei(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 Qt(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function sl(e,t,r){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let a=await fetch(`${o}/tx/${t}/outspend/${r}`);if(a.ok){let u=await a.json();if(u?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(u?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await Ei(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function cl(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 ul(e,t){return{simulate:async(r,n)=>(ve(n,e()),!0),sign:async(r,n)=>{ve(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: HL wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: HL wallet must match envelope owner");return r?.typedData?(oo(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):io({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{ve(o,e());let{Signature:i,keccak256:a}=await import("ethers"),u=i.from(r);if((await(await fetch(n.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:n.action,nonce:n.nonce,signature:{r:u.r,s:u.s,v:u.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(r),status:1}}}}function ll(e){return{simulate:async(t,r)=>(ke(r,e()),!0),sign:async(t,r)=>{ke(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 Et(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=ke(n,e()),i=Et(r,t),a=co(i),u=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),c=await u.json().catch(()=>({}));if(!u.ok||Number(c?.code)!==200)throw new Error("signer: Lighter sendTx rejected the order");return{hash:String(c?.tx_hash||c?.txHash||"lighter"),status:1}}}}function dl(e,t){return{simulate:async(r,n)=>(_e(n,e()),!0),sign:async(r,n)=>{_e(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(s=>String(s).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: order wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: order wallet must match envelope owner");let a=r.domain||r.typedData.domain,u=r.types||r.typedData.types,c=r.message||r.typedData.message;return t.signTypedData(a,u,c)},broadcast:async(r,n,o)=>{let i=_e(o,e()),{keccak256:a}=await import("ethers"),u=n.message||n.typedData.message,c=i.kind==="cow"?{sellToken:u.sellToken,buyToken:u.buyToken,receiver:u.receiver,sellAmount:u.sellAmount,buyAmount:u.buyAmount,validTo:u.validTo,appData:u.appData,feeAmount:u.feeAmount,kind:u.kind,partiallyFillable:u.partiallyFillable,sellTokenBalance:u.sellTokenBalance,buyTokenBalance:u.buyTokenBalance,from:o.owner,signature:r,signingScheme:"eip712",quoteId:n.quoteId??void 0}:{orderHash:i.digest,signature:r,data:u},s=await fetch(i.submitTo,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(c)}),d=await s.json().catch(()=>({}));if(!s.ok||d?.error||d?.success===!1)throw new Error(i.kind==="cow"?"signer: CoW orderbook rejected the order":"signer: 1inch orderbook rejected the order");return{hash:a(r),status:1,orderHash:i.digest,uid:typeof d=="string"?d:d?.uid||null}}}}function fl(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(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),a=Ie(o,i),u=gr(i),{keccak256:c}=await import("ethers"),s=Ln({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:u.key}),d=JSON.stringify(s),l=Cn({creds:u,address:o.owner,method:"POST",path:"/order",body:d}),f=await fetch(a.submitTo,{method:"POST",headers:l,body:d}),p=await f.json().catch(()=>({}));if(!f.ok||p?.success===!1||p?.error||p?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:c(r),status:1}}}}function pl(e,t){let r=Hr(t);return{simulate:async n=>{let o=e(),i=Zr.fromPSBT(Buffer.from(n.psbt,"base64"));return await Promise.all(Array.from({length:i.inputsLength},(a,u)=>{let c=i.getInput(u),s=Buffer.from(c.txid||[]).toString("hex");return sl(o,s,c.index)})),!0},sign:n=>{let o=Zr.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(r),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let a=Zr.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let u;try{let s=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(u=(await s.text()).trim(),!s.ok)throw new Error(`signer: Bitcoin broadcast failed ${s.status}`)}catch(s){if(!/Bitcoin broadcast failed 404/.test(String(s?.message||s)))throw s;u=await Ei(o,"sendrawtransaction",[a.hex])}if(u&&String(u).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let s=i.endsWith("/tx")?i.slice(0,-3):i,d=await fetch(`${s}/tx/${a.id}/status`);d.ok&&(c=(await d.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:c}}}}function ml(e,t){let r=Hr(t);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let a=Buffer.from(n.messageBase64,"base64"),u=gi(a,new Uint8Array(64)),c=await Qt(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[u,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return cl(c)},sign:n=>gi(Buffer.from(n.messageBase64,"base64"),Zu.sign(Buffer.from(n.messageBase64,"base64"),r)),broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let a=await Qt(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await Qt(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:a,status:0};let s=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:a,status:s?1:null}}}}function wl(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 hl(e,t,r,n,{submitPrivate:o}={}){if((await e.getNetwork()).chainId!==BigInt(r.chainId))throw new Error("signer: RPC chain mismatch");let a={native:(await e.getBalance(r.from)).toString()},u=n&&n.privateRelay;if(u&&typeof o=="function"){let l=u==="require"||u?.mode==="require";try{let f=await o(t,{chainId:Number(r.chainId),requirePrivate:l,allowPublicFallback:!l});if(!f.fellBack&&f.hash){let p=await e.waitForTransaction(f.hash),m={native:(await e.getBalance(r.from)).toString()};return{hash:f.hash,status:p?.status??null,verifiedBefore:a,verifiedAfter:m,submission:{path:"private",mode:f.mode,endpoint:f.endpoint}}}}catch(f){if(l)throw f}}let c=await e.broadcastTransaction(t),s=await c.wait(),d={native:(await e.getBalance(r.from)).toString()};return{hash:s?.hash??c.hash,status:s?.status??null,verifiedBefore:a,verifiedAfter:d,submission:{path:"public"}}}async function bi({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:u,Wallet:c}=await import("ethers");if(!t&&!r)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(a<1e3||a>12e4)throw new Error("signer: session must be at most 120 seconds");let s=el(e),d=()=>Object.freeze(Jt(s.policy,s.policyKey,{sequenceAnchorFile:s.policyAnchor})),l=d(),f=M(l,"cex")?di({keyFile:s.policyKey,approvedTelegramOwners:String(process.env.ORACLE_OWNER_TELEGRAM||"").split(",").map(y=>y.trim()).filter(Boolean)}):null;if(!["exact-human","auto-within-rails"].includes(l.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(l.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");let p=["surfaces","actions","destinations","owners"];l.surfaces.some(y=>String(y).startsWith("evm"))&&p.push("chains","spenders");for(let y of p)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"||y==="evm-order")){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"||y==="evm-order")&&(!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")&&y!=="evm-order")&&(!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(M(l,"poly")&&(gr(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(M(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(M(l,"cex")&&(!l.cexAccounts||Object.keys(l.cexAccounts).length===0))throw new Error("signer: cexAccounts allowlist is empty");if(M(l,"hl")){let y=Array.isArray(l.coins)?l.coins.map(String):[],A=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(y.filter(L=>L!=="*"&&L!=="#*").length&&!y.includes("*")&&A.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let m=r?Bo(r):N(t),h=So(s.vault),g=xo(h,m),w;try{w=Ko(g,h.meta)}finally{g.fill(0)}if((mi(l)||M(l,"hl")||M(l,"poly"))&&tn("evm",w.evm,l.owners),M(l,"btc")&&tn("btc",w.btc,l.owners),M(l,"sol")&&tn("sol",w.sol,l.owners),M(l,"cex")){if(!w.cex||Object.keys(w.cex).length===0)throw new Error("signer: local CEX credential records required");for(let[y,A]of Object.entries(l.cexAccounts)){let x=w.cex[y];if(!x||x.accountId!==A.accountId||!A.venues.includes(x.venue)||A.credentialRecordRef!==y)throw new Error("signer: CEX credential venue/account binding refused")}}let E=Array.isArray(l.chains)?l.chains.filter(y=>Number.isInteger(Number(y))&&String(y).trim()!==""):[],b=mi(l);if(b&&(E.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(M(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(M(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let S=b?new u(l.rpcUrl,Number(E[0])):null,I=w.evm&&(b||M(l,"hl")||M(l,"poly"))?S?new c(w.evm.secret).connect(S):new c(w.evm.secret):null,T=S?{simulate:async y=>{if((await S.getNetwork()).chainId!==BigInt(y.chainId))throw new Error("signer: RPC chain mismatch");return await S.call(y),!0},sign:y=>I.signTransaction(y),broadcast:(y,A,x)=>hl(S,y,A,x,{submitPrivate:vo})}:null,v=S?async y=>gl(S,y):void 0,C=new Map,R=y=>y?.surface==="evm-nft"&&String(y?.provider).toLowerCase()==="anvil-nft",j=async(y,A=d(),x="execution")=>{if(!R(y))return null;let L=await ol(S,y,A,{nowMs:Date.now(),signerAddress:I.address}),ne=C.get(V(y));return ne&&hi(ne,L,x),L},ce={...T?{evm:T,"evm-swap":T,"evm-bridge":T,"evm-nft":T}:{},...I&&M(l,"evm-order")?{"evm-order":dl(d,I)}:{},...w.btc?{btc:pl(d,w.btc)}:{},...w.sol?{sol:ml(d,w.sol)}:{},...I&&M(l,"hl")?{hl:ul(d,I)}:{},...I&&M(l,"poly")?{poly:fl(d,I)}:{},...M(l,"lighter")?{lighter:ll(d)}:{}};wl(ce,n);let lt=ro({...ce,...n}),tr=new Set(Object.keys(ce)),Ce=new Set(Object.keys(n||{})),Ne=l.surfaces.filter(y=>y!=="cex"&&!tr.has(y)&&!Ce.has(y));if(Ne.length)throw new Error(`signer: ${Ne.join(",")} require local keys or injected surface transports`);let kt=Date.now(),ze=kt+a,Le=!1,We=!1,$e=()=>{if(!We){We=!0;for(let y of Object.values(w.cex||{}))for(let A of["apiKeyBytes","apiSecretBytes","passphraseBytes"])y[A]?.fill?.(0)}},He=()=>Le?!1:fi.existsSync(s.lock)?(Le=!0,!1):fi.existsSync(s.vault)&&Date.now()<ze,Je=()=>(Le=!0,$e(),se(s.lock,`disarmed ${new Date().toISOString()}
|
|
16
|
+
`),!0),_=bo({host:o,port:i,token:tl(s.token),policy:l,readPolicy:d,isArmed:He,disarm:Je,sessionExpiresAtMs:ze,nowMs:Date.now,simulate:async(y,A)=>(await j(A,d(),"before simulation"),_t(A,lt).simulate(y,A)),estimateNetworkFees:v,sign:async(y,A)=>(await j(A,d(),"before signing"),_t(A,lt).sign(y,A)),verifySigned:(y,A,x)=>mo(x?.surface||"evm",y,A,x),broadcast:async(y,A,x)=>(await j(x,d(),"before broadcast"),_t(x,lt).broadcast(y,A,x)),confirmArtifact:async(y,A,x)=>{let L=await j(y,x),ne=await El(y,A,x,L);return ne===!0&&L&&C.set(A,L),ne},decodeEconomics:(y,A)=>Ir(y,A),reserveLedger:(y,A)=>{let x=y?.version===1&&y?.surface?y:null,L=x?.artifact||y;if(R(x)){let we=V(x),Se=C.get(we);if(!Se||Date.now()-Number(Se.verifiedAtMs)>15e3)throw new Error("signer: fresh independent Anvil attestation required before reservation");let Be=il(A.rpcUrl,L.chainId,x,A,{nowMs:Date.now(),signerAddress:I.address});hi(Se,Be,"before reservation"),C.set(we,Be)}let ne=x?.tradeId||L?.tradeId;if(!ne)throw new Error("ledger: executable artifact requires a tradeId");let xe;if(x)xe=Ir(x,A);else{if(L?.value===void 0)throw new Error("ledger: executable artifact value required");let we=BigInt(L.value),Se=BigInt(L.gasLimit??0),Be=BigInt(L.maxFeePerGas??L.gasPrice??0);if(Se<=0n||Be<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let nn=Se*Be+BigInt(L.l1FeeWei??0)+BigInt(L.operatorFeeWei??0);xe={unit:"wei",value:we.toString(),notional:(we+nn).toString(),fee:nn.toString()}}if(Array.isArray(xe.units))return xt({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:ne,units:xe.units,policy:A});if(xe.value===void 0||xe.notional===void 0)throw new Error("ledger: decoded value and notional required");return xt({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:ne,...xe,policy:A})},commitLedger:y=>To({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),releaseLedger:y=>Oo({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),settleFailedLedger:y=>No({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:y.tradeId}),validateReservation:(y,A,x)=>ko({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,reservation:y,policy:A,economics:x}),verifyFeeWaiver:(y,A)=>$o(y,A,s.policyKey),verifyTriggerAttestation:(y,A,x)=>Lo(y,A,s.policyKey,x),inspectCex:Kt,verifyCexOwnerProof:f?(y,A)=>f.verify(y,A):void 0,cexExecute:M(l,"cex")?async y=>{let A=d(),x=Kt(y,A,Date.now()),L=x.kind==="spot-limit-create"?"create":x.kind==="spot-limit-cancel"?"cancel":"status";L==="create"&&Yo({envelope:y,paths:s,nowMs:Date.now()});let ne=L==="create"?{operation:L,symbol:x.symbol,side:x.side,baseSize:x.baseSize,limitPrice:x.limitPrice,clientOrderId:x.clientOrderId}:{operation:L,symbol:x.symbol,venueOrderId:x.venueOrderId};return si({credential:we=>w.cex[we],settleLedger:({tradeId:we,disposition:Se,filledQuote:Be})=>Co({file:s.ledger,keyFile:s.policyKey,anchorFile:s.ledgerAnchor,policyAnchorFile:s.policyAnchor,tradeId:we,expectedUnit:x.unit,filledQuote:Be,disposition:Se})}).execute({venue:x.venue,accountId:x.accountId,credentialRef:x.credentialRef,tradeId:x.tradeId,reservedNotional:x.notional,order:ne,store:ei({file:s.cexOrders,keyFile:s.policyKey,anchorFile:s.cexOrdersAnchor})})}:void 0,autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),Ge=setTimeout(()=>_.close(),a);return Ge.unref(),_.on("close",()=>{clearTimeout(Ge),$e()}),_.listen(i,o),_}var Zt="0x420000000000000000000000000000000000000F";function yi(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 gl(e,t){if(!ue(t?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:r,Transaction:n}=await import("ethers"),o=new r(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce??0,type:t.type,accessList:t.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let a;try{let u=await e.call({to:Zt,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",u)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await yl(e,o,t.gasLimit)}}async function yl(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:Zt,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!yi(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:Zt,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:Zt,data:t.encodeFunctionData("operatorFeeConstant")}),a=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),u=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+u).toString()}catch(o){if(!yi(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function El(e,t,r,n=null){return process.stdin.isTTY?(process.stderr.write(al(e,t,r,n)),process.stdin.resume(),new Promise(o=>{let i=a=>{process.stdin.off("data",i),process.stdin.pause(),o(String(a).trim()===t)};process.stdin.once("data",i)})):!1}var xi=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
|
|
17
|
+
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,er=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function xl(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(xi+`
|
|
18
|
+
`),0;let r=er(e,"--passphrase-file"),n=await bi({configDir:bl.join(t.configDir||Ot(),"signer"),passphraseFile:r,credentialService:er(e,"--credential-service"),port:Number(er(e,"--port",9462)),sessionMs:Number(er(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
|
|
19
|
+
`),await new Promise(o=>n.on("close",o)),0}var Sw={name:"signer",summary:"run the short-lived loopback signer",usage:xi,run:e=>xl(e.argv||[])};export{Sw as default,xl as run};
|