@oracle-agent/oracle 0.24.10 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/SETUP.md +22 -0
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +45 -44
- package/dist/bin/oracle-data-mcp.mjs +26 -26
- package/dist/bin/oracle.mjs +1 -1
- package/dist/cli/commands/chat.mjs +111 -111
- package/dist/cli/commands/doctor.mjs +3 -3
- package/dist/cli/commands/eval.mjs +180 -42
- package/dist/cli/commands/farm.mjs +73 -60
- package/dist/cli/commands/model.mjs +118 -118
- package/dist/cli/commands/receipt.mjs +3 -3
- package/dist/cli/commands/sign.mjs +11 -11
- package/dist/cli/commands/signer.mjs +13 -13
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +47 -46
- package/dist/index.mjs +48 -47
- package/dist/local-signer/index.mjs +3 -3
- package/package.json +2 -2
- package/public/oracle-splash/downloads/index.html +4 -4
- package/public/oracle-splash/index.html +1 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import Di from"node:path";import ye from"node:fs";import zt from"node:os";import ne from"node:path";import{fileURLToPath as Kt}from"node:url";var Xt=ne.dirname(Kt(import.meta.url)),Hi=ne.resolve(Xt,"../..");function Nr(){return process.env.ORACLE_FAKE_HOME||zt.homedir()}function Zt(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function ve(){return Zt()?process.env.ORACLE_CONFIG_DIR||ne.join(Nr(),".config","oracle"):ne.join(Nr(),".config","oracle")}function Yt(){return ne.join(ve(),"desk.json")}function Qt(){return ne.join(ve(),"env")}function te({force:e=!1}={}){if(te._done&&!e)return te._result||null;te._done=!0;let r={},t=(o,i)=>{if(i==null)return;let a=String(i).trim();a&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=a,r[o]=a))};try{let o=Qt();if(ye.existsSync(o))for(let i of ye.readFileSync(o,"utf8").split(/\r?\n/)){let a=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),t(a[1],s)}}catch{}try{let o=Yt();if(ye.existsSync(o)){let i=JSON.parse(ye.readFileSync(o,"utf8"));i&&typeof i=="object"&&(t("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),t("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),t("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),t("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),t("ORACLE_EXEC_URL",i.execUrl),t("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(t("ORACLE_DESK_URL",n),t("ORACLE_DATA_URL",n),t("ORACLE_API_URL",n),t("ORACLE_PUBLIC_URL",n),t("MAD_DESK_URL",n)),te._result=Object.keys(r).length?r:null,te._result}try{te()}catch{}import Pt from"node:fs";import D from"node:path";import Ii from"node:os";import{createHash as Ni,randomBytes as Li}from"node:crypto";import{Transaction as Sr}from"@scure/btc-signer";import{ed25519 as ki}from"@noble/curves/ed25519.js";import Zo from"node:http";import{timingSafeEqual as Yo}from"node:crypto";import{createHash as $o,randomBytes as Uo,timingSafeEqual as Do}from"node:crypto";import{base58 as lt}from"@scure/base";import{Interface as wn,MaxUint256 as gn,isAddress as En,keccak256 as _a,toUtf8Bytes as Ba}from"ethers";import{Interface as mn,isAddress as da}from"ethers";import{isAddress as aa}from"ethers";import{createHash as on,createHmac as an,timingSafeEqual as sn}from"node:crypto";import{readFileSync as en}from"node:fs";import{homedir as rn}from"node:os";import{join as Ae}from"node:path";function tn(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let t=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return t?[t]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),r=rn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||Ae(r,".config","oracle")).trim();return[e,Ae(t,"exec.env")].filter(Boolean)}return[e,Ae(r,".config","oracle","exec.env"),Ae(r,".config","mad-desk","exec.env")].filter(Boolean)}function le(e,r,t){let n=e??process.env[r]??process.env[t];if(!String(n||"").trim())for(let o of tn())try{let i=en(o,"utf8"),a=i.match(new RegExp(`^${r}=(.*)$`,"m"))||i.match(new RegExp(`^${t}=(.*)$`,"m"));if(a&&(n=a[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${r} required for attestation. Set it in the environment, or place ${r}=<value> in ~/.config/oracle/exec.env`);return n}function oe(e,r,t="guard"){let n=Number(r);if(r==null||!Number.isFinite(n))throw new Error(`${t}: current time must be a finite number (got ${nn(r)})`);let o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${t}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${t} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${t}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${t}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function nn(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var Lr=100;function He(e){return Array.isArray(e)?`[${e.map(He).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${He(e[r])}`).join(",")}}`:JSON.stringify(e??null)}function cn(e,{required:r=!1}={}){try{return le(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(t){if(r)throw t;return null}}function un(e){let{signature:r,...t}=e;return t}function fn(e){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<10||r.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return on("sha256").update(Buffer.from(r.slice(2),"hex")).digest("hex")}function ln(e,r){let t=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(r??""),"utf8");return t.length!==n.length||t.length===0?!1:sn(t,n)}function dn(e){let r=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(r)||r.length<10||r.length%2!==0)return null;let t=r.slice(0,10).toLowerCase(),n=[];for(let i=10;i+64<=r.length;i+=64)n.push(r.slice(i,i+64));let o=i=>n[i]==null?null:BigInt("0x"+n[i]);switch(t){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let a=Number(i)/32;return!Number.isInteger(a)||a<0?null:o(a+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function ze(e,{nowMs:r=Date.now(),chainId:t,venue:n,secret:o,tx:i,requireSigned:a=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let s=cn(o,{required:a});if(a&&!s)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(s){let m=an("sha256",s).update(He(un(e))).digest("hex");if(!ln(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>Lr)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>Lr||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{oe({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},r,"auto-slippage quote")}catch(m){throw new Error(`${m.message}; re-quote before signing`)}if(t!=null&&Number(e.chainId)!==Number(t))throw new Error("auto-slippage guard chain mismatch");if(n&&String(e.venue).toLowerCase()!==String(n).toLowerCase())throw new Error("auto-slippage guard venue mismatch");let l=BigInt(e.quoteAmountOut??0),f=BigInt(e.minAmountOut??0);if(l<=0n||f<=0n)throw new Error("auto-slippage guard amounts must be positive");let d=l*BigInt(1e4-c),p=d/10000n;if(d%10000n!==0n&&(p+=1n),f<p)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let m=dn(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==fn(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 w=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${w}; 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 wa=new mn(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as hn,isAddress as xa}from"ethers";var va=new hn(["function approve(address spender,uint256 amount) returns (bool)"]),Aa=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function kr(e,r="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${r} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${r} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let t=String(e??"").trim();if(t==="")throw new Error(`${r} is required`);if(!/^-?\d+$/.test(t)&&!/^0x[0-9a-fA-F]+$/.test(t))throw new Error(`${r} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(t)}`);try{return BigInt(t)}catch{throw new Error(`${r} must be an integer, got ${JSON.stringify(t)}`)}}var qa=new wn(["function approve(address spender,uint256 amount) returns (bool)"]);function _r(e,r){let t=String(e||"").trim();if(!En(t))throw new Error(`${r} must be an address`);return t.toLowerCase()}function xn(e,r="approval amount",{allowZero:t=!1}={}){let n=kr(e,r);if(t?n<0n:n<=0n)throw new Error(`${r} must be positive`);if(n>=gn)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var Br=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),Sn=new Set(["0x39509351","0xf9255c1f"]);function W(e){let r=String(e||"").toLowerCase();return r.length<10?!1:Br.has(r.slice(0,10))}function de(e){if(!W(e))throw new Error("approval calldata required");let r=String(e||"").toLowerCase(),t=r.slice(0,10),n=r.slice(10).match(/.{1,64}/g)||[],o=u=>n[u]?"0x"+n[u].slice(24):null,i=u=>n[u]?BigInt("0x"+n[u]):null,a=null,s=null,c=null;switch(t){case"0x095ea7b3":case"0x39509351":a=o(0),s=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),a=o(1),s=i(2);break;case"0xd505accf":a=o(1),s=i(2);break;case"0x8fcbaf0c":{a=o(1),s=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),a=o(1),s=i(2);break;default:throw new Error(`approval selector ${t} is recognised but not decodable; refusing to bound it`)}if(a==null||s==null)throw new Error("invalid approve calldata");return{spender:_r(a,"approval spender"),token:c==null?null:_r(c,"approval token"),amount:xn(s,"approval amount",{allowZero:!0}),selector:t,additive:Sn.has(t)}}import{createHash as bn,createHmac as yn,timingSafeEqual as vn}from"node:crypto";var An=2,Ke=300*1e3,Cr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function Tn(e){let r=e==null||e===""?Ke:Number(e);return!Number.isFinite(r)||r<0?Ke:Math.min(r,Cr)}function Xe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Xe).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Xe(e[t])}`).join(",")}}`}function Rr(e){let r=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return r.length>=16?r:""}function Fr(e=process.env){return Rr(process.env)||Rr(e)}function On(e=process.env){return String(process.env.ORACLE_STAMP_REQUIRE_MAC||"").trim()==="1"||String(e?.ORACLE_STAMP_REQUIRE_MAC||"").trim()==="1"}function In(e){let{oraclePrepared:r,prepareHash:t,prepareMac:n,note:o,...i}=e||{};return i}function Nn(e){let r=In(e);return bn("sha256").update(Xe(r)).digest("hex")}function Ln(e,r=Fr()){return r?yn("sha256",r).update(String(e)).digest("hex"):""}function kn(e,r){try{let t=Buffer.from(String(e),"hex"),n=Buffer.from(String(r),"hex");return t.length===0||t.length!==n.length?!1:vn(t,n)}catch{return!1}}function Mr(e,{maxAgeMs:r=Ke,nowMs:t=Date.now(),providers:n=null,kinds:o=null,label:i="operator",env:a=process.env}={}){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)!==An)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=Nn(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let c=Fr(a),u=String(e.prepareMac||"");if(On(a)||u||c){if(!c)throw new Error(`${i}: prepareMac present or ORACLE_STAMP_REQUIRE_MAC=1 but ORACLE_STAMP_HMAC_SECRET missing in signer`);let w=Ln(s,c);if(!u||!kn(u,w))throw new Error(`${i}: prepareMac mismatch \u2014 stamp not from trusted preparer`)}let l=Number(e.preparedAt),f=Number(e.expiresAt),d=Tn(r),p=t-l,m=f-l;if(!Number.isFinite(p)||!Number.isFinite(f)||!Number.isFinite(m)||p<0||m<=0||m>Cr||p>d||t>f)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${p}, max=${d})`);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 Te=e=>String(e||"").toLowerCase(),_n=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),Bn=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function J(e){try{return Bn.has(BigInt(e))}catch{return!1}}var q=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},Pr=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},pe=(e,r,t,n=String)=>{if(!Array.isArray(r)||r.length===0)throw new Error(`policy: ${t} allowlist is empty`);if(!r.map(n).includes(n(e)))throw new Error(`policy: ${t} not allowed`)};function Oe(e,r,{nowMs:t=Date.now(),networkFees:n,requireNetworkFees:o=!1}={}){if(!e||!r)throw new Error("policy: artifact and policy required");if(Object.keys(e).some(p=>!_n.has(p)))throw new Error("policy: unexpected EVM artifact field");if(e.gasPrice!=null&&(e.maxFeePerGas!=null||e.maxPriorityFeePerGas!=null))throw new Error("policy: ambiguous EVM fee fields");if(e.type!=null&&![0,1,2].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");let i=(p,m)=>{try{return BigInt(p)===BigInt(m)}catch{return String(p)===String(m)}};if(!Array.isArray(r.chains)||r.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!r.chains.some(p=>i(p,e.chainId)))throw new Error("policy: chain not allowed");if(pe(e.to,r.destinations,"destination",Te),pe(String(e.data||"0x").slice(0,10),r.selectors,"selector",p=>String(p).toLowerCase()),pe(e.from,r.owners,"owner",Te),W(e.data)){let p;try{p=de(e.data)}catch(w){throw new Error(`policy: malformed approval calldata: ${w?.message||w}`)}pe(p.spender,r.spenders,"spender",Te),pe(p.token||e.to,r.erc20Tokens,"ERC-20 token",Te);let m=q(r.maxApproval,"maxApproval");if(BigInt(p.amount)>m)throw new Error("policy: approval exceeds cap");if(p.additive)throw new Error("policy: additive approval cannot be bounded; use approve() with an absolute amount")}if(q(e.value,"value")>q(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=q(e.gasLimit,"gasLimit");if(a>q(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let s=e.maxFeePerGas??e.gasPrice,c=q(s,"feePerGas")*a,u=0n;try{if(J(e.chainId)&&(e.l1FeeWei===void 0||e.operatorFeeWei===void 0))throw new Error("missing")}catch{throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(e.l1FeeWei!==void 0&&(u+=q(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(u+=q(e.operatorFeeWei,"operatorFeeWei")),J(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=q(n.l1FeeWei,"estimated l1FeeWei")+q(n.operatorFeeWei,"estimated operatorFeeWei");if(u<p)throw new Error("policy: rollup fee attestation understates estimate")}if(c+u>q(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let f=Pr(r.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>f)throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=t)throw new Error("policy: artifact expired");let d=Pr(r.maxTtlMs??12e4,"maxTtlMs");if(d<=0||e.expiresAtMs-t>d)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as qr}from"node:crypto";import{Address as Rn,NETWORK as Cn,OutScript as $r,RawTx as Fn,SigHash as Ur,TEST_NETWORK as Mn,Transaction as Pn}from"@scure/btc-signer";var Dr=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},qn=(e,r)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${r}`);let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error(`envelope: invalid ${r}`);return t},$n=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,Un=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),Q=e=>Un(e)?String(e).toLowerCase():String(e),Ze=(e,r)=>Array.isArray(r)&&r.some(t=>Q(t)===Q(e)),Dn=(e,r)=>Buffer.from(e||[]).equals(Buffer.from(r||[]));function jn(e){let r=Buffer.from(Fn.encode(e)),t=qr("sha256").update(r).digest();return Buffer.from(qr("sha256").update(t).digest()).reverse().toString("hex")}function Wn(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(jn(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))throw new Error("envelope: Bitcoin prevout txid mismatch");let r=e.nonWitnessUtxo.outputs?.[e.index];if(!r)throw new Error("envelope: Bitcoin prevout output missing");if(!e.witnessUtxo)throw new Error("envelope: PSBT input witness UTXO required");if(BigInt(e.witnessUtxo.amount)!==BigInt(r.amount)||!Dn(e.witnessUtxo.script,r.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return r}function Ye(e,r){if(e.action!=="transfer")throw new Error("envelope: BTC decoder requires transfer action");let t=e?.artifact;if(Object.keys(t).some(f=>!["network","psbt"].includes(f)))throw new Error("envelope: unexpected BTC artifact field");if(!Ze(t.network,r.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(t.network).toLowerCase())?Cn:["testnet","signet","regtest"].includes(String(t.network).toLowerCase())?Mn:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Pn.fromPSBT(qn(t.psbt,"PSBT"))}catch(f){throw new Error(`envelope: invalid PSBT: ${f?.message||f}`)}if(o.inputsLength===0||o.outputsLength===0)throw new Error("envelope: PSBT inputs and outputs required");let i=Rn(n);for(let f=0;f<o.inputsLength;f++){let d=o.getInput(f);for(let w of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if($n(d[w]))throw new Error("envelope: signed or finalized PSBT refused");if(d.sighashType!==void 0&&d.sighashType!==Ur.DEFAULT&&d.sighashType!==Ur.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let p=Wn(d),m;try{let w=$r.decode(p.script);if(!["wpkh"].includes(w.type))throw new Error("unsupported input");m=i.encode(w)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!Ze(m,r.owners)||Q(m)!==Q(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...r.changeAddresses||[]].map(f=>Q(f))),s=0n,c=!1,u=[];for(let f=0;f<o.outputsLength;f++){let d=o.getOutput(f),p;try{p=i.encode($r.decode(d.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=Q(p);if(u.push(`${p}:${d.amount}`),m===Q(e.destination)){c=!0,s+=d.amount;continue}if(Ze(p,r.destinations)){s+=d.amount;continue}if(!a.has(m))throw new Error("policy: Bitcoin output destination not allowed")}if(!c)throw new Error("envelope: Bitcoin destination mismatch");let l;try{l=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(l<0n||l>Dr(r.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(s>Dr(r.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:s.toString(),notional:(s+l).toString(),fee:l.toString(),outputs:Object.freeze(u)})}function Qe(e,r){let{unit:t,value:n,notional:o,fee:i}=Ye(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}import{createHash as rr}from"node:crypto";import{base58 as Hr}from"@scure/base";import{getCompiledTransactionMessageDecoder as Jn}from"@solana/transaction-messages";var tr="11111111111111111111111111111111",Vn="ComputeBudget111111111111111111111111111111",Gn="So11111111111111111111111111111111111111112",zr="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var Kr="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Hn=5000n,zn=2039280n,Kn=37095705934669439343138083508754565189542113879843219016388785533085940283555n,k=57896044618658097711785492504343953926634992332820282019728792003956564819949n,jr=19681161376707505956807079304988542015446066515923890162744021073123829784752n,Wr=e=>rr("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Xn=new Map([[Wr("route"),{name:"route",prefixBytes:0}],[Wr("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),M=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},Zn=(e,r)=>{if(typeof e!="string"||e.length===0||e.length>131072||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`envelope: invalid ${r}`);let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error(`envelope: invalid ${r}`);return t},H=(e,r)=>Array.isArray(r)&&r.some(t=>String(t)===String(e)),$=e=>String(e||""),Yn=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,Ne=e=>rr("sha256").update(e).digest("hex");function Ie(e,r){try{let t=Buffer.from(Hr.decode(String(e||"")));if(t.length!==32)throw new Error("wrong length");return t}catch{throw new Error(`envelope: invalid Solana ${r}`)}}function F(e){let r=e%k;return r>=0n?r:k+r}function V(e,r){let t=e;for(;r-- >0n;)t=t*t%k;return t}function Qn(e){let t=e*e%k*e%k,n=V(t,2n)*t%k,o=V(n,1n)*e%k,i=V(o,5n)*o%k,a=V(i,10n)*i%k,s=V(a,20n)*a%k,c=V(s,40n)*s%k,u=V(c,80n)*c%k,l=V(u,80n)*c%k,f=V(l,10n)*i%k;return V(f,2n)*e%k}function eo(e,r){let t=F(r*r*r),n=F(t*t*r),o=Qn(e*n),i=F(e*t*o),a=F(r*i*i),s=i,c=F(i*jr),u=a===e,l=a===F(-e),f=a===F(-e*jr);return u&&(i=s),(l||f)&&(i=c),(F(i)&1n)===1n&&(i=F(-i)),!u&&!l?null:i}function ro(e){if(!e||e.length!==32)return!1;let r=0n;for(let o=31;o>=0;o--)r=(r<<8n)+BigInt(o===31?e[o]&127:e[o]);let t=F(r*r),n=eo(F(t-1n),F(Kn*t+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function to(e,r){let t=Buffer.concat([...e,Ie(r,"program id"),Buffer.from("ProgramDerivedAddress")]),n=rr("sha256").update(t).digest();if(ro(n))throw new Error("envelope: derived Solana program address is on curve");return Hr.encode(n)}function nr(e,r,t=zr){let n=[Ie(e,"owner"),Ie(t,"token program"),Ie(r,"mint")];for(let o=255;o>=0;o--)try{return to([...n,Buffer.from([o])],Kr)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function no(e,r){return(r.accountIndices||[]).map(t=>$(e.staticAccounts[t]))}function me(e){return Buffer.from(e.data||[])}function oo(e,r){return $(e.staticAccounts[r.programAddressIndex])}function Xr(e,r){return Number(r)<e.header.numSignerAccounts}function io(e,r){let t=e.header.numSignerAccounts,n=e.header.numReadonlySignerAccounts,o=e.header.numReadonlyNonSignerAccounts,i=e.staticAccounts.length;return Number(r)<t?Number(r)<t-n:Number(r)<i-o}function he(e){return e.accountIndices||[]}function er(e,r){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${r} allowlist required`);return e.map(String)}function Jr(e,r){let t=he(r).map(n=>{let o=Xr(e,n)?"s":"n",i=io(e,n)?"w":"r";return`${n}:${$(e.staticAccounts[n])}:${o}:${i}`});return Ne(Buffer.from(t.join(`
|
|
2
|
-
`)))}function Vr(e,r,t){if(r+8>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readBigUInt64LE(r)}function ao(e,r,t){if(r+2>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readUInt16LE(r)}function so(e,r,t){if(r+4>e.length)throw new Error(`envelope: malformed Jupiter ${t}`);return e.readUInt32LE(r)}function co(e,r,t){let n=t.maxJupiterRoutePlanSteps===void 0?1:Number(t.maxJupiterRoutePlanSteps);if(!Number.isSafeInteger(n)||n<1)throw new Error("policy: maxJupiterRoutePlanSteps must be a positive integer");if(r<1||r>n)throw new Error("policy: Jupiter route-plan step count exceeds reviewed cap");let o=Array.isArray(t.jupiterRouteVariants)?t.jupiterRouteVariants.map(Number):[];if(!o.length)throw new Error("policy: Jupiter route variant allowlist required");let i=t.jupiterRouteVariantPayloadBytes||{},a=0,s=0,c=[];for(let u=0;u<r;u++){if(a>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let l=e[a++];if(!o.includes(l))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(l)))throw new Error("policy: Jupiter route variant payload size required");let f=Number(i[String(l)]);if(!Number.isSafeInteger(f)||f<0||f>16)throw new Error("policy: Jupiter route variant payload size invalid");if(a+f+3>e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let d=e.subarray(a,a+f);a+=f;let p=d.toString("hex"),m=t.jupiterRouteVariantPayloads?.[String(l)];if(!Array.isArray(m)||!m.map(String).includes(p))throw new Error("policy: Jupiter route variant payload not allowed");let w=e[a++],x=e[a++],h=e[a++];if(w<1||w>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(x!==u||h!==u+1)throw new Error("envelope: unsupported Jupiter route-plan token index");s+=w,c.push(Object.freeze({swapVariant:l,variantPayloadHex:p,percent:w,inputIndex:x,outputIndex:h}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(s!==100*r)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function uo(e,r){let t=me({data:e}),n=t.subarray(0,8).toString("hex"),o=Xn.get(n);if(!o)throw new Error("envelope: unsupported Jupiter instruction discriminator");let i=19,a=o.prefixBytes===1?t[8]:null;if(o.prefixBytes===1&&t.length<9)throw new Error("envelope: malformed Jupiter shared route payload");let s=8+o.prefixBytes,c=s+4,u=t.length-i;if(u<=c)throw new Error("envelope: malformed Jupiter route payload");let l=so(t,s,"route plan length"),f=t.subarray(c,u),d=co(f,l,r);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:l,routePlan:d,routePlanHash:Ne(f),inAmount:Vr(t,u,"in_amount"),quotedOutAmount:Vr(t,u+8,"quoted_out_amount"),slippageBps:ao(t,u+16,"slippage_bps"),platformFeeBps:t[u+18],instructionHash:Ne(t)})}function fo(e,r,t){let n=no(e,r),o=(i,a)=>{let s=n[i];if(!s)throw new Error(`envelope: Jupiter ${a} account missing`);return s};if(t.instruction==="route"){if(n.length<9)throw new Error("envelope: Jupiter route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),userTransferAuthority:o(1,"userTransferAuthority"),userSourceTokenAccount:o(2,"userSourceTokenAccount"),userDestinationTokenAccount:o(3,"userDestinationTokenAccount"),destinationTokenAccount:o(4,"destinationTokenAccount"),destinationMint:o(5,"destinationMint"),platformFeeAccount:o(6,"platformFeeAccount"),eventAuthority:o(7,"eventAuthority"),program:o(8,"program")}}if(t.instruction==="shared_accounts_route"){if(n.length<13)throw new Error("envelope: Jupiter shared route account layout incomplete");return{tokenProgram:o(0,"tokenProgram"),programAuthority:o(1,"programAuthority"),userTransferAuthority:o(2,"userTransferAuthority"),userSourceTokenAccount:o(3,"sourceTokenAccount"),programSourceTokenAccount:o(4,"programSourceTokenAccount"),programDestinationTokenAccount:o(5,"programDestinationTokenAccount"),userDestinationTokenAccount:o(6,"destinationTokenAccount"),sourceMint:o(7,"sourceMint"),destinationMint:o(8,"destinationMint"),platformFeeAccount:o(9,"platformFeeAccount"),token2022Program:o(10,"token2022Program"),eventAuthority:o(11,"eventAuthority"),program:o(12,"program")}}throw new Error("envelope: unsupported Jupiter account layout")}function Gr(e,r){return e&&e!==r?e:null}function P(e,r,t){let n=$(e.staticAccounts[r]);if(!n)throw new Error(`envelope: Jupiter ${t} missing`);return n}function lo(e,r){let t=me(e);if(t.length===5&&t[0]===2){let n=t.readUInt32LE(1),o=r.maxComputeUnits===void 0?14e5:Number(r.maxComputeUnits);if(!Number.isSafeInteger(o)||o<=0)throw new Error("policy: maxComputeUnits must be positive");if(n>o)throw new Error("policy: Jupiter compute unit limit exceeds cap");return 0n}throw t.length===9&&t[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function po(e,r,t,n,o,i){let a=me(r);if(a.length!==1||a[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let s=he(r);if(s.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=P(e,s[0],"ATA payer"),u=P(e,s[1],"ATA account"),l=P(e,s[2],"ATA owner"),f=P(e,s[3],"ATA mint"),d=P(e,s[4],"ATA system program"),p=P(e,s[5],"ATA token program");if(c!==t.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(l!==t.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(d!==tr)throw new Error("envelope: Jupiter ATA system program mismatch");if(p!==o)throw new Error("envelope: Jupiter ATA token program mismatch");if(f!==n.inputMint&&f!==n.outputMint)throw new Error("envelope: Jupiter ATA mint mismatch");if(u!==nr(t.owner,f,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:u,debit:i}}function mo(e,r,t,n,o){let i=he(r),a=me(r);if(i.length!==2||a.length!==12||a.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let s=P(e,i[0],"wrap payer"),c=P(e,i[1],"wrap target"),u=a.readBigUInt64LE(4);if(s!==t.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(u!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return u}function ho(e,r,t,n){let o=he(r),i=me(r);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||P(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=P(e,o[0],"closeAccount source"),s=P(e,o[1],"closeAccount destination"),c=P(e,o[2],"closeAccount authority");if(a!==n||s!==t.owner||c!==t.owner)throw new Error("envelope: Jupiter closeAccount must return to owner");return{kind:"closeAccount"}}throw new Error("envelope: unsupported Jupiter token helper")}function wo(e,r,t,n,o,i,a){let s=nr(r.owner,r.artifact.inputMint,a);if(o.userSourceTokenAccount!==s)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=M(t.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<zn)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let u=new Map,l=0n,f=!1,d=!1;for(let p of e.instructions){if(p===n)continue;let m=oo(e,p);if(m===Vn)lo(p,t);else if(m===Kr){let{ata:w,debit:x}=po(e,p,r,r.artifact,a,c);u.set(w,x)}else if(m===tr)l+=mo(e,p,r,s,i);else if(m===a){let w=ho(e,p,r,s);w.kind==="syncNative"&&(f=!0),w.kind==="closeAccount"&&(d=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(l>0n&&(!f||!d))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(l!==0n&&l!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...u.values()].reduce((p,m)=>p+m,0n)}function go(e){let r;try{r=Jn().decode(Zn(e.messageBase64,"Solana message"))}catch(t){throw new Error(`envelope: invalid Solana message: ${t?.message||t}`)}if(r.version!=="legacy"&&Array.isArray(r.addressTableLookups)&&r.addressTableLookups.length)throw new Error("envelope: unresolved Solana address tables refused");return r}function Eo(e,r,t){if(e.header.numSignerAccounts!==1||$(e.staticAccounts[0])!==r.owner||!H(r.owner,t.owners))throw new Error("envelope: Solana owner mismatch");if(!Array.isArray(e.instructions)||e.instructions.length===0)throw new Error("envelope: Solana instructions required");let n=[];for(let o of e.instructions){let i=$(e.staticAccounts[o.programAddressIndex]);if(!i||!H(i,t.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function xo(e,r,t){let n=M(t.lamportsPerSignature,"lamportsPerSignature");if(n<Hn)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=t.maxLamportsPerSignature===void 0?n:M(t.maxLamportsPerSignature,"maxLamportsPerSignature");if(n>o)throw new Error("policy: Solana per-signature fee exceeds cap");let i=BigInt(e.header.numSignerAccounts),a=i*n,s=i*o;if(r.exactFeeLamports!==void 0){let u=M(r.exactFeeLamports,"exactFeeLamports");if(u<a)throw new Error("policy: Solana exact fee below the base signature fee");if(u>s)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=s;if(c>M(t.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function So(e,r,t,n){let o=0n,i=!1;for(let a of e.instructions){if($(e.staticAccounts[a.programAddressIndex])!==tr)throw new Error("envelope: unsupported Solana program decoder");let c=a.accountIndices||[];if(c.length!==2||$(e.staticAccounts[c[0]])!==r.owner)throw new Error("envelope: Solana transfer owner mismatch");let u=$(e.staticAccounts[c[1]]);if(u!==r.destination||!H(u,t.destinations))throw new Error("envelope: Solana destination mismatch");let l=Buffer.from(a.data||[]);if(l.length!==12||l.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=l.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>M(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function bo(e,r,t,n){let o=r.artifact;if(o.provider!=="jupiter")throw new Error("envelope: Solana swap provider must be jupiter");if(o.inputMint!==Gn)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==r.destination||!H(o.outputMint,t.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Yn(t);if(!H(o.inputMint,i)||!H(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=M(o.inAmount,"inAmount"),s=M(o.outAmount,"outAmount"),c=M(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>M(t.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>M(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(s<=0n||c<=0n||c>s)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(r.slippageBps))throw new Error("policy: Solana slippage mismatch");let u=$(o.jupiterProgram);if(!u||!H(u,t.programs)||!n.includes(u))throw new Error("policy: Jupiter program not allowed or absent");let l=e.instructions.filter(v=>$(e.staticAccounts[v.programAddressIndex])===u);if(l.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let f=l[0],d=uo(f.data,t);if(d.instruction==="shared_accounts_route"){let v=Array.isArray(t.jupiterSharedRouteIds)?t.jupiterSharedRouteIds.map(Number):[];if(!v.length)throw new Error("policy: Jupiter shared route id allowlist required");if(!v.includes(Number(d.routeId)))throw new Error("policy: Jupiter shared route id not allowed")}else if(d.routeId!=null)throw new Error("envelope: unexpected Jupiter shared route id");if(!er(t.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(d.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(d.inAmount!==a)throw new Error("envelope: Jupiter route in_amount mismatch");if(d.quotedOutAmount!==s)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(d.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let p=d.quotedOutAmount-d.quotedOutAmount*BigInt(d.slippageBps)/10000n;if(c!==p)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(d.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let m=fo(e,f,d),w=he(f),x=d.instruction==="shared_accounts_route"?2:1;if(!Xr(e,w[x]))throw new Error("envelope: Jupiter transfer authority must be signer");if(m.program!==u)throw new Error("envelope: Jupiter program account mismatch");if(m.userTransferAuthority!==r.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(m.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(m.sourceMint!==void 0&&m.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let h=Array.isArray(t.tokenPrograms)&&t.tokenPrograms.length?t.tokenPrograms:[zr];if(!H(m.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let E=nr(r.owner,o.outputMint,m.tokenProgram);if(m.userDestinationTokenAccount!==E)throw new Error("envelope: Jupiter destination token account is not owner ATA");let S=Gr(m.destinationTokenAccount,u);if(S&&S!==E)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(Gr(m.platformFeeAccount,u))throw new Error("policy: Jupiter platform fee account not allowed");if(!er(t.jupiterRouteAccountHashes,"Jupiter route account hash").includes(Jr(e,f)))throw new Error("policy: Jupiter route account hash not allowed");let y=Ne(Buffer.from([d.instruction,d.routeId??"",d.routePlanHash,Jr(e,f)].join(`
|
|
3
|
-
`)));if(!er(t.jupiterRouteReviewHashes,"Jupiter route review hash").includes(y))throw new Error("policy: Jupiter route review hash not allowed");let N=wo(e,r,t,f,m,a,m.tokenProgram),O=a+N;if(O>M(t.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:O,programs:n}}function or(e,r){if(e.action!=="transfer"&&e.action!=="swap")throw new Error("envelope: Solana decoder requires transfer or swap action");let t=e?.artifact,n=e.action==="transfer"?["cluster","messageBase64","exactFeeLamports"]:["cluster","provider","messageBase64","exactFeeLamports","inputMint","outputMint","inAmount","outAmount","otherAmountThreshold","slippageBps","jupiterProgram"];if(Object.keys(t||{}).some(c=>!n.includes(c)))throw new Error("envelope: unexpected Solana artifact field");if(!H(t.cluster,r.chains))throw new Error("policy: chain not allowed");let o=go(t),i=Eo(o,e,r),a=e.action==="transfer"?So(o,e,r,i):bo(o,e,r,i),s=xo(o,t,r);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+s).toString(),fee:s.toString(),programs:Object.freeze(a.programs)})}function ir(e,r){let{unit:t,value:n,notional:o,fee:i}=or(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}var Yr=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol"]);var sr=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0}),yo=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Qr=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"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),vo=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"}}),Ao=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 Le=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`envelope: bounded ${r} required`);return e},b=(e,r)=>{try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`envelope: ${r} must be a non-negative integer`)}},Zr=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},To=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${r} allowlist is empty`);return e},_=(e,r,t)=>{if(!To(r,t).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${t} not allowed`)},ar=(e,r,t)=>{Array.isArray(r)&&r.length&&_(e,r,t)},K=(e,r)=>{let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(t))throw new Error(`envelope: ${r} must be a 20-byte address`);return t},ie=e=>String(e||"0x").slice(0,10).toLowerCase(),et=e=>b(e.gasLimit,"gasLimit")*b(e.maxFeePerGas??e.gasPrice,"feePerGas")+b(e.l1FeeWei??0,"l1FeeWei")+b(e.operatorFeeWei??0,"operatorFeeWei");function we(e,r,t,{dynamicTail:n=!1}={}){let o=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(o)||o.length<10+r*64)throw new Error(`envelope: malformed ${t} calldata`);if(!n&&o.length!==10+r*64)throw new Error(`envelope: malformed ${t} calldata`);return{hex:o,word:i=>o.slice(10+i*64,10+(i+1)*64)}}function U(e,r){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${r} address`);return`0x${e.slice(24)}`}function z(e,r){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${r} integer`)}}function Oo(e){if(ie(e)!=="0x095ea7b3")return null;let r=we(e,2,"approval");return{kind:"approval",spender:U(r.word(0),"approval spender"),amount:z(r.word(1),"approval amount")}}function Io(e,r){let t=r==="router02-exact-input-single"?7:8,n=we(e,t,"Uniswap v3 exactInputSingle"),o=t===7?4:5;return{kind:"action",action:"swap",inputToken:U(n.word(0),"input token"),outputToken:U(n.word(1),"output token"),recipient:U(n.word(3),"recipient"),amountIn:z(n.word(o),"amountIn"),minimumOut:z(n.word(o+1),"amountOutMinimum")}}function No(e){let r=we(e,12,"Across depositV3",{dynamicTail:!0}),t=z(r.word(11),"message offset");if(t!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let n=10+Number(t)*2;if(r.hex.length<n+64)throw new Error("envelope: malformed Across depositV3 message");let o=Number(BigInt(`0x${r.hex.slice(n,n+64)}`));if(!Number.isSafeInteger(o))throw new Error("envelope: malformed Across depositV3 message length");let i=Math.ceil(o/32)*64;if(r.hex.length!==n+64+i)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:U(r.word(0),"depositor"),recipient:U(r.word(1),"recipient"),inputToken:U(r.word(2),"input token"),outputToken:U(r.word(3),"output token"),amountIn:z(r.word(4),"inputAmount"),minimumOut:z(r.word(5),"outputAmount"),destinationChainId:z(r.word(6),"destinationChainId")}}function Lo(e,r){let t=ie(e),n=Qr[t];if(!n)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(r).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed selector");if(n.action==="swap")return{...Io(e,n.layout),selector:t,provider:n.provider};if(n.action==="bridge")return{...No(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function ko(e){let r=we(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",contract:U(r.word(0),"mint NFT contract"),feeRecipient:U(r.word(1),"mint fee recipient"),recipient:U(r.word(2),"mint recipient"),quantity:z(r.word(3),"mint quantity")}}function _o(e,r){let t=ie(e);if(String(r).toLowerCase()==="nft-mint")return Bo(e);let n=vo[t];if(!n)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(String(r).toLowerCase()!==n.provider)throw new Error("envelope: provider does not match reviewed NFT selector");if(n.layout==="seadrop-mint-public")return{...ko(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function Bo(e){let r=ie(e);if(r==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let t=Ao[r];if(!t)throw new Error("envelope: opaque or unsupported NFT mint calldata");if(t.layout==="mint-no-args")return{kind:"mint",action:"mint",selector:r,provider:"nft-mint",quantity:1n};if(t.layout==="mint-quantity"){let n=we(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:r,provider:"nft-mint",quantity:z(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function ke(e){let r=e?.artifact;if(Array.isArray(r?.transactions))return r.transactions;if(r?.transaction&&typeof r.transaction=="object")return[r.transaction];if(r?.data)return[r];throw new Error("envelope: ordered EVM transaction batch required")}function rt(e,r,t,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=K(e.owner,"owner"),s=e.artifact,c=Number(s?.chainId??ke(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(_(c,r.chains,"chain"),s?.owner!==void 0&&K(s.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let u=ke(e);if(!u.length||u.length>8)throw new Error("envelope: bounded EVM transaction batch required");let l=0n,f=0n,d=0n;for(let p of u){if(!p||typeof p!="object"||Array.isArray(p))throw new Error("envelope: structured EVM transaction required");if(Number(p.chainId)!==c)throw new Error("envelope: every batch leg must use the same chain");if(K(p.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(_(ie(p.data),r.selectors,"selector"),l+=b(p.value??0,"value"),f+=b(p.gasLimit,"gasLimit"),d+=et(p),J(c)&&(p.l1FeeWei===void 0||p.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(l>b(r.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(f>b(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(d>b(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:u,chainId:c,owner:a,totalValue:l,totalGas:f,totalFee:d}}function tt(e,r,{nowMs:t=Date.now(),routeAttestationSecret:n}={}){let o=String(e?.surface||"");if(o!=="evm-swap"&&o!=="evm-bridge")throw new Error("envelope: strict EVM swap/bridge surface required");let i=Le(e.provider,"provider",64).toLowerCase();_(i,r.providers,"provider");let a=rt(e,r,o,{nowMs:t}),s=[],c=-1;for(let m=0;m<a.transactions.length;m++){let w=a.transactions[m],x=Oo(w.data),h;if(x){if(c!==-1)throw new Error("envelope: approval must be before action");if(b(w.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let y=K(w.to,"approval token");if(_(y,r.tokens,"token"),_(x.spender,r.spenders,"spender"),x.amount>b(r.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...x,token:y,index:m}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");_(w.to,r.destinations,"destination"),h={...Lo(w.data,i),target:K(w.to,"action target"),index:m},c=m}let E=b(w.value??0,"value"),S=b(w.gasLimit,"gasLimit");s.push({...h,value:E,gas:S,fee:et(w)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let u=s[c],l=o==="evm-swap"?"swap":"bridge";if(u.action!==l||e.action!==l)throw new Error("envelope: surface/action/calldata mismatch");if(K(e.destination,"destination")!==u.target)throw new Error("envelope: destination must equal decoded action target");if(u.recipient!==a.owner)throw new Error("envelope: decoded recipient must equal owner");if(u.depositor&&u.depositor!==a.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(_(u.inputToken,r.tokens,"input token"),_(u.outputToken,r.tokens,"output token"),u.amountIn<=0n||u.amountIn>b(r.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(u.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(ze(e.autoSlippage,{nowMs:t,chainId:a.chainId,venue:i,tx:a.transactions[c],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(u.minimumOut!==b(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(u.action==="bridge"&&b(e.toChainId,"toChainId")!==u.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let f=s.filter(m=>m.kind==="approval");if(!new Set([...yo,...Array.isArray(r.nativeInputTokens)?r.nativeInputTokens.map(m=>String(m).toLowerCase()):[]]).has(u.inputToken))throw new Error("envelope: strict local signer swap/bridge requires native input token; use wallet signing for token-unit rails");if(f.length)throw new Error("envelope: native-value action must not include token approval");if(u.value!==u.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let p=Object.freeze({quoteAmountOut:b(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:b(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...a,decoded:s,action:u,provider:i,authenticatedQuote:p}}function nt(e,r,{nowMs:t=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint action");let n=Le(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();ar(n,r.providers,"provider");let o=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;o?.oraclePrepared===!0&&Mr(o,{nowMs:t,providers:Array.isArray(r.providers)&&r.providers.length?r.providers:null,kinds:["nft-mint"],label:"local-signer"});let i=rt(e,r,"evm-nft",{nowMs:t});if(i.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let a=i.transactions[0],s=ie(a.data);_(s,r.selectors,"selector"),_(a.to,r.destinations,"destination");let c=_o(a.data,n),u=K(e.contract??e.artifact?.contract,"NFT contract");if(ar(u,r.nftContracts,"NFT contract"),(c.contract||K(a.to,"NFT contract"))!==u)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==i.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&ar(c.feeRecipient,r.nftFeeRecipients,"mint fee recipient");let f=b(e.quantity??e.artifact?.quantity,"quantity");if(f<=0n||f>b(r.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(c.quantity!==f)throw new Error("envelope: mint calldata quantity mismatch");let d=b(e.totalWei??e.artifact?.totalWei,"totalWei");if(i.totalValue!==d)throw new Error("envelope: mint value does not match declared totalWei");if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&b(e.priceWei??e.artifact.priceWei,"priceWei")*f!==d)throw new Error("envelope: mint price does not match declared totalWei");if(d>b(r.maxMintTotalWei??r.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...i,provider:n,decoded:[{...c,target:K(a.to,"mint target"),value:i.totalValue,gas:i.totalGas,fee:i.totalFee}]}}function Ro(e,{localsWaiver:r=!1}={}){if(!(e in sr))throw new Error("fee: unknown action");return r?0:sr[e]}function _e(e,r,{nowMs:t=Date.now(),verifyFeeWaiver:n,routeAttestationSecret:o,networkFees:i,requireNetworkFees:a=!1}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let s=Le(e.surface,"surface",16);if(!Yr.has(s))throw new Error("envelope: unsupported public surface");let c=Le(e.action,"action",32);_(s,r.surfaces,"surface"),_(c,r.actions,"action"),_(e.owner,r.owners,"owner"),_(e.destination,r.destinations,"destination");let u=Zr(r.maxTtlMs,"maxTtlMs"),l=Zr(r.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=t||e.expiresAtMs-t>u)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>l)throw new Error("policy: slippage exceeds cap");let f=e.artifact;if(!f||typeof f!="object"||Array.isArray(f))throw new Error("envelope: structured artifact required");if(s==="evm-swap"||s==="evm-bridge")tt(e,r,{nowMs:t,routeAttestationSecret:o});else if(s==="evm-nft")nt(e,r,{nowMs:t});else if(s==="evm"){if(!["transfer","approve"].includes(c))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(String(f.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(String(f.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: artifact from mismatch with owner");Oe({...f,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},r,{nowMs:t,networkFees:i,requireNetworkFees:a});let m=String(f.data||"0x").toLowerCase(),w=b(f.value,"EVM value");if(m==="0x"){if(w===0n)throw new Error("envelope: native EVM transfer value required")}else if(W(m)){if(w!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else s==="btc"?Qe(e,r):s==="sol"&&ir(e,r);let d=Number(e.fee?.oracleFeeBps)===0&&sr[c]!==0;if(e.fee?.waiver||d&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(d&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let p=Ro(c,{localsWaiver:d});if(Number(e.fee?.oracleFeeBps)!==p)throw new Error("fee: final artifact fee mismatch");return!0}var cr=Object.freeze([...Yr]),ns=Object.freeze({...Qr});function ur(e,r){if(e.surface==="btc")return Qe(e,r);if(e.surface==="sol")return ir(e,r);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let t=tt(e,r,{nowMs:Math.max(0,Number(e.expiresAtMs)-1),routeAttestationSecret:r.routeAttestationSecret}),n=t.totalValue.toString(),o=t.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(t.totalValue+t.totalFee).toString(),fee:o})}if(e.surface==="evm-nft"){let t=nt(e,r,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=t.totalValue.toString(),o=t.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(t.totalValue+t.totalFee).toString(),fee:o})}if(String(e.surface).startsWith("evm")){let t=b(e.artifact?.value,"EVM value"),n=b(e.artifact?.gasLimit,"EVM gasLimit"),o=b(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+b(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+b(e.artifact?.operatorFeeWei??0,"EVM operatorFeeWei");return Object.freeze({unit:"wei",value:t.toString(),notional:(t+i).toString(),fee:i.toString()})}throw new Error("envelope: unsupported public surface")}function ot(e={}){let r={};for(let t of cr){let n=e[t];if(n){if(typeof n.simulate!="function"||typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${t} requires simulate, sign, and broadcast functions`);r[t]=Object.freeze({simulate:(o,i)=>n.simulate(structuredClone(o),structuredClone(i)),sign:(o,i)=>n.sign(structuredClone(o),structuredClone(i)),broadcast:(o,i,a)=>n.broadcast(o,structuredClone(i),structuredClone(a))})}}return Object.freeze(r)}function Be(e,r){let t=e?.surface||"evm",n=r?.[t];if(!n)throw new Error(`adapter: ${t} is not configured on this self-host`);return n}import{createHash as it}from"node:crypto";import{ed25519 as Co}from"@noble/curves/ed25519.js";import{base58 as st}from"@scure/base";import{RawTx as fr,SigHash as ee,Transaction as lr}from"@scure/btc-signer";import{Transaction as dr}from"ethers";var ae=e=>{if(typeof e!="string"||e.length===0||e.length>262144||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return null;let r=Buffer.from(e,"base64");return r.toString("base64")===e?r:null},Re=e=>String(e||"").toLowerCase();function Fo(e,r){if(typeof e!="string")return!1;let t,n;try{t=dr.from(e),n=dr.from({chainId:r.chainId,to:r.to,data:r.data,value:r.value,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce,type:r.type,accessList:r.accessList})}catch{return!1}return Re(t.from)!==Re(r.from)||Re(t.to)!==Re(r.to)?!1:t.unsignedHash===n.unsignedHash}function Mo(e){let r=Buffer.from(fr.encode(e)),t=it("sha256").update(r).digest();return Buffer.from(it("sha256").update(t).digest()).reverse().toString("hex")}function at(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Mo(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))return!1;let r=e.nonWitnessUtxo.outputs?.[e.index];return r?BigInt(e.witnessUtxo.amount)===BigInt(r.amount)&&Buffer.from(e.witnessUtxo.script||[]).equals(Buffer.from(r.script||[])):!1}function Po(e,r){let t=ae(e),n=ae(r.psbt);if(!t||!n)return!1;try{let o=lr.fromPSBT(n),i=lr.fromPSBT(t);if(!Buffer.from(i.unsignedTx).equals(Buffer.from(o.unsignedTx))||i.inputsLength!==o.inputsLength)return!1;for(let a=0;a<i.inputsLength;a++){let s=i.getInput(a),c=o.getInput(a);if(!at(c)||!at(s))return!1;let u=(h,E)=>{if(h==null&&E==null)return!0;if(h==null||E==null)return!1;try{return Buffer.from(h).equals(Buffer.from(E))}catch{return!1}},l=(h,E)=>{if(h==null&&E==null)return!0;if(h==null||E==null)return!1;try{return Buffer.from(fr.encode(h)).equals(Buffer.from(fr.encode(E)))}catch{return u(h,E)}};if(!!s.witnessUtxo!=!!c.witnessUtxo||s.witnessUtxo&&(BigInt(s.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!u(s.witnessUtxo.script,c.witnessUtxo.script))||!l(s.nonWitnessUtxo,c.nonWitnessUtxo)||!u(s.redeemScript,c.redeemScript)||!u(s.witnessScript,c.witnessScript)||s.sighashType!==void 0&&s.sighashType!==ee.DEFAULT&&s.sighashType!==ee.ALL)return!1;let f=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===ee.ALL,d=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===ee.ALL:!1;for(let h of s.partialSig||[]){let E=Array.isArray(h)?h[1]:h;if(!f(E))return!1}if(s.tapKeySig&&!d(s.tapKeySig))return!1;for(let h of s.tapScriptSig||[]){let E=Array.isArray(h)?h[1]:h;if(!d(E))return!1}let p=h=>h[h.length-1]===ee.ALL,m=h=>h.length>=9&&h.length<=73&&h[1]===h.length-3&&h[2]===2,w=h=>{let E=!1;for(let S of h)if(S instanceof Uint8Array){if(S[0]===48){if(!m(S)||!p(S))return!1;E=!0;continue}if(S.length===64){E=!0;continue}if(S.length===65){if(S[64]!==ee.ALL&&S[64]!==ee.DEFAULT)return!1;E=!0}}return E};if(s.finalScriptWitness){let h;if(Array.isArray(s.finalScriptWitness))h=s.finalScriptWitness;else if(s.finalScriptWitness instanceof Uint8Array){let E=s.finalScriptWitness,S=O=>{let v=E[O];return v===void 0?null:v<253?{value:v,next:O+1}:v===253?{value:E[O+1]|E[O+2]<<8,next:O+3}:null},y=S(0);if(!y)return!1;h=[];let N=y.next;for(let O=0;O<y.value;O++){let v=S(N);if(!v||N+v.value>E.length)return!1;h.push(E.slice(v.next,v.next+v.value)),N=v.next+v.value}if(N!==E.length)return!1}else return!1;if(!h.length||!w(h))return!1}if(s.finalScriptSig instanceof Uint8Array&&s.finalScriptSig.length){let h=s.finalScriptSig,E=[],S=0;for(;S<h.length;){let y=h[S];if(y>=1&&y<=75){if(S+1+y>h.length)return!1;E.push(h.slice(S+1,S+1+y)),S+=1+y;continue}if(y===76){let N=h[S+1];if(N===void 0||S+2+N>h.length)return!1;E.push(h.slice(S+2,S+2+N)),S+=2+N;continue}return!1}if(!E.length||!w(E))return!1}if(![s.partialSig,s.tapKeySig,s.tapScriptSig,s.finalScriptSig,s.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function ct(e){let r=0,t=0,n=0;for(;n<e.length&&n<3;){let o=e[n++];if(r|=(o&127)<<t,(o&128)===0)return{value:r,offset:n};t+=7}return null}function qo(e,r,t){let n=ae(e),o=ae(r.messageBase64);if(!n||!o)return!1;let i=ct(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let s=n.subarray(i.offset,a),c=n.subarray(a);if(!c.equals(o))return!1;try{let u=st.decode(String(t));return u.length===32&&Co.verify(s,c,u)}catch{return!1}}function ut(e,r,t,n){return String(e).startsWith("evm")?Fo(r,t):e==="btc"?Po(r,t):e==="sol"?qo(r,t,n?.owner):!1}function ft(e,r){try{if(String(e).startsWith("evm"))return dr.from(r).hash;if(e==="btc"){let t=ae(r);if(!t)return null;let n=lr.fromPSBT(t);return n.finalize(),n.extract(),n.id}if(e==="sol"){let t=ae(r);if(!t)return null;let n=ct(t);if(!n||n.value!==1)return null;let o=t.subarray(n.offset,n.offset+64);return o.length===64?st.encode(o):null}}catch{}return null}var jo=e=>String(e||"").toLowerCase();function X(e){return $o("sha256").update(JSON.stringify(e)).digest("hex")}function mr(e,r,t={}){return Oe(e,r,t)}async function Wo(e,r={}){if(!J(e?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(typeof r.estimateNetworkFees!="function")throw new Error("policy: rollup fee estimate required");let t=await r.estimateNetworkFees(e);if(!t||t.l1FeeWei===void 0||t.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");return{l1FeeWei:String(t.l1FeeWei),operatorFeeWei:String(t.operatorFeeWei)}}function dt(e,r,t=!1){if(!J(e?.chainId))return!0;if(e.l1FeeWei===void 0||e.operatorFeeWei===void 0)throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei");if(t||r!=null){if(!r||r.l1FeeWei===void 0||r.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let n=BigInt(e.l1FeeWei)+BigInt(e.operatorFeeWei),o=BigInt(r.l1FeeWei)+BigInt(r.operatorFeeWei);if(n<o)throw new Error("policy: rollup fee attestation understates estimate")}return!0}var Ce=class{#e=new Map;constructor({now:r=Date.now}={}){this.now=r}issue({artifact:r,owner:t,ttlMs:n=6e4}){if(!Number.isFinite(n)||!Number.isInteger(n)||n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=Uo(32).toString("hex");return this.#e.set(o,{digest:X(r),owner:jo(t),expiresAtMs:this.now()+n}),o}consume(r,t){let n=this.#e.get(String(r));if(!n)throw new Error("confirmation: used or unknown nonce");if(n.expiresAtMs<=this.now())throw this.#e.delete(String(r)),new Error("confirmation: expired nonce");let o=Buffer.from(n.digest,"hex"),i=Buffer.from(X(t),"hex");if(!Do(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(r)),n}clear(){this.#e.clear()}};function Jo(e){let r=String(e?.data||"0x").toLowerCase(),t=BigInt(e?.value??0);if(r==="0x"){if(t<=0n)throw new Error("signer: native EVM transfer value required");return!0}if(W(r)){if(t!==0n)throw new Error("signer: EVM approval cannot transfer native value");return!0}throw new Error("signer: unsupported EVM calldata; use a versioned envelope")}function Vo(e={},r={}){let t={};for(let n of new Set([...Object.keys(e||{}),...Object.keys(r||{})]))t[n]=(BigInt(r?.[n]??0)-BigInt(e?.[n]??0)).toString();return t}function Fe(e,r){let t=String(r||"");if(String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(t);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(t);if(e==="sol")try{let n=lt.decode(t);return n.length===64&<.encode(n)===t}catch{return!1}return!1}function pt(e,r,t){return!Fe(e,r)||!Fe(e,t)?!1:e==="sol"?String(r)===String(t):String(r).toLowerCase()===String(t).toLowerCase()}function Go(e){let r=e?.confirmationMode;if(r!=="exact-human"&&r!=="auto-within-rails")throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");return r}async function pr({artifact:e,envelope:r,nonce:t,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:s}){let c=Go(o);if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(c!=="auto-within-rails")throw new Error("signer: autonomous execution requires auto-within-rails policy");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(r?.triggerAttestation,e,s())!==!0)throw new Error("signer: autonomous trigger attestation required");return i}if(c!=="exact-human")throw new Error("signer: non-autonomous execution requires exact-human exact confirmation policy");if(!n.confirmations)throw new Error("signer: exact-human confirmation store required");if(a)return n.confirmations.consume(t,e);if(!i||!Number.isFinite(i.expiresAtMs)||i.expiresAtMs<=s())throw new Error("confirmation: expired nonce");return i}function Ho(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function zo(e,r){return e&&Ho(e.surface)?ke(e):[r]}function Ko(e,r){let t=e?.hash??null,n=e?.transactionHash??null;if(t!=null&&n!=null&&!pt(r,t,n))throw new Error("signer: receipt reports conflicting transaction hashes");return t||n||null}function Xo(e,r){let t=e?.verifiedBefore??e?.before,n=e?.verifiedAfter??e?.after;return{transactionHash:r,status:e?.status,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:Vo(t,n)}}async function mt(e,r,t){if(!t.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:x,...h}=e||{};return h})(),i=zo(n,o),a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,s=()=>typeof t.nowMs=="function"?t.nowMs():t.nowMs??Date.now(),c=await pr({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:null,consumeNonce:!0,nowMs:s}),u=X(e),l=(x={})=>{n?_e(n,a,x):(mr(o,a,{nowMs:x.nowMs,networkFees:x.networkFees,requireNetworkFees:x.requireNetworkFees}),Jo(o))},f=async x=>{let h=n&&!String(n.surface||"").startsWith("evm")?void 0:await Wo(x,t);return{nowMs:s(),verifyFeeWaiver:t.verifyFeeWaiver,routeAttestationSecret:t.routeAttestationSecret,networkFees:h,requireNetworkFees:J(x?.chainId)}};l({nowMs:s(),verifyFeeWaiver:t.verifyFeeWaiver,routeAttestationSecret:t.routeAttestationSecret});for(let x of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof t[x]!="function")throw new Error(`signer: ${x} is required`);let d=t.reserveLedger(n||e,a);if(!d)throw new Error("signer: ledger reservation required");let p=!1,m=[];try{for(let x of i){if(typeof t.simulate!="function"||await t.simulate(x,n)!==!0)throw new Error("signer: strict affirmative simulation required");let h=await f(x);if(dt(x,h.networkFees,h.requireNetworkFees),!t.isArmed())throw new Error("signer: disarmed before signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=await pr({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:c,consumeNonce:!1,nowMs:s}),l(h),t.validateReservation(d,a,n&&typeof t.decodeEconomics=="function"?t.decodeEconomics(n,a):void 0),p=!0;let E=await t.sign(x,n);if(typeof t.verifySigned!="function"||await t.verifySigned(E,x,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!t.isArmed())throw new Error("signer: disarmed before broadcast");if(X(e)!==u)throw new Error("signer: artifact mutated after signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=await pr({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:c,consumeNonce:!1,nowMs:s});let S=await f(x);dt(x,S.networkFees,S.requireNetworkFees),l(S),t.validateReservation(d,a,n&&typeof t.decodeEconomics=="function"?t.decodeEconomics(n,a):void 0);let y=await t.broadcast(E,x,n),N=y?.status,O=n?.surface||"evm",v=Ko(y,O),Ve=ft(O,E);if(!pt(O,v,Ve))throw new Error("signer: receipt transaction hash does not match signed bytes");if(N===0||N==="0x0")throw Fe(O,v)?(t.settleFailedLedger(d),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(N!==1&&N!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Fe(O,v))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(Xo(y,v))}}catch(x){throw p||t.releaseLedger(d),x}if(t.commitLedger(d),m.length===1){let x={receipt:m[0]};return n?.surface==="evm-bridge"&&(x.originStatus="success",x.destinationStatus="unverified",x.destinationSuccess=!1,x.note="Origin-chain receipts do not prove destination-chain settlement."),x}let w={receipts:m,status:"success"};return n?.surface==="evm-bridge"&&(w.originStatus="success",w.destinationStatus="unverified",w.destinationSuccess=!1,w.note="Origin-chain receipts do not prove destination-chain settlement."),w}var ht=new Set(["127.0.0.1","::1","localhost"]),Qo=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&Yo(t,n)},B=(e,r,t)=>{let n=JSON.stringify(t);e.writeHead(r,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function ei(e){let r=String(e||"");if(r.startsWith("[")){let t=r.indexOf("]");if(t>1)return r.slice(1,t)}return r.split(":")[0]}var wt=e=>new Promise((r,t)=>{let n=0,o=[],i=!1;e.on("data",a=>{n+=a.length,n>64*1024&&!i?(i=!0,t(new Error("request refused")),e.resume()):i||o.push(a)}),e.on("end",()=>{if(!i)try{r(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{t(new Error("request refused"))}}),e.on("error",t)});function gt(e={}){let r=e.host||"127.0.0.1";if(!ht.has(r))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let i of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[i]!="function")throw new Error(`signer: ${i} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let t=e.confirmations||new Ce,n=e.origin||`http://${r}`;return Zo.createServer(async(i,a)=>{try{let s=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!Qo(s,e.token))return B(a,401,{error:"unauthorized"});let c=ei(i.headers.host);if(!ht.has(c))return B(a,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return B(a,403,{error:"origin refused"});if(i.method==="GET"&&i.url==="/status"){let u=typeof e.readPolicy=="function"?e.readPolicy():e.policy,l=new Set(cr),f=Array.isArray(u?.surfaces)?u.surfaces.filter(d=>typeof d=="string"&&l.has(d)):[];return B(a,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:f,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(i.method==="POST"&&i.url==="/disarm")return e.disarm(),t.clear(),B(a,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return B(a,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return B(a,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return B(a,403,{error:"autonomous signer does not issue human confirmation nonces"});let u=await wt(i),l=X(u.artifact),f=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(f?.confirmationMode!=="exact-human")return B(a,403,{error:"exact-human policy required"});let d=typeof e.nowMs=="function"?e.nowMs():Date.now();if(u.artifact?.version===1&&u.artifact?.surface)_e(u.artifact,f,{nowMs:d,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:p,...m}=u.artifact||{};mr(m,f,{nowMs:d})}return typeof e.confirmArtifact!="function"?B(a,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(u.artifact,l,f)!==!0?B(a,400,{error:"exact human confirmation refused"}):B(a,200,{confirmationNonce:t.issue({artifact:u.artifact,owner:u.artifact?.owner??u.artifact?.from,ttlMs:u.ttlMs})})}if(i.method==="POST"&&i.url==="/execute"){let u=await wt(i),l=await mt(u.artifact,u.confirmationNonce,{...e,confirmations:t});return B(a,200,l)}return B(a,404,{error:"not found"})}catch(s){return e.onError?.(String(s?.message||s)),B(a,400,{error:"request refused"})}})}import{createCipheriv as As,createDecipheriv as ri,randomBytes as ti,scryptSync as ni}from"node:crypto";import T from"node:fs";import se from"node:path";var oi="ORACLE-LOCAL-VAULT",ii=1,Pe=Object.freeze({N:1<<17,r:8,p:1}),ai=256*1024*1024,si=16*1024;function Me(e,r,t,{max:n=r}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${t} encoding`);let o=Buffer.from(e,"base64");if(o.toString("base64")!==e||o.length<r||o.length>n)throw new Error(`local-vault: invalid ${t} length`);return o}function ci(e,r,t=Pe){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return ni(n,r,32,{...t,maxmem:ai})}function Et(e,r){if(e?.magic!==oi||e?.version!==ii)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!==Pe.N||e.kdf.r!==Pe.r||e.kdf.p!==Pe.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(f=>!["address","addresses","kind","createdAt"].includes(f))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||JSON.stringify(e.meta.addresses||{}).length>1024||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let t=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(f=>!t.includes(f)))throw new Error("local-vault: unexpected vault field");let n=Me(e.kdf.salt,32,"salt"),o=Me(e.cipher.iv,12,"iv"),i=Me(e.tag,16,"tag"),a=Me(e.ciphertext,1,"ciphertext",{max:si}),{ciphertext:s,tag:c,...u}=e,l=ci(r,n);try{let f=ri("aes-256-gcm",l,o);return f.setAAD(Buffer.from(JSON.stringify(u))),f.setAuthTag(i),Buffer.concat([f.update(a),f.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{l.fill(0)}}function ui(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 fi(e){let r=se.dirname(e),t=T.lstatSync(r);if(!t.isDirectory()||t.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(t.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");if((t.mode&63)!==0)throw new Error("local-vault: destination directory must be owner-only (0700)");try{let n=T.lstatSync(e);if(n.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!n.isFile()||n.uid!==process.getuid?.()||n.nlink!==1)throw new Error("local-vault: unsafe destination file");if(n.dev!==t.dev)throw new Error("local-vault: destination device mismatch")}catch(n){if(n.code!=="ENOENT")throw n}}function I(e){let r;try{r=T.openSync(e,T.constants.O_RDONLY|T.constants.O_NOFOLLOW)}catch(t){throw t.code==="ELOOP"?new Error("local-vault: refusing symlink"):t}try{let t=T.fstatSync(r);if(ui(t),t.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=T.lstatSync(e);if(n.isSymbolicLink()||n.dev!==t.dev||n.ino!==t.ino)throw new Error("local-vault: secret source changed or is too large");return T.readFileSync(r,"utf8").replace(/[\r\n]+$/,"")}finally{T.closeSync(r)}}function xt(e){return JSON.parse(I(e))}function Y(e,r){T.mkdirSync(se.dirname(e),{recursive:!0,mode:448}),fi(e);let t=se.join(se.dirname(e),`.${se.basename(e)}.${process.pid}.${ti(6).toString("hex")}.tmp`);try{let n=T.openSync(t,T.constants.O_CREAT|T.constants.O_EXCL|T.constants.O_WRONLY|T.constants.O_NOFOLLOW,384);try{T.writeFileSync(n,String(r)),T.fsyncSync(n)}finally{T.closeSync(n)}T.renameSync(t,e),T.chmodSync(e,384);let o=T.openSync(se.dirname(e),"r");try{T.fsyncSync(o)}finally{T.closeSync(o)}}catch(n){try{T.unlinkSync(t)}catch{}throw n}}import{createHmac as di,randomBytes as pi,timingSafeEqual as mi}from"node:crypto";import R from"node:fs";import re from"node:path";import{homedir as hr}from"node:os";import{join as wr}from"node:path";var St=process.env.ORACLE_PUBLIC_DESKTOP==="1",li=St?process.env.ORACLE_CONFIG_DIR||wr(hr(),".config","oracle"):wr(hr(),".config","oracle"),ks=St?li:wr(hr(),".config","mad-desk");var Fs="0".repeat(64),Ms=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 qe(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(qe).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+qe(e[t])).join(",")+"}"}var Ps=Promise.resolve();function ce(e,r){if(!e)throw new Error("ledger: separate freshness anchor required");let t=a=>{try{return R.realpathSync(a)}catch{return re.resolve(a)}},n=t(re.dirname(re.resolve(e))),o=t(re.dirname(re.resolve(r))),i=(a,s)=>s===a||s.startsWith(a+re.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var hi=864e5,C=(e,r)=>di("sha256",r).update(qe(e)).digest("hex"),G=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&mi(t,n)},wi=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:r,...t}=e;return t};function gi(e,r){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!G(e.integrity.mac,C(e.policy,r)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Ue(e,r){if(!e)throw new Error("policy: sequence anchor required");let t;try{t=I(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(t)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!G(n?.integrity?.mac,C(n?.marker,r)))throw new Error("policy: sequence anchor integrity failed");return{sequence:Number(n?.marker?.policySequence||0),policyMac:n?.marker?.policyMac??null,present:!0,ledgerInitialized:n?.marker?.ledgerInitialized===!0}}function Ei(e,r,t,n=null,{ledgerInitialized:o}={}){if(n==null||!String(n))throw new Error("policy: sequence anchor must bind the sealed policy MAC");let i=o===!0;if(o===void 0)try{let s=Ue(e,t);i=s.present&&s.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(r),policyMac:String(n)};i&&(a.ledgerInitialized=!0),Y(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:C(a,t)}})+`
|
|
4
|
-
`)}function
|
|
5
|
-
`);let c={version:2,sequence:a.sequence,ledgerMac:s};
|
|
6
|
-
`);let u={version:1,sequence:a.sequence,ledgerMac:s};
|
|
7
|
-
`),o&&
|
|
8
|
-
`),
|
|
1
|
+
import Ga from"node:path";import Pe from"node:fs";import Nn from"node:os";import ue from"node:path";import{fileURLToPath as _n}from"node:url";var Bn=ue.dirname(_n(import.meta.url)),Qa=ue.resolve(Bn,"../..");function Jr(){return process.env.ORACLE_FAKE_HOME||Nn.homedir()}function Cn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function Re(){return Cn()?process.env.ORACLE_CONFIG_DIR||ue.join(Jr(),".config","oracle"):ue.join(Jr(),".config","oracle")}function Pn(){return ue.join(Re(),"desk.json")}function Rn(){return ue.join(Re(),"env")}function ce({force:e=!1}={}){if(ce._done&&!e)return ce._result||null;ce._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=Rn();if(Pe.existsSync(o))for(let i of Pe.readFileSync(o,"utf8").split(/\r?\n/)){let a=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),r(a[1],s)}}catch{}try{let o=Pn();if(Pe.existsSync(o)){let i=JSON.parse(Pe.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)),ce._result=Object.keys(t).length?t:null,ce._result}try{ce()}catch{}import yn from"node:fs";import J from"node:path";import La from"node:os";import{createHash as Na,randomBytes as _a}from"node:crypto";import{Transaction as Mr}from"@scure/btc-signer";import{ed25519 as Ba}from"@noble/curves/ed25519.js";import Qi from"node:http";import{timingSafeEqual as ea}from"node:crypto";import{createHash as Ui,randomBytes as ji,timingSafeEqual as Wi}from"node:crypto";import{base58 as Ht}from"@scure/base";import{Interface as Xn,MaxUint256 as Zn,isAddress as Qn,keccak256 as Fs,toUtf8Bytes as qs}from"ethers";import{Interface as Kn,isAddress as ys}from"ethers";import{isAddress as ds}from"ethers";import{createHash as Dn,createHmac as Un,timingSafeEqual as jn}from"node:crypto";import{readFileSync as Mn}from"node:fs";import{homedir as Fn}from"node:os";import{join as Me}from"node:path";function qn(){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=Fn();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||Me(t,".config","oracle")).trim();return[e,Me(r,"exec.env")].filter(Boolean)}return[e,Me(t,".config","oracle","exec.env"),Me(t,".config","mad-desk","exec.env")].filter(Boolean)}function be(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of qn())try{let i=Mn(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 le(e,t,r="guard"){let n=Number(t);if(t==null||!Number.isFinite(n))throw new Error(`${r}: current time must be a finite number (got ${$n(t)})`);let o=Number(e?.issuedAtMs),i=Number(e?.expiresAtMs);if(!Number.isFinite(i))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>i)throw new Error(`${r} expired at ${i}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(i<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:i}}function $n(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var Hr=100;function nr(e){return Array.isArray(e)?`[${e.map(nr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${nr(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function Wn(e,{required:t=!1}={}){try{return be(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function Jn(e){let{signature:t,...r}=e;return r}function Hn(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 Dn("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function Vn(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:jn(r,n)}function Gn(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 or(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 s=Wn(o,{required:a});if(a&&!s)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(s){let m=Un("sha256",s).update(nr(Jn(e))).digest("hex");if(!Vn(e.signature,m))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),u=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>Hr)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>Hr||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{le({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 f=BigInt(e.quoteAmountOut??0),l=BigInt(e.minAmountOut??0);if(f<=0n||l<=0n)throw new Error("auto-slippage guard amounts must be positive");let p=f*BigInt(1e4-c),d=p/10000n;if(p%10000n!==0n&&(d+=1n),l<d)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(i?.data&&e.minAmountOut!=null){let m=Gn(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==Hn(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 y=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${y}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(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 Ss=new Kn(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Yn,isAddress as Ts}from"ethers";var Ls=new Yn(["function approve(address spender,uint256 amount) returns (bool)"]),Ns=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function Vr(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=String(e??"").trim();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)}`)}}var Js=new Xn(["function approve(address spender,uint256 amount) returns (bool)"]);function Gr(e,t){let r=String(e||"").trim();if(!Qn(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function eo(e,t="approval amount",{allowZero:r=!1}={}){let n=Vr(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=Zn)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var zr=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),ro=new Set(["0x39509351","0xf9255c1f"]);function H(e){let t=String(e||"").toLowerCase();return t.length<10?!1:zr.has(t.slice(0,10))}function xe(e){if(!H(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=u=>n[u]?"0x"+n[u].slice(24):null,i=u=>n[u]?BigInt("0x"+n[u]):null,a=null,s=null,c=null;switch(r){case"0x095ea7b3":case"0x39509351":a=o(0),s=i(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":c=o(0),a=o(1),s=i(2);break;case"0xd505accf":a=o(1),s=i(2);break;case"0x8fcbaf0c":{a=o(1),s=i(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":c=o(0),a=o(1),s=i(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(a==null||s==null)throw new Error("invalid approve calldata");return{spender:Gr(a,"approval spender"),token:c==null?null:Gr(c,"approval token"),amount:eo(s,"approval amount",{allowZero:!0}),selector:r,additive:ro.has(r)}}import{createHash as to,createHmac as no,timingSafeEqual as oo}from"node:crypto";var io=2,ir=300*1e3,Yr=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function ao(e){let t=e==null||e===""?ir:Number(e);return!Number.isFinite(t)||t<0?ir:Math.min(t,Yr)}function ar(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ar).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ar(e[r])}`).join(",")}}`}function Kr(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function Xr(e=process.env){return Kr(process.env)||Kr(e)}function so(e=process.env){return String(process.env.ORACLE_STAMP_REQUIRE_MAC||"").trim()==="1"||String(e?.ORACLE_STAMP_REQUIRE_MAC||"").trim()==="1"}function co(e){let{oraclePrepared:t,prepareHash:r,prepareMac:n,note:o,...i}=e||{};return i}function uo(e){let t=co(e);return to("sha256").update(ar(t)).digest("hex")}function lo(e,t=Xr()){return t?no("sha256",t).update(String(e)).digest("hex"):""}function fo(e,t){try{let r=Buffer.from(String(e),"hex"),n=Buffer.from(String(t),"hex");return r.length===0||r.length!==n.length?!1:oo(r,n)}catch{return!1}}function Zr(e,{maxAgeMs:t=ir,nowMs:r=Date.now(),providers:n=null,kinds:o=null,label:i="operator",env:a=process.env}={}){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)!==io)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=uo(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let c=Xr(a),u=String(e.prepareMac||"");if(so(a)||u||c){if(!c)throw new Error(`${i}: prepareMac present or ORACLE_STAMP_REQUIRE_MAC=1 but ORACLE_STAMP_HMAC_SECRET missing in signer`);let y=lo(s,c);if(!u||!fo(u,y))throw new Error(`${i}: prepareMac mismatch \u2014 stamp not from trusted preparer`)}let f=Number(e.preparedAt),l=Number(e.expiresAt),p=ao(t),d=r-f,m=l-f;if(!Number.isFinite(d)||!Number.isFinite(l)||!Number.isFinite(m)||d<0||m<=0||m>Yr||d>p||r>l)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${p})`);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 Fe=e=>String(e||"").toLowerCase(),po=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),mo=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function V(e){try{return mo.has(BigInt(e))}catch{return!1}}var U=(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`)}},Qr=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},Se=(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 qe(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(d=>!po.has(d)))throw new Error("policy: unexpected EVM artifact field");if(e.gasPrice!=null&&(e.maxFeePerGas!=null||e.maxPriorityFeePerGas!=null))throw new Error("policy: ambiguous EVM fee fields");if(e.type!=null&&![0,1,2].includes(Number(e.type)))throw new Error("policy: unsupported EVM transaction type");let i=(d,m)=>{try{return BigInt(d)===BigInt(m)}catch{return String(d)===String(m)}};if(!Array.isArray(t.chains)||t.chains.length===0)throw new Error("policy: chain allowlist is empty");if(!t.chains.some(d=>i(d,e.chainId)))throw new Error("policy: chain not allowed");if(Se(e.to,t.destinations,"destination",Fe),Se(String(e.data||"0x").slice(0,10),t.selectors,"selector",d=>String(d).toLowerCase()),Se(e.from,t.owners,"owner",Fe),H(e.data)){let d;try{d=xe(e.data)}catch(y){throw new Error(`policy: malformed approval calldata: ${y?.message||y}`)}Se(d.spender,t.spenders,"spender",Fe),Se(d.token||e.to,t.erc20Tokens,"ERC-20 token",Fe);let m=U(t.maxApproval,"maxApproval");if(BigInt(d.amount)>m)throw new Error("policy: approval exceeds cap");if(d.additive)throw new Error("policy: additive approval cannot be bounded; use approve() with an absolute amount")}if(U(e.value,"value")>U(t.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=U(e.gasLimit,"gasLimit");if(a>U(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let s=e.maxFeePerGas??e.gasPrice,c=U(s,"feePerGas")*a,u=0n;try{if(V(e.chainId)&&(e.l1FeeWei===void 0||e.operatorFeeWei===void 0))throw new Error("missing")}catch{throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(e.l1FeeWei!==void 0&&(u+=U(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(u+=U(e.operatorFeeWei,"operatorFeeWei")),V(e.chainId)&&(o||n!=null)){if(!n||n.l1FeeWei===void 0||n.operatorFeeWei===void 0)throw new Error("policy: rollup fee estimate required");let d=U(n.l1FeeWei,"estimated l1FeeWei")+U(n.operatorFeeWei,"estimated operatorFeeWei");if(u<d)throw new Error("policy: rollup fee attestation understates estimate")}if(c+u>U(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let l=Qr(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 p=Qr(t.maxTtlMs??12e4,"maxTtlMs");if(p<=0||e.expiresAtMs-r>p)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as et}from"node:crypto";import{Address as ho,NETWORK as wo,OutScript as rt,RawTx as go,SigHash as tt,TEST_NETWORK as yo,Transaction as Eo}from"@scure/btc-signer";var nt=(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`)}},bo=(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},xo=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,So=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),ne=e=>So(e)?String(e).toLowerCase():String(e),sr=(e,t)=>Array.isArray(t)&&t.some(r=>ne(r)===ne(e)),Ao=(e,t)=>Buffer.from(e||[]).equals(Buffer.from(t||[]));function vo(e){let t=Buffer.from(go.encode(e)),r=et("sha256").update(t).digest();return Buffer.from(et("sha256").update(r).digest()).reverse().toString("hex")}function To(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(vo(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)||!Ao(e.witnessUtxo.script,t.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return t}function cr(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(!sr(r.network,t.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(r.network).toLowerCase())?wo:["testnet","signet","regtest"].includes(String(r.network).toLowerCase())?yo:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=Eo.fromPSBT(bo(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=ho(n);for(let l=0;l<o.inputsLength;l++){let p=o.getInput(l);for(let y of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(xo(p[y]))throw new Error("envelope: signed or finalized PSBT refused");if(p.sighashType!==void 0&&p.sighashType!==tt.DEFAULT&&p.sighashType!==tt.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let d=To(p),m;try{let y=rt.decode(d.script);if(!["wpkh"].includes(y.type))throw new Error("unsupported input");m=i.encode(y)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!sr(m,t.owners)||ne(m)!==ne(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...t.changeAddresses||[]].map(l=>ne(l))),s=0n,c=!1,u=[];for(let l=0;l<o.outputsLength;l++){let p=o.getOutput(l),d;try{d=i.encode(rt.decode(p.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=ne(d);if(u.push(`${d}:${p.amount}`),m===ne(e.destination)){c=!0,s+=p.amount;continue}if(sr(d,t.destinations)){s+=p.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 f;try{f=o.fee}catch{throw new Error("envelope: PSBT fee cannot be decoded")}if(f<0n||f>nt(t.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(s>nt(t.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:s.toString(),notional:(s+f).toString(),fee:f.toString(),outputs:Object.freeze(u)})}function ur(e,t){let{unit:r,value:n,notional:o,fee:i}=cr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}import{createHash as fr}from"node:crypto";import{base58 as ut}from"@scure/base";import{getCompiledTransactionMessageDecoder as Io}from"@solana/transaction-messages";var dr="11111111111111111111111111111111",ko="ComputeBudget111111111111111111111111111111",Oo="So11111111111111111111111111111111111111112",lt="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";var ft="ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",Lo=5000n,No=2039280n,_o=37095705934669439343138083508754565189542113879843219016388785533085940283555n,N=57896044618658097711785492504343953926634992332820282019728792003956564819949n,ot=19681161376707505956807079304988542015446066515923890162744021073123829784752n,it=e=>fr("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),Bo=new Map([[it("route"),{name:"route",prefixBytes:0}],[it("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]),$=(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`)}},Co=(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},K=(e,t)=>Array.isArray(t)&&t.some(r=>String(r)===String(e)),j=e=>String(e||""),Po=e=>Array.isArray(e.solMints)&&e.solMints.length?e.solMints:e.tokens,De=e=>fr("sha256").update(e).digest("hex");function $e(e,t){try{let r=Buffer.from(ut.decode(String(e||"")));if(r.length!==32)throw new Error("wrong length");return r}catch{throw new Error(`envelope: invalid Solana ${t}`)}}function q(e){let t=e%N;return t>=0n?t:N+t}function G(e,t){let r=e;for(;t-- >0n;)r=r*r%N;return r}function Ro(e){let r=e*e%N*e%N,n=G(r,2n)*r%N,o=G(n,1n)*e%N,i=G(o,5n)*o%N,a=G(i,10n)*i%N,s=G(a,20n)*a%N,c=G(s,40n)*s%N,u=G(c,80n)*c%N,f=G(u,80n)*c%N,l=G(f,10n)*i%N;return G(l,2n)*e%N}function Mo(e,t){let r=q(t*t*t),n=q(r*r*t),o=Ro(e*n),i=q(e*r*o),a=q(t*i*i),s=i,c=q(i*ot),u=a===e,f=a===q(-e),l=a===q(-e*ot);return u&&(i=s),(f||l)&&(i=c),(q(i)&1n)===1n&&(i=q(-i)),!u&&!f?null:i}function Fo(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=q(t*t),n=Mo(q(r-1n),q(_o*r+1n));return n===null?!1:!(n===0n&&(e[31]&128)!==0)}function qo(e,t){let r=Buffer.concat([...e,$e(t,"program id"),Buffer.from("ProgramDerivedAddress")]),n=fr("sha256").update(r).digest();if(Fo(n))throw new Error("envelope: derived Solana program address is on curve");return ut.encode(n)}function pr(e,t,r=lt){let n=[$e(e,"owner"),$e(r,"token program"),$e(t,"mint")];for(let o=255;o>=0;o--)try{return qo([...n,Buffer.from([o])],ft)}catch(i){if(!/on curve/.test(String(i?.message||i)))throw i}throw new Error("envelope: unable to derive associated token account")}function $o(e,t){return(t.accountIndices||[]).map(r=>j(e.staticAccounts[r]))}function Ae(e){return Buffer.from(e.data||[])}function Do(e,t){return j(e.staticAccounts[t.programAddressIndex])}function dt(e,t){return Number(t)<e.header.numSignerAccounts}function Uo(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 ve(e){return e.accountIndices||[]}function lr(e,t){if(!Array.isArray(e)||!e.length)throw new Error(`policy: ${t} allowlist required`);return e.map(String)}function at(e,t){let r=ve(t).map(n=>{let o=dt(e,n)?"s":"n",i=Uo(e,n)?"w":"r";return`${n}:${j(e.staticAccounts[n])}:${o}:${i}`});return De(Buffer.from(r.join(`
|
|
2
|
+
`)))}function st(e,t,r){if(t+8>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readBigUInt64LE(t)}function jo(e,t,r){if(t+2>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt16LE(t)}function Wo(e,t,r){if(t+4>e.length)throw new Error(`envelope: malformed Jupiter ${r}`);return e.readUInt32LE(t)}function Jo(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,s=0,c=[];for(let u=0;u<t;u++){if(a>=e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");let f=e[a++];if(!o.includes(f))throw new Error("policy: Jupiter route variant not allowed");if(!Object.hasOwn(i,String(f)))throw new Error("policy: Jupiter route variant payload size required");let l=Number(i[String(f)]);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 p=e.subarray(a,a+l);a+=l;let d=p.toString("hex"),m=r.jupiterRouteVariantPayloads?.[String(f)];if(!Array.isArray(m)||!m.map(String).includes(d))throw new Error("policy: Jupiter route variant payload not allowed");let y=e[a++],w=e[a++],h=e[a++];if(y<1||y>100)throw new Error("envelope: Jupiter route-plan percent invalid");if(w!==u||h!==u+1)throw new Error("envelope: unsupported Jupiter route-plan token index");s+=y,c.push(Object.freeze({swapVariant:f,variantPayloadHex:d,percent:y,inputIndex:w,outputIndex:h}))}if(a!==e.length)throw new Error("envelope: opaque or unsupported Jupiter route-plan payload");if(s!==100*t)throw new Error("envelope: Jupiter route-plan percent total mismatch");return Object.freeze(c)}function Ho(e,t){let r=Ae({data:e}),n=r.subarray(0,8).toString("hex"),o=Bo.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 s=8+o.prefixBytes,c=s+4,u=r.length-i;if(u<=c)throw new Error("envelope: malformed Jupiter route payload");let f=Wo(r,s,"route plan length"),l=r.subarray(c,u),p=Jo(l,f,t);return Object.freeze({instruction:o.name,routeId:a,routePlanSteps:f,routePlan:p,routePlanHash:De(l),inAmount:st(r,u,"in_amount"),quotedOutAmount:st(r,u+8,"quoted_out_amount"),slippageBps:jo(r,u+16,"slippage_bps"),platformFeeBps:r[u+18],instructionHash:De(r)})}function Vo(e,t,r){let n=$o(e,t),o=(i,a)=>{let s=n[i];if(!s)throw new Error(`envelope: Jupiter ${a} account missing`);return s};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 ct(e,t){return e&&e!==t?e:null}function D(e,t,r){let n=j(e.staticAccounts[t]);if(!n)throw new Error(`envelope: Jupiter ${r} missing`);return n}function Go(e,t){let r=Ae(e);if(r.length===5&&r[0]===2){let n=r.readUInt32LE(1),o=t.maxComputeUnits===void 0?14e5:Number(t.maxComputeUnits);if(!Number.isSafeInteger(o)||o<=0)throw new Error("policy: maxComputeUnits must be positive");if(n>o)throw new Error("policy: Jupiter compute unit limit exceeds cap");return 0n}throw r.length===9&&r[0]===3?new Error("policy: Jupiter priority fee not allowed"):new Error("envelope: unsupported Jupiter compute-budget helper")}function zo(e,t,r,n,o,i){let a=Ae(t);if(a.length!==1||a[0]!==1)throw new Error("envelope: unsupported Jupiter ATA helper");let s=ve(t);if(s.length!==6)throw new Error("envelope: malformed Jupiter ATA helper");let c=D(e,s[0],"ATA payer"),u=D(e,s[1],"ATA account"),f=D(e,s[2],"ATA owner"),l=D(e,s[3],"ATA mint"),p=D(e,s[4],"ATA system program"),d=D(e,s[5],"ATA token program");if(c!==r.owner)throw new Error("envelope: Jupiter ATA payer must equal owner");if(f!==r.owner)throw new Error("envelope: Jupiter ATA owner must equal owner");if(p!==dr)throw new Error("envelope: Jupiter ATA system program mismatch");if(d!==o)throw new Error("envelope: Jupiter ATA token program mismatch");if(l!==n.inputMint&&l!==n.outputMint)throw new Error("envelope: Jupiter ATA mint mismatch");if(u!==pr(r.owner,l,o))throw new Error("envelope: Jupiter ATA account mismatch");return{ata:u,debit:i}}function Ko(e,t,r,n,o){let i=ve(t),a=Ae(t);if(i.length!==2||a.length!==12||a.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Jupiter system helper");let s=D(e,i[0],"wrap payer"),c=D(e,i[1],"wrap target"),u=a.readBigUInt64LE(4);if(s!==r.owner||c!==n)throw new Error("envelope: unsupported Jupiter wrap transfer");if(u!==o)throw new Error("envelope: Jupiter wrap transfer amount mismatch");return u}function Yo(e,t,r,n){let o=ve(t),i=Ae(t);if(i.length!==1)throw new Error("envelope: unsupported Jupiter token helper");if(i[0]===17){if(o.length!==1||D(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=D(e,o[0],"closeAccount source"),s=D(e,o[1],"closeAccount destination"),c=D(e,o[2],"closeAccount authority");if(a!==n||s!==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 Xo(e,t,r,n,o,i,a){let s=pr(t.owner,t.artifact.inputMint,a);if(o.userSourceTokenAccount!==s)throw new Error("envelope: Jupiter source token account is not owner ATA");let c=$(r.jupiterAtaRentLamports,"jupiterAtaRentLamports");if(c<No)throw new Error("policy: Jupiter ATA rent below the token-account rent-exempt minimum");let u=new Map,f=0n,l=!1,p=!1;for(let d of e.instructions){if(d===n)continue;let m=Do(e,d);if(m===ko)Go(d,r);else if(m===ft){let{ata:y,debit:w}=zo(e,d,t,t.artifact,a,c);u.set(y,w)}else if(m===dr)f+=Ko(e,d,t,s,i);else if(m===a){let y=Yo(e,d,t,s);y.kind==="syncNative"&&(l=!0),y.kind==="closeAccount"&&(p=!0)}else throw new Error("envelope: unsupported Jupiter helper instruction")}if(f>0n&&(!l||!p))throw new Error("envelope: Jupiter native wrap helpers incomplete");if(f!==0n&&f!==i)throw new Error("envelope: Jupiter native wrap amount mismatch");return[...u.values()].reduce((d,m)=>d+m,0n)}function Zo(e){let t;try{t=Io().decode(Co(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 Qo(e,t,r){if(e.header.numSignerAccounts!==1||j(e.staticAccounts[0])!==t.owner||!K(t.owner,r.owners))throw new Error("envelope: Solana owner mismatch");if(!Array.isArray(e.instructions)||e.instructions.length===0)throw new Error("envelope: Solana instructions required");let n=[];for(let o of e.instructions){let i=j(e.staticAccounts[o.programAddressIndex]);if(!i||!K(i,r.programs))throw new Error("policy: Solana program not allowed");n.push(i)}return n}function ei(e,t,r){let n=$(r.lamportsPerSignature,"lamportsPerSignature");if(n<Lo)throw new Error("policy: Solana per-signature fee is below the network minimum");let o=r.maxLamportsPerSignature===void 0?n:$(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,s=i*o;if(t.exactFeeLamports!==void 0){let u=$(t.exactFeeLamports,"exactFeeLamports");if(u<a)throw new Error("policy: Solana exact fee below the base signature fee");if(u>s)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let c=s;if(c>$(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return c}function ri(e,t,r,n){let o=0n,i=!1;for(let a of e.instructions){if(j(e.staticAccounts[a.programAddressIndex])!==dr)throw new Error("envelope: unsupported Solana program decoder");let c=a.accountIndices||[];if(c.length!==2||j(e.staticAccounts[c[0]])!==t.owner)throw new Error("envelope: Solana transfer owner mismatch");let u=j(e.staticAccounts[c[1]]);if(u!==t.destination||!K(u,r.destinations))throw new Error("envelope: Solana destination mismatch");let f=Buffer.from(a.data||[]);if(f.length!==12||f.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=f.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>$(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:o,programs:n}}function ti(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!==Oo)throw new Error("envelope: Jupiter local signer requires native SOL input");if(o.outputMint!==t.destination||!K(o.outputMint,r.destinations))throw new Error("envelope: Jupiter output mint destination mismatch");let i=Po(r);if(!K(o.inputMint,i)||!K(o.outputMint,i))throw new Error("policy: Solana token not allowed");let a=$(o.inAmount,"inAmount"),s=$(o.outAmount,"outAmount"),c=$(o.otherAmountThreshold,"otherAmountThreshold");if(a<=0n||a>$(r.maxPerTradeLamports,"maxPerTradeLamports"))throw new Error("policy: Solana swap amount exceeds per-trade cap");if(a>$(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");if(s<=0n||c<=0n||c>s)throw new Error("envelope: Jupiter quote floor invalid");if(Number(o.slippageBps)!==Number(t.slippageBps))throw new Error("policy: Solana slippage mismatch");let u=j(o.jupiterProgram);if(!u||!K(u,r.programs)||!n.includes(u))throw new Error("policy: Jupiter program not allowed or absent");let f=e.instructions.filter(v=>j(e.staticAccounts[v.programAddressIndex])===u);if(f.length!==1)throw new Error("envelope: exactly one Jupiter swap instruction required");let l=f[0],p=Ho(l.data,r);if(p.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(p.routeId)))throw new Error("policy: Jupiter shared route id not allowed")}else if(p.routeId!=null)throw new Error("envelope: unexpected Jupiter shared route id");if(!lr(r.jupiterRoutePlanHashes,"Jupiter route-plan hash").includes(p.routePlanHash))throw new Error("policy: Jupiter route-plan hash not allowed");if(p.inAmount!==a)throw new Error("envelope: Jupiter route in_amount mismatch");if(p.quotedOutAmount!==s)throw new Error("envelope: Jupiter route quoted_out_amount mismatch");if(p.slippageBps!==Number(o.slippageBps))throw new Error("envelope: Jupiter route slippage mismatch");let d=p.quotedOutAmount-p.quotedOutAmount*BigInt(p.slippageBps)/10000n;if(c!==d)throw new Error("envelope: Jupiter otherAmountThreshold does not match serialized min-out");if(p.platformFeeBps!==0)throw new Error("policy: Jupiter platform fee not allowed");let m=Vo(e,l,p),y=ve(l),w=p.instruction==="shared_accounts_route"?2:1;if(!dt(e,y[w]))throw new Error("envelope: Jupiter transfer authority must be signer");if(m.program!==u)throw new Error("envelope: Jupiter program account mismatch");if(m.userTransferAuthority!==t.owner)throw new Error("envelope: Jupiter transfer authority must equal owner");if(m.destinationMint!==o.outputMint)throw new Error("envelope: Jupiter destination mint mismatch");if(m.sourceMint!==void 0&&m.sourceMint!==o.inputMint)throw new Error("envelope: Jupiter source mint mismatch");let h=Array.isArray(r.tokenPrograms)&&r.tokenPrograms.length?r.tokenPrograms:[lt];if(!K(m.tokenProgram,h))throw new Error("policy: Solana token program not allowed");let b=pr(t.owner,o.outputMint,m.tokenProgram);if(m.userDestinationTokenAccount!==b)throw new Error("envelope: Jupiter destination token account is not owner ATA");let E=ct(m.destinationTokenAccount,u);if(E&&E!==b)throw new Error("envelope: Jupiter optional destination account redirects proceeds");if(ct(m.platformFeeAccount,u))throw new Error("policy: Jupiter platform fee account not allowed");if(!lr(r.jupiterRouteAccountHashes,"Jupiter route account hash").includes(at(e,l)))throw new Error("policy: Jupiter route account hash not allowed");let S=De(Buffer.from([p.instruction,p.routeId??"",p.routePlanHash,at(e,l)].join(`
|
|
3
|
+
`)));if(!lr(r.jupiterRouteReviewHashes,"Jupiter route review hash").includes(S))throw new Error("policy: Jupiter route review hash not allowed");let I=Xo(e,t,r,l,m,a,m.tokenProgram),k=a+I;if(k>$(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");return{value:k,programs:n}}function mr(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(!K(r.cluster,t.chains))throw new Error("policy: chain not allowed");let o=Zo(r),i=Qo(o,e,t),a=e.action==="transfer"?ri(o,e,t,i):ti(o,e,t,i),s=ei(o,r,t);return Object.freeze({unit:"lamports",value:a.value.toString(),notional:(a.value+s).toString(),fee:s.toString(),programs:Object.freeze(a.programs)})}function hr(e,t){let{unit:r,value:n,notional:o,fee:i}=mr(e,t);return Object.freeze({unit:r,value:n,notional:o,fee:i})}var ni=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),oi=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),ii=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-stake-delegate":"delegate"}),ai=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-stake-delegate":"tokenDelegate"}),pt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`hl: bounded ${t} required`);return e};function mt(e){let t=String(e||"").replace(/\/$/,"");if(!ni.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function wr(e){return/^#\d+$/.test(String(e||""))}function si(e,t){let r=String(e||""),n=Array.isArray(t.coins)?t.coins.map(String):[];if(wr(r)){if(t.hip4===!1)throw new Error("hl: HIP-4 outcome orders are disabled by policy");if(n.includes(r)||n.includes("#*")||n.includes("*")||t.hip4===!0||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 ci(e,t,r){let n=Array.isArray(r.hlMarkets)?r.hlMarkets:[];if(n.length){if(!n.some(a=>{if(typeof a=="string"){let[s,c]=String(a).split(":");return s===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(wr(e)){let i=Array.isArray(r.coins)?r.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0||r.hip4===!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 Q(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=pt(r.kind,"kind",48),o=ii[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");if(mt(r.submitTo),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 i=Number(r.nonce);if(!Number.isSafeInteger(i)||i<=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(r.action.type!==ai[n])throw new Error("hl: action type must match kind");if(oi.has(n)||n==="perp-cancel"||n==="perp-leverage"||n==="perp-isolated-margin"){let a=pt(r.coin,"coin",64);si(a,t);let s=Number(r.assetId??r.assetIndex);if(!Number.isInteger(s)||s<0)throw new Error("hl: assetId required");if(ci(a,s,t),n==="hip4-order"&&!wr(a))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"){let c=Number(r.notionalUsd);if(!Number.isFinite(c)||c<=0)throw new Error("hl: notionalUsd required");if(c>Number(t.maxNotionalUsd))throw new Error("hl: notional exceeds cap");if(!["buy","sell"].includes(String(r.side)))throw new Error("hl: side must be buy or sell");if(r.action.type!=="order"||!Array.isArray(r.action.orders)||r.action.orders.length!==1)throw new Error("hl: exactly one signed order is required");let u=r.action.orders[0];if(Number(u.a)!==s)throw new Error("hl: signed asset must match assetId");if(!!u.b!=(r.side==="buy"))throw new Error("hl: signed side must match");if(String(u.s)!==String(r.size))throw new Error("hl: signed size must match");if(String(u.p)!==String(r.price))throw new Error("hl: signed price must match");let f=Number(u.s)*Number(u.p);if(!Number.isFinite(f)||Math.abs(f-c)>1e-6)throw new Error("hl: signed notional must match")}if(n==="perp-leverage"){let c=Number(r.leverage);if(!Number.isInteger(c)||c<1)throw new Error("hl: leverage must be a positive integer");if(c>Number(t.maxLeverage||50))throw new Error("hl: leverage exceeds cap")}if(n==="perp-cancel"){let c=r.action.cancels;if(!Array.isArray(c)||c.length!==1)throw new Error("hl: exactly one cancel is required");if(Number(c[0].a)!==s)throw new Error("hl: signed cancel asset must match assetId")}if(n==="perp-leverage"){if(Number(r.action.asset)!==s)throw new Error("hl: signed leverage asset must match assetId");if(Number(r.action.leverage)!==Number(r.leverage))throw new Error("hl: signed leverage must match")}if(n==="perp-isolated-margin"&&Number(r.action.asset)!==s)throw new Error("hl: signed margin asset must match assetId")}if(n.startsWith("hype-stake")&&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(r.notionalUsd??r.action.wei??0),notional:String(r.notionalUsd??0),fee:"0",kind:n,actionType:r.action.type,amount:String(r.action.wei??r.notionalUsd??0),coin:r.coin||null,submitTo:mt(r.submitTo)})}import{createHmac as ui}from"node:crypto";var fe="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 ht({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)),s=String(r||"").toUpperCase(),c=String(n||"");if(s!=="POST"||c!=="/order")throw new Error("poly: L2 headers are only built for POST /order");let u=a+s+c+String(o||""),f=String(e.secret).replace(/-/g,"+").replace(/_/g,"/"),l=Buffer.from(f,"base64"),p=ui("sha256",l).update(u).digest("base64").replace(/\+/g,"-").replace(/\//g,"_");return{POLY_ADDRESS:t,POLY_SIGNATURE:p,POLY_TIMESTAMP:a,POLY_API_KEY:e.key,POLY_PASSPHRASE:e.passphrase,"content-type":"application/json"}}function li(e,t){let r=Number(e.side)===0?"BUY":Number(e.side)===1?"SELL":null;if(!r)throw new Error("poly: side must be BUY or SELL");if(t&&t!==r)throw new Error("poly: side mismatch");return r}function wt(e,t){let r=BigInt(String(e.makerAmount)),n=BigInt(String(e.takerAmount));if(r<=0n||n<=0n)throw new Error("poly: order amounts must be positive integer micro-units");return Number(t==="BUY"?r:n)/1e6}function fi(e){let t=typeof e=="bigint"?e.toString(10):String(e??"").trim();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 gt({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=li(e,t);if(String(e.metadata||fe).toLowerCase()!==fe)throw new Error("poly: metadata must be zero");if(String(e.builder||fe).toLowerCase()!==fe)throw new Error("poly: builder must be zero");let a=fi(e.salt);return{deferExec:!1,order:{builder:fe,expiration:"0",maker:e.maker,makerAmount:String(e.makerAmount),metadata:fe,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 di=new Set(["https://clob.polymarket.com/order"]),Te=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),sc=Object.freeze(Te.map(e=>e[0])),pi=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),yt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`poly: bounded ${t} required`);return e};function Et(e){let t=String(e||"").replace(/\/$/,"");if(!di.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function bt(e){let t=String(e||"").toLowerCase();if(!pi.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function ee(e,t){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let r=e.artifact;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("poly: structured artifact required");let n=yt(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(String(e.destination).toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(Et(r.submitTo),Number(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"||String(o.version)!=="2"||Number(o.chainId)!==137)throw new Error("poly: EIP-712 domain must be official CTF Exchange v2 on Polygon");if(bt(o.verifyingContract),bt(r.exchange),String(o.verifyingContract).toLowerCase()!==String(r.exchange).toLowerCase())throw new Error("poly: exchange/domain mismatch");let i=r.message||r.value;if(!i||typeof i!="object")throw new Error("poly: signed order message required");let a=r.types?.Order;if(!Array.isArray(a)||a.length!==Te.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let d=0;d<Te.length;d+=1)if(a[d]?.name!==Te[d][0]||a[d]?.type!==Te[d][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 s=String(e.owner||"").toLowerCase();if(String(i.maker||"").toLowerCase()!==s)throw new Error("poly: maker must equal owner");if(String(i.signer||"").toLowerCase()!==s)throw new Error("poly: signer must equal owner");if(Number(i.signatureType)!==0)throw new Error("poly: only EOA signatureType 0 is public");if(![0,1].includes(Number(i.side)))throw new Error("poly: side must be BUY or SELL");let c=yt(String(r.tokenId||""),"tokenId",80);if(String(i.tokenId)!==c)throw new Error("poly: tokenId mismatch");let u=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(u.length&&!u.includes(c)&&!u.includes("*"))throw new Error("poly: tokenId not allowed");let f=Number(i.side)===0?"BUY":"SELL";if(r.side&&r.side!==f)throw new Error("poly: side mismatch");let l=wt(i,f),p=Number(r.notionalUsdc);if(!Number.isFinite(p)||Math.abs(p-l)>1e-6)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");if(l>Number(t.maxNotionalUsd??t.maxNotionalUsdc))throw new Error("poly: notional exceeds cap");return Object.freeze({unit:"usdc",value:String(l),notional:String(l),fee:"0",kind:n,tokenId:c,side:f,submitTo:Et(r.submitTo)})}var mi=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),Ie=14,xt=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`lighter: bounded ${t} required`);return e};function yr(e){let t=String(e||"").replace(/\/$/,"");if(!mi.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function re(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=xt(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=yr(r.submitTo),i=Number(r.marketIndex);if(!Number.isInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=xt(r.symbol||r.coin,"symbol",32),s=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(s.length&&!s.includes(a)&&!s.includes(String(i))&&!s.includes("*"))throw new Error("lighter: market not allowed");if(!["buy","sell"].includes(String(r.side)))throw new Error("lighter: side must be buy or sell");let c=Number(r.baseAmount),u=Number(r.price);if(!(c>0)||!(u>0))throw new Error("lighter: baseAmount and price required");let f=Number(r.sizeDecimals??0),l=Number(r.priceDecimals??0);if(!Number.isInteger(f)||f<0||f>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(l)||l<0||l>12)throw new Error("lighter: priceDecimals required");let p=c/10**f*(u/10**l),d=Number(r.notionalUsd);if(!Number.isFinite(d)||d<=0)throw new Error("lighter: notionalUsd required");if(!Number.isFinite(p)||Math.abs(p-d)>.01)throw new Error("lighter: notionalUsd must match size and price");if(p>Number(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER))throw new Error("lighter: notional exceeds cap");if(Number(r.txType??Ie)!==Ie)throw new Error("lighter: only official create-order txType is public");return Object.freeze({unit:"usd",value:String(d),notional:String(d),fee:"0",kind:n,symbol:a,marketIndex:i,side:r.side,baseAmount:c,price:u,submitTo:o,actionType:"create-order",amount:String(d)})}var vt=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var br=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0,delegate:0}),hi=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),Tt=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"}}),wi=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"}}),gi=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 Ue=(e,t,r=256)=>{if(typeof e!="string"||!e||e.length>r)throw new Error(`envelope: bounded ${t} required`);return e},x=(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`)}},St=(e,t)=>{let r=Number(e);if(!Number.isFinite(r))throw new Error(`policy: ${t} must be finite`);return r},yi=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${t} allowlist is empty`);return e},_=(e,t,r)=>{if(!yi(t,r).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${r} not allowed`)},Er=(e,t,r)=>{Array.isArray(t)&&t.length&&_(e,t,r)},Y=(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},oe=e=>String(e||"0x").slice(0,10).toLowerCase(),It=e=>x(e.gasLimit,"gasLimit")*x(e.maxFeePerGas??e.gasPrice,"feePerGas")+x(e.l1FeeWei??0,"l1FeeWei")+x(e.operatorFeeWei??0,"operatorFeeWei");function de(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 B(e,t){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${t} address`);return`0x${e.slice(24)}`}function W(e,t){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${t} integer`)}}function Ei(e){if(oe(e)!=="0x095ea7b3")return null;let t=de(e,2,"approval");return{kind:"approval",spender:B(t.word(0),"approval spender"),amount:W(t.word(1),"approval amount")}}function kt(e,t){let r=t==="router02-exact-input-single"?7:8,n=de(e,r,"Uniswap v3 exactInputSingle"),o=r===7?4:5;return{kind:"action",action:"swap",inputToken:B(n.word(0),"input token"),outputToken:B(n.word(1),"output token"),recipient:B(n.word(3),"recipient"),amountIn:W(n.word(o),"amountIn"),minimumOut:W(n.word(o+1),"amountOutMinimum")}}function bi(e){let t=de(e,12,"Across depositV3",{dynamicTail:!0}),r=W(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:B(t.word(0),"depositor"),recipient:B(t.word(1),"recipient"),inputToken:B(t.word(2),"input token"),outputToken:B(t.word(3),"output token"),amountIn:W(t.word(4),"inputAmount"),minimumOut:W(t.word(5),"outputAmount"),destinationChainId:W(t.word(6),"destinationChainId")}}function xi(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 At(e,{hasDeadline:t}){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<74)throw new Error("envelope: malformed exactInput calldata");let n=[];for(let w=10;w+64<=r.length;w+=64)n.push(r.slice(w,w+64));let o=(w,h)=>{if(!n[w])throw new Error(`envelope: malformed ${h}`);return BigInt(`0x${n[w]}`)},i=Number(o(0,"exactInput struct offset"));if(i%32!==0)throw new Error("envelope: malformed exactInput struct offset");let a=i/32,s=Number(o(a,"path offset")),c=n[a+1],u=o(a+(t?3:2),"amountIn"),f=o(a+(t?4:3),"amountOutMinimum"),l=a+s/32;if(!Number.isInteger(l)||!n[l])throw new Error("envelope: malformed exactInput path");let p=Number(o(l,"path length")),d=r.slice(10+(l+1)*64,10+(l+1)*64+p*2),{inputToken:m,outputToken:y}=xi(`0x${d}`);return{kind:"action",action:"swap",inputToken:m,outputToken:y,recipient:B(c,"recipient"),amountIn:u,minimumOut:f}}function Si(e){let t=de(e,8,"Aerodrome exactInputSingle");return{kind:"action",action:"swap",inputToken:B(t.word(0),"input token"),outputToken:B(t.word(1),"output token"),recipient:B(t.word(3),"recipient"),amountIn:W(t.word(5),"amountIn"),minimumOut:W(t.word(6),"amountOutMinimum")}}function Ai(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x5ae401dc"))throw new Error("envelope: malformed Uniswap multicall");let r=[];for(let p=10;p+64<=t.length;p+=64)r.push(t.slice(p,p+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]}`)),s=o+1+a/32,c=Number(BigInt(`0x${r[s]}`)),f=`0x${t.slice(10+(s+1)*64,10+(s+1)*64+c*2)}`,l=oe(f);if(l!=="0x04e45aaf"&&l!=="0x414bf389")throw new Error("envelope: multicall inner call must be exactInputSingle");return kt(f,l==="0x04e45aaf"?"router02-exact-input-single":"swap-router-exact-input-single")}function vi(e,t){let r=oe(e),n=Tt[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{...kt(e,n.layout),selector:r,provider:n.provider};if(n.layout==="exact-input-deadline")return{...At(e,{hasDeadline:!0}),selector:r,provider:n.provider};if(n.layout==="exact-input")return{...At(e,{hasDeadline:!1}),selector:r,provider:n.provider};if(n.layout==="multicall-deadline")return{...Ai(e),selector:r,provider:n.provider};if(n.layout==="aerodrome-exact-input-single")return{...Si(e),selector:r,provider:n.provider};if(n.action==="bridge")return{...bi(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Ti(e){let t=de(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",contract:B(t.word(0),"mint NFT contract"),feeRecipient:B(t.word(1),"mint fee recipient"),recipient:B(t.word(2),"mint recipient"),quantity:W(t.word(3),"mint quantity")}}function Ii(e,t){let r=oe(e);if(String(t).toLowerCase()==="nft-mint")return ki(e);let n=wi[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{...Ti(e),selector:r,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function ki(e){let t=oe(e);if(t==="0x40c10f19")throw new Error("envelope: ambiguous mint(address,uint256) calldata is not a built-in signer surface");let r=gi[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=de(e,1,"generic NFT mint");return{kind:"mint",action:"mint",selector:t,provider:"nft-mint",quantity:W(n.word(0),"mint quantity")}}throw new Error("envelope: unsupported generic NFT mint calldata")}function je(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 Ot(e,t,r,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=Y(e.owner,"owner"),s=e.artifact,c=Number(s?.chainId??je(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(_(c,t.chains,"chain"),s?.owner!==void 0&&Y(s.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let u=je(e);if(!u.length||u.length>8)throw new Error("envelope: bounded EVM transaction batch required");let f=0n,l=0n,p=0n;for(let d of u){if(!d||typeof d!="object"||Array.isArray(d))throw new Error("envelope: structured EVM transaction required");if(Number(d.chainId)!==c)throw new Error("envelope: every batch leg must use the same chain");if(Y(d.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(_(oe(d.data),t.selectors,"selector"),f+=x(d.value??0,"value"),l+=x(d.gasLimit,"gasLimit"),p+=It(d),V(c)&&(d.l1FeeWei===void 0||d.operatorFeeWei===void 0))throw new Error("policy: rollup EVM artifacts require l1FeeWei and operatorFeeWei")}if(f>x(t.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(l>x(t.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(p>x(t.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:u,chainId:c,owner:a,totalValue:f,totalGas:l,totalFee:p}}function Lt(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=Ue(e.provider,"provider",64).toLowerCase();_(i,t.providers,"provider");let a=Ot(e,t,o,{nowMs:r}),s=[],c=-1;for(let m=0;m<a.transactions.length;m++){let y=a.transactions[m],w=Ei(y.data),h;if(w){if(c!==-1)throw new Error("envelope: approval must be before action");if(x(y.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let S=Y(y.to,"approval token");if(_(S,t.tokens,"token"),_(w.spender,t.spenders,"spender"),w.amount>x(t.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");h={...w,token:S,index:m}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");_(y.to,t.destinations,"destination"),h={...vi(y.data,i),target:Y(y.to,"action target"),index:m},c=m}let b=x(y.value??0,"value"),E=x(y.gasLimit,"gasLimit");s.push({...h,value:b,gas:E,fee:It(y)})}if(c<0)throw new Error("envelope: reviewed swap/bridge action required");let u=s[c],f=o==="evm-swap"?"swap":"bridge";if(u.action!==f||e.action!==f)throw new Error("envelope: surface/action/calldata mismatch");if(Y(e.destination,"destination")!==u.target)throw new Error("envelope: destination must equal decoded action target");if(u.recipient!==a.owner)throw new Error("envelope: decoded recipient must equal owner");if(u.depositor&&u.depositor!==a.owner)throw new Error("envelope: decoded bridge depositor must equal owner");if(_(u.inputToken,t.tokens,"input token"),_(u.outputToken,t.tokens,"output token"),u.amountIn<=0n||u.amountIn>x(t.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(u.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(or(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(u.minimumOut!==x(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(u.action==="bridge"&&x(e.toChainId,"toChainId")!==u.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let l=s.filter(m=>m.kind==="approval");if(!new Set([...hi,...Array.isArray(t.nativeInputTokens)?t.nativeInputTokens.map(m=>String(m).toLowerCase()):[]]).has(u.inputToken))throw new Error("envelope: strict local signer swap/bridge requires native input token; use wallet signing for token-unit rails");if(l.length)throw new Error("envelope: native-value action must not include token approval");if(u.value!==u.amountIn)throw new Error("envelope: native value must exactly match decoded amountIn");let d=Object.freeze({quoteAmountOut:x(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:x(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{...a,decoded:s,action:u,provider:i,authenticatedQuote:d}}function Nt(e,t,{nowMs:r=Date.now()}={}){if(e?.surface!=="evm-nft")throw new Error("envelope: evm-nft surface required");if(!["mint","nft"].includes(e.action))throw new Error("envelope: evm-nft requires mint action");let n=Ue(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();Er(n,t.providers,"provider");let o=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;o?.oraclePrepared===!0&&Zr(o,{nowMs:r,providers:Array.isArray(t.providers)&&t.providers.length?t.providers:null,kinds:["nft-mint"],label:"local-signer"});let i=Ot(e,t,"evm-nft",{nowMs:r});if(i.transactions.length!==1)throw new Error("envelope: mint supports exactly one transaction");let a=i.transactions[0],s=oe(a.data);_(s,t.selectors,"selector"),_(a.to,t.destinations,"destination");let c=Ii(a.data,n),u=Y(e.contract??e.artifact?.contract,"NFT contract");if(Er(u,t.nftContracts,"NFT contract"),(c.contract||Y(a.to,"NFT contract"))!==u)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient&&c.recipient!==i.owner)throw new Error("envelope: mint calldata recipient mismatch");c.feeRecipient&&Er(c.feeRecipient,t.nftFeeRecipients,"mint fee recipient");let l=x(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>x(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 p=x(e.totalWei??e.artifact?.totalWei,"totalWei");if(i.totalValue!==p)throw new Error("envelope: mint value does not match declared totalWei");if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&x(e.priceWei??e.artifact.priceWei,"priceWei")*l!==p)throw new Error("envelope: mint price does not match declared totalWei");if(p>x(t.maxMintTotalWei??t.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...i,provider:n,decoded:[{...c,target:Y(a.to,"mint target"),value:i.totalValue,gas:i.totalGas,fee:i.totalFee}]}}function Oi(e,{localsWaiver:t=!1}={}){if(!(e in br))throw new Error("fee: unknown action");return t?0:br[e]}function We(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 s=Ue(e.surface,"surface",16);if(!vt.has(s))throw new Error("envelope: unsupported public surface");let c=Ue(e.action,"action",32);_(s,t.surfaces,"surface"),_(c,t.actions,"action"),_(e.owner,t.owners,"owner"),_(e.destination,t.destinations,"destination");let u=St(t.maxTtlMs,"maxTtlMs"),f=St(t.maxSlippageBps,"maxSlippageBps");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=r||e.expiresAtMs-r>u)throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>f)throw new Error("policy: slippage exceeds cap");let l=e.artifact;if(!l||typeof l!="object"||Array.isArray(l))throw new Error("envelope: structured artifact required");if(s==="evm-swap"||s==="evm-bridge")Lt(e,t,{nowMs:r,routeAttestationSecret:o});else if(s==="evm-nft")Nt(e,t,{nowMs:r});else if(s==="evm"){if(!["transfer","approve"].includes(c))throw new Error("envelope: generic evm requires transfer or approve; use strict evm-nft for mint action");if(c==="swap"||c==="bridge")throw new Error("envelope: surface/action mismatch; use strict decoded surface");if(String(l.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(String(l.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: artifact from mismatch with owner");qe({...l,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},t,{nowMs:r,networkFees:i,requireNetworkFees:a});let m=String(l.data||"0x").toLowerCase(),y=x(l.value,"EVM value");if(m==="0x"){if(y===0n)throw new Error("envelope: native EVM transfer value required")}else if(H(m)){if(y!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else s==="btc"?ur(e,t):s==="sol"?hr(e,t):s==="hl"?Q(e,t):s==="poly"?ee(e,t):s==="lighter"&&re(e,t);let p=Number(e.fee?.oracleFeeBps)===0&&br[c]!==0;if(e.fee?.waiver||p&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(p&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let d=Oi(c,{localsWaiver:p});if(Number(e.fee?.oracleFeeBps)!==d)throw new Error("fee: final artifact fee mismatch");return!0}var xr=Object.freeze([...vt]),Ec=Object.freeze({...Tt});function Sr(e,t){if(e.surface==="hl")return Q(e,t);if(e.surface==="poly")return ee(e,t);if(e.surface==="lighter")return re(e,t);if(e.surface==="btc")return ur(e,t);if(e.surface==="sol")return hr(e,t);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let r=Lt(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=Nt(e,t,{nowMs:Math.max(0,Number(e.expiresAtMs)-1)}),n=r.totalValue.toString(),o=r.totalFee.toString();return Object.freeze({unit:"wei",value:n,notional:(r.totalValue+r.totalFee).toString(),fee:o})}if(String(e.surface).startsWith("evm")){let r=x(e.artifact?.value,"EVM value"),n=x(e.artifact?.gasLimit,"EVM gasLimit"),o=x(e.artifact?.maxFeePerGas??e.artifact?.gasPrice,"EVM feePerGas"),i=n*o+x(e.artifact?.l1FeeWei??0,"EVM l1FeeWei")+x(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 _t(e={}){let t={};for(let r of xr){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 Je(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 Ft}from"node:crypto";import{ed25519 as Mi}from"@noble/curves/ed25519.js";import{base58 as Ut}from"@scure/base";import{RawTx as Ir,SigHash as ae,Transaction as kr}from"@scure/btc-signer";import{Transaction as Or,keccak256 as qt,verifyTypedData as $t}from"ethers";import{encode as Li}from"@msgpack/msgpack";import{keccak256 as Ni,verifyTypedData as _i}from"ethers";var pe=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Ar=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});function Bt(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 Bi(e,t,{vaultAddress:r=null,expiresAfter:n=null}={}){let i=[Buffer.from(Li(e)),Bt(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]),Bt(n)),Ni(Buffer.concat(i))}function vr(e,t,{isMainnet:r=!0,vaultAddress:n=null,expiresAfter:o=null}={}){return{source:r?"a":"b",connectionId:Bi(e,t,{vaultAddress:n,expiresAfter:o})}}function Ct(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=vr(e.action,e.nonce,{isMainnet:!String(e.submitTo||"").includes("testnet")});if(t.domain?.name!==pe.name||String(t.domain?.version)!==pe.version||Number(t.domain?.chainId)!==pe.chainId||String(t.domain?.verifyingContract||"").toLowerCase()!==String(pe.verifyingContract).toLowerCase())throw new Error("hl-l1: typedData domain must be Hyperliquid L1");if(JSON.stringify(t.types?.Agent||[])!==JSON.stringify(Ar.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 Pt({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=vr(t,r,{isMainnet:n,vaultAddress:o,expiresAfter:i});return await e.signTypedData(pe,Ar,a)}function Rt({signature:e,action:t,nonce:r,isMainnet:n=!0,owner:o,vaultAddress:i=null,expiresAfter:a=null}){try{let s=vr(t,r,{isMainnet:n,vaultAddress:i,expiresAfter:a}),c=_i(pe,Ar,s,e);return String(c).toLowerCase()===String(o).toLowerCase()}catch{return!1}}var Ci=[["AccountIndex","account_index","accountIndex"],["ApiKeyIndex","api_key_index","apiKeyIndex"],["ClientOrderIndex","client_order_index","clientOrderIndex"],["Type","type"],["TimeInForce","time_in_force","timeInForce"],["ReduceOnly","reduce_only","reduceOnly"],["TriggerPrice","trigger_price","triggerPrice"],["OrderExpiry","order_expiry","orderExpiry"],["ExpiredAt","expired_at","expiredAt"],["Nonce","nonce"],["Sig","sig","Signature","signature"]];function Tr(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)Tr(t);return}for(let t of Object.values(e))Tr(t)}}}function Pi(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 Tr(e),JSON.parse(JSON.stringify(e))}function ie(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 ke(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 Ri(e){let t={};for(let r of Ci){let n=r.filter(a=>e[a]!==void 0&&e[a]!==null);if(!n.length)continue;let o=n.map(a=>String(e[a]));if(new Set(o).size>1)throw new Error(`lighter: conflicting ${r[0]}`);let i=e[n[0]];if(typeof i=="function")throw new Error("lighter: signed tx_info cannot include functions");t[r[0]]=i}return t}function Oe(e,t){let r=Pi(t),n=ie(ke(r,["MarketIndex","market_index","marketIndex"],"MarketIndex"),"MarketIndex"),o=ie(ke(r,["BaseAmount","base_amount","baseAmount"],"BaseAmount"),"BaseAmount"),i=ie(ke(r,["Price","price"],"Price"),"Price");if(n!==ie(e.marketIndex,"marketIndex"))throw new Error("lighter: signed MarketIndex must match the prepared order");if(o!==ie(e.baseAmount,"baseAmount"))throw new Error("lighter: signed BaseAmount must match the prepared order");if(i!==ie(e.price,"price"))throw new Error("lighter: signed Price must match the prepared order");let a=ke(r,["IsAsk","is_ask","isAsk"],"IsAsk");if(a!==0&&a!==1&&a!=="0"&&a!=="1")throw new Error("lighter: signed IsAsk must be 0 or 1");let s=Number(a)===1,c=String(e.side)==="sell";if(s!==c)throw new Error("lighter: signed IsAsk must match the prepared side");let f=["txType","tx_type","TxType"].filter(m=>r[m]!==void 0&&r[m]!==null).length?Number(ie(ke(r,["txType","tx_type","TxType"],"txType"),"txType")):Number(e.txType??Ie);if(f!==Ie)throw new Error("lighter: signed txType must be official create-order");let l={...Ri(r),MarketIndex:Number(n),BaseAmount:Number(o),Price:Number(i),IsAsk:s?1:0,txType:f},p=JSON.stringify(l),d=JSON.parse(p);if(d.MarketIndex!==Number(n)||d.BaseAmount!==Number(o)||d.Price!==Number(i)||d.IsAsk!==(s?1:0)||d.txType!==f)throw new Error("lighter: canonical tx_info mutated");return{txType:f,txInfo:p,submitTo:yr(e.submitTo)}}function Mt(e){return new URLSearchParams({tx_type:String(e.txType),tx_info:e.txInfo}).toString()}var me=e=>{if(typeof e!="string"||e.length===0||e.length>262144||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return null;let t=Buffer.from(e,"base64");return t.toString("base64")===e?t:null},He=e=>String(e||"").toLowerCase();function Fi(e,t){if(typeof e!="string")return!1;let r,n;try{r=Or.from(e),n=Or.from({chainId:t.chainId,to:t.to,data:t.data,value:t.value,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce,type:t.type,accessList:t.accessList})}catch{return!1}return He(r.from)!==He(t.from)||He(r.to)!==He(t.to)?!1:r.unsignedHash===n.unsignedHash}function qi(e){let t=Buffer.from(Ir.encode(e)),r=Ft("sha256").update(t).digest();return Buffer.from(Ft("sha256").update(r).digest()).reverse().toString("hex")}function Dt(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||qi(e.nonWitnessUtxo)!==Buffer.from(e.txid||[]).toString("hex"))return!1;let t=e.nonWitnessUtxo.outputs?.[e.index];return t?BigInt(e.witnessUtxo.amount)===BigInt(t.amount)&&Buffer.from(e.witnessUtxo.script||[]).equals(Buffer.from(t.script||[])):!1}function $i(e,t){let r=me(e),n=me(t.psbt);if(!r||!n)return!1;try{let o=kr.fromPSBT(n),i=kr.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 s=i.getInput(a),c=o.getInput(a);if(!Dt(c)||!Dt(s))return!1;let u=(h,b)=>{if(h==null&&b==null)return!0;if(h==null||b==null)return!1;try{return Buffer.from(h).equals(Buffer.from(b))}catch{return!1}},f=(h,b)=>{if(h==null&&b==null)return!0;if(h==null||b==null)return!1;try{return Buffer.from(Ir.encode(h)).equals(Buffer.from(Ir.encode(b)))}catch{return u(h,b)}};if(!!s.witnessUtxo!=!!c.witnessUtxo||s.witnessUtxo&&(BigInt(s.witnessUtxo.amount)!==BigInt(c.witnessUtxo.amount)||!u(s.witnessUtxo.script,c.witnessUtxo.script))||!f(s.nonWitnessUtxo,c.nonWitnessUtxo)||!u(s.redeemScript,c.redeemScript)||!u(s.witnessScript,c.witnessScript)||s.sighashType!==void 0&&s.sighashType!==ae.DEFAULT&&s.sighashType!==ae.ALL)return!1;let l=h=>!(h instanceof Uint8Array)||h.length<9?!1:h[h.length-1]===ae.ALL,p=h=>h instanceof Uint8Array?h.length===64?!0:h.length===65&&h[64]===ae.ALL:!1;for(let h of s.partialSig||[]){let b=Array.isArray(h)?h[1]:h;if(!l(b))return!1}if(s.tapKeySig&&!p(s.tapKeySig))return!1;for(let h of s.tapScriptSig||[]){let b=Array.isArray(h)?h[1]:h;if(!p(b))return!1}let d=h=>h[h.length-1]===ae.ALL,m=h=>h.length>=9&&h.length<=73&&h[1]===h.length-3&&h[2]===2,y=h=>{let b=!1;for(let E of h)if(E instanceof Uint8Array){if(E[0]===48){if(!m(E)||!d(E))return!1;b=!0;continue}if(E.length===64){b=!0;continue}if(E.length===65){if(E[64]!==ae.ALL&&E[64]!==ae.DEFAULT)return!1;b=!0}}return b};if(s.finalScriptWitness){let h;if(Array.isArray(s.finalScriptWitness))h=s.finalScriptWitness;else if(s.finalScriptWitness instanceof Uint8Array){let b=s.finalScriptWitness,E=k=>{let v=b[k];return v===void 0?null:v<253?{value:v,next:k+1}:v===253?{value:b[k+1]|b[k+2]<<8,next:k+3}:null},S=E(0);if(!S)return!1;h=[];let I=S.next;for(let k=0;k<S.value;k++){let v=E(I);if(!v||I+v.value>b.length)return!1;h.push(b.slice(v.next,v.next+v.value)),I=v.next+v.value}if(I!==b.length)return!1}else return!1;if(!h.length||!y(h))return!1}if(s.finalScriptSig instanceof Uint8Array&&s.finalScriptSig.length){let h=s.finalScriptSig,b=[],E=0;for(;E<h.length;){let S=h[E];if(S>=1&&S<=75){if(E+1+S>h.length)return!1;b.push(h.slice(E+1,E+1+S)),E+=1+S;continue}if(S===76){let I=h[E+1];if(I===void 0||E+2+I>h.length)return!1;b.push(h.slice(E+2,E+2+I)),E+=2+I;continue}return!1}if(!b.length||!y(b))return!1}if(![s.partialSig,s.tapKeySig,s.tapScriptSig,s.finalScriptSig,s.finalScriptWitness].some(h=>Array.isArray(h)||h instanceof Uint8Array?h.length>0:h!=null))return!1}return!0}catch{return!1}}function jt(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 Di(e,t,r){let n=me(e),o=me(t.messageBase64);if(!n||!o)return!1;let i=jt(n);if(!i||i.value!==1||i.offset!==1)return!1;let a=i.offset+64;if(a>=n.length)return!1;let s=n.subarray(i.offset,a),c=n.subarray(a);if(!c.equals(o))return!1;try{let u=Ut.decode(String(r));return u.length===32&&Mi.verify(s,c,u)}catch{return!1}}function Wt(e,t,r,n){if(String(e).startsWith("evm"))return Fi(t,r);if(e==="btc")return $i(t,r);if(e==="sol")return Di(t,r,n?.owner);if(e==="hl"){if(r?.typedData?.domain&&r.typedData.types&&r.typedData.message)try{return String($t(r.typedData.domain,r.typedData.types,r.typedData.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}return Rt({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($t(r.domain,r.types,r.message,t)).toLowerCase()===String(n?.owner||"").toLowerCase()}catch{return!1}if(e==="lighter")try{return Oe(r,t),!0}catch{return!1}return!1}function Jt(e,t){try{if(String(e).startsWith("evm"))return Or.from(t).hash;if(e==="btc"){let r=me(t);if(!r)return null;let n=kr.fromPSBT(r);return n.finalize(),n.extract(),n.id}if(e==="sol"){let r=me(t);if(!r)return null;let n=jt(r);if(!n||n.value!==1)return null;let o=r.subarray(n.offset,n.offset+64);return o.length===64?Ut.encode(o):null}if(e==="hl"&&typeof t=="string"&&t.startsWith("0x"))return qt(t);if(e==="poly"&&typeof t=="string"&&t.startsWith("0x"))return qt(t)}catch{}return null}var Ji=e=>String(e||"").toLowerCase();function X(e){return Ui("sha256").update(JSON.stringify(e)).digest("hex")}function Nr(e,t,r={}){return qe(e,t,r)}async function Hi(e,t={}){if(!V(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 Vt(e,t,r=!1){if(!V(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 Ve=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=ji(32).toString("hex");return this.#e.set(o,{digest:X(t),owner:Ji(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(X(r),"hex");if(!Wi(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(t)),n}clear(){this.#e.clear()}};function Vi(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(H(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 Gi(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 Ge(e,t){let r=String(t||"");if(String(e).startsWith("evm"))return/^0x[0-9a-fA-F]{64}$/.test(r);if(e==="btc")return/^[0-9a-fA-F]{64}$/.test(r);if(e==="sol")try{let n=Ht.decode(r);return n.length===64&&Ht.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 Gt(e,t,r){return!Ge(e,t)||!Ge(e,r)?!1:e==="sol"?String(t)===String(r):String(t).toLowerCase()===String(r).toLowerCase()}function zi(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 Lr({artifact:e,envelope:t,nonce:r,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:s}){let c=zi(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,s())!==!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<=s())throw new Error("confirmation: expired nonce");return i}function Ki(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Yi(e,t){return e&&Ki(e.surface)?je(e):[t]}function Xi(e,t){let r=e?.hash??null,n=e?.transactionHash??null;if(r!=null&&n!=null&&!Gt(t,r,n))throw new Error("signer: receipt reports conflicting transaction hashes");return r||n||null}function Zi(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:Gi(r,n)}}async function zt(e,t,r){if(!r.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=n?n.artifact:(()=>{let{tradeId:w,...h}=e||{};return h})(),i=Yi(n,o),a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,s=()=>typeof r.nowMs=="function"?r.nowMs():r.nowMs??Date.now(),c=await Lr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:null,consumeNonce:!0,nowMs:s}),u=X(e),f=(w={})=>{n?We(n,a,w):(Nr(o,a,{nowMs:w.nowMs,networkFees:w.networkFees,requireNetworkFees:w.requireNetworkFees}),Vi(o))},l=async w=>{let h=n&&!String(n.surface||"").startsWith("evm")?void 0:await Hi(w,r);return{nowMs:s(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret,networkFees:h,requireNetworkFees:V(w?.chainId)}};f({nowMs:s(),verifyFeeWaiver:r.verifyFeeWaiver,routeAttestationSecret:r.routeAttestationSecret});for(let w of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof r[w]!="function")throw new Error(`signer: ${w} is required`);let p=r.reserveLedger(n||e,a);if(!p)throw new Error("signer: ledger reservation required");let d=!1,m=[];try{for(let w of i){if(typeof r.simulate!="function"||await r.simulate(w,n)!==!0)throw new Error("signer: strict affirmative simulation required");let h=await l(w);if(Vt(w,h.networkFees,h.requireNetworkFees),!r.isArmed())throw new Error("signer: disarmed before signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await Lr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:s}),f(h),r.validateReservation(p,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0),d=!0;let b=await r.sign(w,n);if(typeof r.verifySigned!="function"||await r.verifySigned(b,w,n)!==!0)throw new Error("signer: signed bytes do not match confirmed artifact");if(!r.isArmed())throw new Error("signer: disarmed before broadcast");if(X(e)!==u)throw new Error("signer: artifact mutated after signing");a=typeof r.readPolicy=="function"?r.readPolicy():r.policy,c=await Lr({artifact:e,envelope:n,nonce:t,deps:r,policy:a,confirmation:c,consumeNonce:!1,nowMs:s});let E=await l(w);Vt(w,E.networkFees,E.requireNetworkFees),f(E),r.validateReservation(p,a,n&&typeof r.decodeEconomics=="function"?r.decodeEconomics(n,a):void 0);let S=await r.broadcast(b,w,n),I=S?.status,k=n?.surface||"evm",v=Xi(S,k),ye=Jt(k,b);if(!Gt(k,v,ye))throw new Error("signer: receipt transaction hash does not match signed bytes");if(I===0||I==="0x0")throw Ge(k,v)?(r.settleFailedLedger(p),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(!Ge(k,v))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(Zi(S,v))}}catch(w){throw d||r.releaseLedger(p),w}if(r.commitLedger(p),m.length===1){let w={receipt:m[0]};return n?.surface==="evm-bridge"&&(w.originStatus="success",w.destinationStatus="unverified",w.destinationSuccess=!1,w.note="Origin-chain receipts do not prove destination-chain settlement."),w}let y={receipts:m,status:"success"};return n?.surface==="evm-bridge"&&(y.originStatus="success",y.destinationStatus="unverified",y.destinationSuccess=!1,y.note="Origin-chain receipts do not prove destination-chain settlement."),y}var Kt=new Set(["127.0.0.1","::1","localhost"]),ra=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&ea(r,n)},C=(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 ta(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 Yt=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 Xt(e={}){let t=e.host||"127.0.0.1";if(!Kt.has(t))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");for(let i of["reserveLedger","validateReservation","commitLedger","releaseLedger","settleFailedLedger"])if(typeof e[i]!="function")throw new Error(`signer: ${i} is required`);if(typeof e.disarm!="function")throw new Error("signer: disarm callback is required");let r=e.confirmations||new Ve,n=e.origin||`http://${t}`;return Qi.createServer(async(i,a)=>{try{let s=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!ra(s,e.token))return C(a,401,{error:"unauthorized"});let c=ta(i.headers.host);if(!Kt.has(c))return C(a,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return C(a,403,{error:"origin refused"});if(i.method==="GET"&&i.url==="/status"){let u=typeof e.readPolicy=="function"?e.readPolicy():e.policy,f=new Set(xr),l=Array.isArray(u?.surfaces)?u.surfaces.filter(p=>typeof p=="string"&&f.has(p)):[];return C(a,200,{ok:!0,service:"oracle-signer",armed:e.isArmed?.()===!0,surfaces:l,sessionExpiresAtMs:e.sessionExpiresAtMs||null})}if(i.method==="POST"&&i.url==="/disarm")return e.disarm(),r.clear(),C(a,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return C(a,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return C(a,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return C(a,403,{error:"autonomous signer does not issue human confirmation nonces"});let u=await Yt(i),f=X(u.artifact),l=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(l?.confirmationMode!=="exact-human")return C(a,403,{error:"exact-human policy required"});let p=typeof e.nowMs=="function"?e.nowMs():Date.now();if(u.artifact?.version===1&&u.artifact?.surface)We(u.artifact,l,{nowMs:p,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:d,...m}=u.artifact||{};Nr(m,l,{nowMs:p})}return typeof e.confirmArtifact!="function"?C(a,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(u.artifact,f,l)!==!0?C(a,400,{error:"exact human confirmation refused"}):C(a,200,{confirmationNonce:r.issue({artifact:u.artifact,owner:u.artifact?.owner??u.artifact?.from,ttlMs:u.ttlMs})})}if(i.method==="POST"&&i.url==="/execute"){let u=await Yt(i),f=await zt(u.artifact,u.confirmationNonce,{...e,confirmations:r});return C(a,200,f)}return C(a,404,{error:"not found"})}catch(s){return e.onError?.(String(s?.message||s)),C(a,400,{error:"request refused"})}})}import{createCipheriv as Gc,createDecipheriv as na,randomBytes as oa,scryptSync as ia}from"node:crypto";import T from"node:fs";import he from"node:path";var aa="ORACLE-LOCAL-VAULT",sa=1,Ke=Object.freeze({N:1<<17,r:8,p:1}),ca=256*1024*1024,ua=16*1024;function ze(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 la(e,t,r=Ke){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return ia(n,t,32,{...r,maxmem:ca})}function Zt(e,t){if(e?.magic!==aa||e?.version!==sa)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!==Ke.N||e.kdf.r!==Ke.r||e.kdf.p!==Ke.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=ze(e.kdf.salt,32,"salt"),o=ze(e.cipher.iv,12,"iv"),i=ze(e.tag,16,"tag"),a=ze(e.ciphertext,1,"ciphertext",{max:ua}),{ciphertext:s,tag:c,...u}=e,f=la(t,n);try{let l=na("aes-256-gcm",f,o);return l.setAAD(Buffer.from(JSON.stringify(u))),l.setAuthTag(i),Buffer.concat([l.update(a),l.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{f.fill(0)}}function fa(e){if(!e.isFile())throw new Error("local-vault: secret source must be a regular file");if(e.uid!==process.getuid?.())throw new Error("local-vault: secret source must be owned by this user");if(e.nlink!==1)throw new Error("local-vault: refusing hard-linked secret source");if((e.mode&63)!==0)throw new Error("local-vault: secret source must be owner-only (0600)")}function da(e){let t=he.dirname(e),r=T.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=T.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 O(e){let t;try{t=T.openSync(e,T.constants.O_RDONLY|T.constants.O_NOFOLLOW)}catch(r){throw r.code==="ELOOP"?new Error("local-vault: refusing symlink"):r}try{let r=T.fstatSync(t);if(fa(r),r.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=T.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 T.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{T.closeSync(t)}}function Qt(e){return JSON.parse(O(e))}function te(e,t){T.mkdirSync(he.dirname(e),{recursive:!0,mode:448}),da(e);let r=he.join(he.dirname(e),`.${he.basename(e)}.${process.pid}.${oa(6).toString("hex")}.tmp`);try{let n=T.openSync(r,T.constants.O_CREAT|T.constants.O_EXCL|T.constants.O_WRONLY|T.constants.O_NOFOLLOW,384);try{T.writeFileSync(n,String(t)),T.fsyncSync(n)}finally{T.closeSync(n)}T.renameSync(r,e),T.chmodSync(e,384);let o=T.openSync(he.dirname(e),"r");try{T.fsyncSync(o)}finally{T.closeSync(o)}}catch(n){try{T.unlinkSync(r)}catch{}throw n}}import{createHmac as ma,randomBytes as ha,timingSafeEqual as wa}from"node:crypto";import P from"node:fs";import se from"node:path";import{homedir as _r}from"node:os";import{join as Br}from"node:path";var en=process.env.ORACLE_PUBLIC_DESKTOP==="1",pa=en?process.env.ORACLE_CONFIG_DIR||Br(_r(),".config","oracle"):Br(_r(),".config","oracle"),Qc=en?pa:Br(_r(),".config","mad-desk");var ou="0".repeat(64),iu=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 Ye(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Ye).join(",")+"]":"{"+Object.keys(e).sort().map(r=>JSON.stringify(r)+":"+Ye(e[r])).join(",")+"}"}var au=Promise.resolve();function we(e,t){if(!e)throw new Error("ledger: separate freshness anchor required");let r=a=>{try{return P.realpathSync(a)}catch{return se.resolve(a)}},n=r(se.dirname(se.resolve(e))),o=r(se.dirname(se.resolve(t))),i=(a,s)=>s===a||s.startsWith(a+se.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var ga=864e5,F=(e,t)=>ma("sha256",t).update(Ye(e)).digest("hex"),z=(e,t)=>{let r=Buffer.from(String(e)),n=Buffer.from(String(t));return r.length===n.length&&wa(r,n)},ya=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:t,...r}=e;return r};function Ea(e,t){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!z(e.integrity.mac,F(e.policy,t)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function Ze(e,t){if(!e)throw new Error("policy: sequence anchor required");let r;try{r=O(e)}catch{return{sequence:0,present:!1}}let n;try{n=JSON.parse(r)}catch{throw new Error("policy: sequence anchor is unreadable")}if(!z(n?.integrity?.mac,F(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 ba(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 s=Ze(e,r);i=s.present&&s.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(t),policyMac:String(n)};i&&(a.ledgerInitialized=!0),te(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:F(a,r)}})+`
|
|
4
|
+
`)}function xa(e,t){let r=Ze(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 ba(e,r.sequence,t,r.policyMac,{ledgerInitialized:!0}),!0}function rn(e,t,{sequenceAnchorFile:r}={}){if(!r)throw new Error("policy: sequence anchor required");let n=O(t),o;try{o=JSON.parse(O(e))}catch(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=Ea(o,n);we(r,e);let a=Ze(r,n),s=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(s!==a.sequence)throw new Error("policy: rolled back to a superseded policy");if(a.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!z(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Ne(e,t,r,n,o){let i=`${e}.continuity`,a;try{let s=JSON.parse(O(e));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!z(s?.integrity?.mac,F(s.ledger,t)))throw new Error("integrity verification failed");if(a=s.ledger,!Number.isFinite(a?.windowStartMs)||!Array.isArray(a?.entries)||a.sequence!==void 0&&(!Number.isSafeInteger(a.sequence)||a.sequence<0))throw new Error("invalid ledger")}catch(s){if(s?.code==="ENOENT"){if(P.existsSync(i)||P.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=Ze(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: ${s?.message||s}`)}try{let s=JSON.parse(O(i));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!z(s?.integrity?.mac,F(s.marker,t)))throw new Error("continuity verification failed");if(s.marker?.version===2&&(s.marker.sequence!==a.sequence||!z(s.marker.ledgerMac,F(a,t))))throw new Error("continuity rollback detected");if(s.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(P.existsSync(n)&&(s.marker?.version!==2||a.sequence===void 0))throw new Error("legacy ledger rollback detected after checkpoint initialization");if(s.marker?.version===2){let c=JSON.parse(O(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!z(c?.integrity?.mac,F(c.marker,t))||c.marker?.version!==1||c.marker.sequence!==a.sequence||!z(c.marker.ledgerMac,F(a,t)))throw new Error("checkpoint rollback detected")}}catch(s){throw new Error(`ledger: corrupt or unreadable: ${s?.message||s}`)}if(r-a.windowStartMs>=ga){let s=a.entries.map(c=>c.state==="reserved"?c:{...c,state:"consumed",value:"0",notional:"0"});return{windowStartMs:r,entries:s,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function Xe(e,t,r){return e.filter(n=>(n.unit||"wei")===r).reduce((n,o)=>n+BigInt(o[t]??0),0n)}function tn(e,t){let r=t==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:t==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:t==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:null;if(!r)throw new Error("ledger: unsupported accounting unit");for(let n of r)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return r.map(n=>BigInt(e[n]))}function _e(e,t){let r=`${e}.lock`,n=ha(16).toString("hex"),o;try{o=P.openSync(r,P.constants.O_CREAT|P.constants.O_EXCL|P.constants.O_WRONLY|(P.constants.O_NOFOLLOW||0),384),P.writeFileSync(o,n),P.fsyncSync(o)}catch(i){throw o!==void 0&&P.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return t()}finally{P.closeSync(o);try{O(r)===n&&P.unlinkSync(r)}catch{}}}function Le(e,t,r,n,o){let i=`${e}.continuity`,a={...t,sequence:(t.sequence??0)+1},s=F(a,r);te(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:s}})+`
|
|
5
|
+
`);let c={version:2,sequence:a.sequence,ledgerMac:s};te(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:F(c,r)}})+`
|
|
6
|
+
`);let u={version:1,sequence:a.sequence,ledgerMac:s};P.mkdirSync(se.dirname(n),{recursive:!0,mode:448}),te(n,JSON.stringify({marker:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:F(u,r)}})+`
|
|
7
|
+
`),o&&xa(o,r)}function nn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:s=0,fee:c,policy:u,nowMs:f=Date.now()}){let l=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(l))throw new Error("ledger: bounded tradeId required");we(r,e);let p=O(t);return _e(e,()=>{let d=Ne(e,p,f,r,n);if(d.entries.some(S=>String(S.tradeId)===l))throw new Error("ledger: replayed tradeId");let m=BigInt(a),y=BigInt(s),[w,h,b]=tn(u,i);if(m<0n||y<0n||y>b)throw new Error("ledger: per-trade cap exceeded");if(Xe(d.entries,"value",i)+m>w||Xe(d.entries,"notional",i)+y>h)throw new Error("ledger: daily cap exceeded");let E={tradeId:l,unit:i,value:m.toString(),notional:y.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:f};return d.entries.push(E),Le(e,d,p,r,n),structuredClone(E)})}function on({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:s=Date.now()}){we(r,e);let c=O(t);return _e(e,()=>{let u=Ne(e,c,s,r,n),f=u.entries.find(y=>String(y.tradeId)===String(o?.tradeId??"")&&y.state==="reserved");if(!f||f.unit!==o.unit||f.value!==o.value||f.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==f.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(f.value)||BigInt(a.notional)>BigInt(f.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let l=f.unit||"wei",[p,d,m]=tn(i,l);if(BigInt(f.notional)>m)throw new Error("ledger: per-trade cap exceeded");if(Xe(u.entries,"value",l)>p||Xe(u.entries,"notional",l)>d)throw new Error("ledger: daily cap exceeded");return structuredClone(f)})}function an({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){we(r,e);let a=O(t);return _e(e,()=>{let s=Ne(e,a,i,r,n),c=s.entries.find(u=>String(u.tradeId)===String(o??"")&&u.state==="reserved");if(!c||c.state!=="reserved")throw new Error("ledger: reservation unavailable");return c.state="committed",c.committedAtMs=i,Le(e,s,a,r,n),structuredClone(c)})}function sn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){we(r,e);let a=O(t);return _e(e,()=>{let s=Ne(e,a,i,r,n),c=s.entries.findIndex(f=>String(f.tradeId)===String(o??"")&&f.state==="reserved");if(c<0)throw new Error("ledger: reservation unavailable");let[u]=s.entries.splice(c,1);return Le(e,s,a,r,n),structuredClone(u)})}function cn({file:e,keyFile:t,anchorFile:r,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){we(r,e);let a=O(t);return _e(e,()=>{let s=Ne(e,a,i,r,n),c=s.entries.find(f=>String(f.tradeId)===String(o??"")&&f.state==="reserved");if(!c)throw new Error("ledger: reservation unavailable");let u=BigInt(c.fee??0);return u<=0n?(c.state="committed",c.committedAtMs=i,c.value="0",c.notional="0",c.settledAs="no-fee",Le(e,s,a,r,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=u.toString(),c.settledAs="fee-only",Le(e,s,a,r,n),structuredClone(c))})}function un(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:X(ya(t))};return z(e.mac,F(o,O(r)))}function Sa(e){let t={...e?.fee||{}};return delete t.waiverAttestation,{...e,fee:t}}function ln(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:X(Sa(t))};return z(e.mac,F(o,O(r)))}import{spawnSync as Aa}from"node:child_process";function fn(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=Aa(r,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}import{Wallet as Cr}from"ethers";import{base58 as mn}from"@scure/base";import{ed25519 as va}from"@noble/curves/ed25519.js";import{NETWORK as hn,TEST_NETWORK as wn,WIF as Ta,p2wpkh as dn}from"@scure/btc-signer";import{pubECDSA as Ia}from"@scure/btc-signer/utils.js";var ka=e=>{let t=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(t)||t.length%2?null:Buffer.from(t,"hex")},Oa=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},ge=(e,t)=>{if(!(e instanceof Uint8Array))throw new Error(`${t}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${t}: expected 32-byte private key material`)};function Pr(e,t){let r=String(t||"").trim();if(e==="evm")return new Cr(r).privateKey;if(e==="btc")for(let i of[hn,wn])try{return Buffer.from(Ta(i).decode(r))}catch{}if(e==="sol")try{return ge(mn.decode(r),"sol")}catch{}let n=ka(r);if(n)return e==="evm"?new Cr(`0x${n.toString("hex")}`).privateKey:ge(n,e);let o=Oa(r);if(o)return ge(o,e);if(r.startsWith("[")||r.startsWith("{")){let i=JSON.parse(r);if(Array.isArray(i))return ge(Uint8Array.from(i),e);let a=i.privateKey??i.secretKey??i.key;if(a)return Pr(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function pn(e,t){if(e==="evm"){let r=new Cr(String(t));return{kind:e,secret:r.privateKey,addresses:[r.address.toLowerCase()]}}if(e==="btc"){let r=ge(t,"btc"),n=Ia(r);return{kind:e,secret:r.toString("hex"),addresses:[dn(n,hn).address,dn(n,wn).address]}}if(e==="sol"){let r=ge(t,"sol");return{kind:e,secret:r.toString("hex"),addresses:[mn.encode(va.getPublicKey(r))]}}throw new Error(`unsupported signer kind ${e}`)}function gn(e,t={}){let r=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(t.kind||"")!=="multichain")return{[t.kind||"evm"]:pn(t.kind||"evm",Pr(t.kind||"evm",r))};let n=JSON.parse(r),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=pn(i,Pr(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function Rr(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}function Ca(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||J.join(process.env.XDG_STATE_HOME||J.join(La.homedir(),".local","state"),"oracle"),r=Na("sha256").update(J.resolve(e)).digest("hex").slice(0,16);return{vault:J.join(e,"vault.json"),policy:J.join(e,"signer-policy.json"),policyKey:J.join(e,"policy-integrity-key"),policyAnchor:J.join(t,`signer-policy-${r}.high-water`),ledger:J.join(e,"signer-ledger.json"),ledgerAnchor:J.join(t,`signer-ledger-${r}.high-water`),token:J.join(e,"signer-token"),lock:J.join(t,`signer-${r}.lock`)}}function Pa(e){try{return O(e)}catch(r){if(r.code!=="ENOENT")throw r}let t=_a(32).toString("hex");return te(e,t+`
|
|
8
|
+
`),t}function Fr(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 En(e){return e.surfaces.some(t=>String(t).startsWith("evm"))}function R(e,t){return e.surfaces.includes(t)}function Ra(e,t,r){let n=e?.version===1&&e?.surface?e:null,o=n?.artifact||e||{},i=[`surface=${n?.surface||"evm"} action=${n?.action||"evm"}`,`chain=${o.chainId??o.network??o.cluster??"n/a"} owner=${n?.owner||o.from||"n/a"}`,`to=${o.to||n?.destination||"n/a"} calldata=${String(o.data||"0x")} value=${o.value??"n/a"}`,`gas=${o.gasLimit??"n/a"} maxFeePerGas=${o.maxFeePerGas??o.gasPrice??"n/a"} maxPriorityFeePerGas=${o.maxPriorityFeePerGas??"n/a"}`,`l1FeeWei=${o.l1FeeWei??"n/a"} operatorFeeWei=${o.operatorFeeWei??"n/a"}`,`nonce=${o.nonce??"n/a"} type=${o.type??"n/a"} accessList=${Array.isArray(o.accessList)?o.accessList.length:0}`,`slippageBps=${n?.slippageBps??o.slippageBps??"n/a"} expiresAtMs=${n?.expiresAtMs??o.expiresAtMs??"n/a"}`],a=(c,u)=>{if(i.push(`LEG ${u} chain=${c.chainId??"n/a"} from=${c.from??"n/a"} to=${c.to??"n/a"}`),i.push(`LEG ${u} calldata=${String(c.data||"0x")} value=${c.value??"n/a"}`),i.push(`LEG ${u} gas=${c.gasLimit??"n/a"} maxFeePerGas=${c.maxFeePerGas??c.gasPrice??"n/a"} maxPriorityFeePerGas=${c.maxPriorityFeePerGas??"n/a"}`),i.push(`LEG ${u} l1FeeWei=${c.l1FeeWei??"n/a"} operatorFeeWei=${c.operatorFeeWei??"n/a"} nonce=${c.nonce??"n/a"} type=${c.type??"n/a"}`),H(String(c.data||"0x")))try{let f=xe(String(c.data||"0x"));i.push(`LEG ${u} APPROVAL token=${f.token||c.to||"n/a"} spender=${f.spender} amount=${f.amount}`)}catch{i.push(`LEG ${u} APPROVAL spender=undecodable amount=undecodable`)}},s=String(o.data||"0x");if(H(s))try{let c=xe(s);i.push(`APPROVAL token=${c.token||o.to||"n/a"} spender=${c.spender} amount=${c.amount}`)}catch{i.push("APPROVAL spender=undecodable amount=undecodable")}if(Array.isArray(o.transactions)&&(i.push(`batchLegs=${o.transactions.length}`),o.transactions.forEach((c,u)=>a(c,u))),n?.surface==="btc"){let c=cr(n,r);i.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(n?.surface==="sol"){let c=mr(n,r);i.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}if(n?.surface==="hl"){let c=Q(n,r);i.push(`hlKind=${c.kind} actionType=${c.actionType} coin=${c.coin||"n/a"} amount=${c.amount} notionalUsd=${c.notional} submitTo=${c.submitTo}`)}if(n?.surface==="poly"){let c=ee(n,r);i.push(`polyKind=${c.kind} tokenId=${c.tokenId} notionalUsdc=${c.notional} submitTo=${c.submitTo}`)}if(n?.surface==="lighter"){let c=re(n,r);i.push(`lighterKind=${c.kind} actionType=${c.actionType} market=${c.symbol} amount=${c.amount} submitTo=${c.submitTo}`)}return`
|
|
9
9
|
Confirm exact action
|
|
10
10
|
${i.join(`
|
|
11
11
|
`)}
|
|
12
|
-
Type digest ${r}: `}async function je(e,r){let t=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)}),n=await t.text();if(!t.ok)throw new Error(`rpc: HTTP ${t.status}`);let o=JSON.parse(n||"{}");if(o.error)throw new Error(`rpc: ${o.error.message||"request failed"}`);return o.result}function $t(e,r){return Buffer.concat([Buffer.from([1]),Buffer.from(r),Buffer.from(e)]).toString("base64")}async function Dt(e,r,t){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation and broadcast");return je(n,{jsonrpc:"1.0",id:"oracle",method:r,params:t})}async function Ci(e,r,t){let n=String(e.btcRpcUrl||e.bitcoinRpcUrl||"").replace(/\/$/,"");if(!n)throw new Error("signer: btcRpcUrl required for Bitcoin simulation");let o=n.endsWith("/tx")?n.slice(0,-3):n;try{let a=await fetch(`${o}/tx/${r}/outspend/${t}`);if(a.ok){let s=await a.json();if(s?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(s?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await Dt(e,"gettxout",[r,Number(t),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Fi(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 Mi(e,r){let t=xr(r);return{simulate:async n=>{let o=e(),i=Sr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let a=0;a<i.inputsLength;a++){let s=i.getInput(a),c=Buffer.from(s.txid||[]).toString("hex");await Ci(o,c,s.index)}return!0},sign:n=>{let o=Sr.fromPSBT(Buffer.from(n.psbt,"base64"));return o.sign(t),Buffer.from(o.toPSBT()).toString("base64")},broadcast:async n=>{let o=e(),i=String(o.btcRpcUrl||o.bitcoinRpcUrl||"").replace(/\/$/,"");if(!i)throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");let a=Sr.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let s;try{let u=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(s=(await u.text()).trim(),!u.ok)throw new Error(`signer: Bitcoin broadcast failed ${u.status}`)}catch(u){if(!/Bitcoin broadcast failed 404/.test(String(u?.message||u)))throw u;s=await Dt(o,"sendrawtransaction",[a.hex])}if(s&&String(s).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let u=i.endsWith("/tx")?i.slice(0,-3):i,l=await fetch(`${u}/tx/${a.id}/status`);l.ok&&(c=(await l.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:c}}}}function Pi(e,r){let t=xr(r);return{simulate:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana simulation");let a=Buffer.from(n.messageBase64,"base64"),s=$t(a,new Uint8Array(64)),c=await je(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[s,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Fi(c)},sign:n=>$t(Buffer.from(n.messageBase64,"base64"),ki.sign(Buffer.from(n.messageBase64,"base64"),t)),broadcast:async n=>{let o=e(),i=String(o.solRpcUrl||o.solanaRpcUrl||"");if(!i)throw new Error("signer: solRpcUrl required for Solana broadcast");let a=await je(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await je(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:a,status:0};let u=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:a,status:u?1:null}}}}async function jt({configDir:e,passphraseFile:r,credentialService:t,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:s,Wallet:c}=await import("ethers");if(!r&&!t)throw new Error("signer: --credential-service or --passphrase-file is required for non-interactive service start");if(a<1e3||a>12e4)throw new Error("signer: session must be at most 120 seconds");let u=_i(e),l=()=>Object.freeze(bt(u.policy,u.policyKey,{sequenceAnchorFile:u.policyAnchor})),f=l();if(!["exact-human","auto-within-rails"].includes(f.confirmationMode))throw new Error("signer: confirmationMode must be exact-human or auto-within-rails");if(f.confirmationMode==="auto-within-rails"&&process.env.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: auto-within-rails requires ORACLE_AUTONOMOUS_TRADING=1");for(let g of["surfaces","actions","chains","destinations","spenders","owners"])if(!Array.isArray(f[g])||f[g].length===0)throw new Error(`signer: ${g} allowlist is empty`);if(f.surfaces.some(g=>g==="evm-swap"||g==="evm-bridge"||g==="evm-nft")){for(let g of["providers"])if(!Array.isArray(f[g])||f[g].length===0)throw new Error(`signer: ${g} allowlist is empty`)}if(f.surfaces.some(g=>g==="evm-swap"||g==="evm-bridge")&&(!Array.isArray(f.tokens)||f.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(f.surfaces.some(g=>String(g).startsWith("evm"))&&(!Array.isArray(f.selectors)||f.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(f.surfaces.includes("sol")&&(!Array.isArray(f.programs)||f.programs.length===0))throw new Error("signer: programs allowlist is empty");if(f.surfaces.some(g=>g==="hl"||g==="poly"))throw new Error("signer: hl/poly are not public signer families");let d=t?kt(t):I(r),p=xt(u.vault),m=Et(p,d),w;try{w=Mt(m,p.meta)}finally{m.fill(0)}qt(f)&&br("evm",w.evm,f.owners),De(f,"btc")&&br("btc",w.btc,f.owners),De(f,"sol")&&br("sol",w.sol,f.owners);let x=f.chains.filter(g=>Number.isInteger(Number(g))&&String(g).trim()!==""),h=qt(f);if(h&&(x.length!==1||!f.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(De(f,"btc")&&!(f.btcRpcUrl||f.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(De(f,"sol")&&!(f.solRpcUrl||f.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=h?new s(f.rpcUrl,Number(x[0])):null,S=h?new c(w.evm.secret).connect(E):null,y=E?{simulate:async g=>{if((await E.getNetwork()).chainId!==BigInt(g.chainId))throw new Error("signer: RPC chain mismatch");return await E.call(g),!0},sign:g=>S.signTransaction(g),broadcast:async(g,A)=>{if((await E.getNetwork()).chainId!==BigInt(A.chainId))throw new Error("signer: RPC chain mismatch");let j={native:(await E.getBalance(A.from)).toString()},fe=await E.broadcastTransaction(g),Z=await fe.wait(),be={native:(await E.getBalance(A.from)).toString()};return{hash:Z?.hash??fe.hash,status:Z?.status??null,verifiedBefore:j,verifiedAfter:be}}}:null,N=E?async g=>qi(E,g):void 0,O={...y?{evm:y,"evm-swap":y,"evm-bridge":y,"evm-nft":y}:{},...w.btc?{btc:Mi(l,w.btc)}:{},...w.sol?{sol:Pi(l,w.sol)}:{}},v=ot({...O,...n}),Ve=new Set(Object.keys(O)),Jt=new Set(Object.keys(n||{})),yr=f.surfaces.filter(g=>!Ve.has(g)&&!Jt.has(g));if(yr.length)throw new Error(`signer: ${yr.join(",")} require local keys or injected surface transports`);let Vt=Date.now(),vr=Vt+a,Ge=!1,Gt=()=>Ge?!1:Pt.existsSync(u.lock)?(Ge=!0,!1):Pt.existsSync(u.vault)&&Date.now()<vr,Ht=()=>(Ge=!0,Y(u.lock,`disarmed ${new Date().toISOString()}
|
|
13
|
-
`),!0),
|
|
14
|
-
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,
|
|
15
|
-
`),0;let
|
|
16
|
-
`),await new Promise(o=>n.on("close",o)),0}var
|
|
12
|
+
Type digest ${t}: `}async function Qe(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 bn(e,t){return Buffer.concat([Buffer.from([1]),Buffer.from(t),Buffer.from(e)]).toString("base64")}async function Sn(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 Qe(n,{jsonrpc:"1.0",id:"oracle",method:t,params:r})}async function Ma(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 s=await a.json();if(s?.spent===!0)throw new Error("signer: Bitcoin input already spent");if(s?.spent===!1)return!0}}catch(a){if(/already spent/.test(String(a?.message||a)))throw a}if(!await Sn(e,"gettxout",[t,Number(r),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Fa(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 qa(e,t){return{simulate:async(r,n)=>(Q(n,e()),!0),sign:async(r,n)=>{Q(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?(Ct(r),t.signTypedData(r.typedData.domain,r.typedData.types,r.typedData.message)):Pt({wallet:t,action:r.action,nonce:r.nonce,isMainnet:!String(r.submitTo||"").includes("testnet")})},broadcast:async(r,n,o)=>{Q(o,e());let{Signature:i,keccak256:a}=await import("ethers"),s=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:s.r,s:s.s,v:s.v}})})).json())?.status!=="ok")throw new Error("signer: Hyperliquid exchange rejected the action");return{hash:a(r),status:1}}}}function $a(e){return{simulate:async(t,r)=>(re(r,e()),!0),sign:async(t,r)=>{re(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 Oe(t,o),typeof o=="string"?o:JSON.stringify(o)},broadcast:async(t,r,n)=>{let o=re(n,e()),i=Oe(r,t),a=Mt(i),s=await fetch(o.submitTo,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:a}),c=await s.json().catch(()=>({}));if(!s.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 Da(e,t){return{simulate:async(r,n)=>(ee(n,e()),!0),sign:async(r,n)=>{ee(n,e());let o=e();if(!(Array.isArray(o.owners)?o.owners:[]).some(a=>String(a).toLowerCase()===String(t.address).toLowerCase()))throw new Error("signer: Poly wallet is not an allowed policy owner");if(String(n.owner||"").toLowerCase()!==String(t.address).toLowerCase())throw new Error("signer: Poly wallet must match envelope owner");return t.signTypedData(r.domain,r.types,r.message)},broadcast:async(r,n,o)=>{let i=e(),a=ee(o,i),s=gr(i),{keccak256:c}=await import("ethers"),u=gt({message:n.message,side:n.side,signature:r,orderType:n.orderType||"GTC",apiKey:s.key}),f=JSON.stringify(u),l=ht({creds:s,address:o.owner,method:"POST",path:"/order",body:f}),p=await fetch(a.submitTo,{method:"POST",headers:l,body:f}),d=await p.json().catch(()=>({}));if(!p.ok||d?.success===!1||d?.error||d?.errorMsg)throw new Error("signer: Polymarket CLOB rejected the order");return{hash:c(r),status:1}}}}function Ua(e,t){let r=Rr(t);return{simulate:async n=>{let o=e(),i=Mr.fromPSBT(Buffer.from(n.psbt,"base64"));for(let a=0;a<i.inputsLength;a++){let s=i.getInput(a),c=Buffer.from(s.txid||[]).toString("hex");await Ma(o,c,s.index)}return!0},sign:n=>{let o=Mr.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=Mr.fromPSBT(Buffer.from(n,"base64"));a.finalize(),a.extract();let s;try{let u=await fetch(i.endsWith("/tx")?i:`${i}/tx`,{method:"POST",headers:{"content-type":"text/plain"},body:a.hex});if(s=(await u.text()).trim(),!u.ok)throw new Error(`signer: Bitcoin broadcast failed ${u.status}`)}catch(u){if(!/Bitcoin broadcast failed 404/.test(String(u?.message||u)))throw u;s=await Sn(o,"sendrawtransaction",[a.hex])}if(s&&String(s).toLowerCase()!==a.id.toLowerCase())throw new Error("signer: Bitcoin broadcast txid mismatch");let c=null;try{let u=i.endsWith("/tx")?i.slice(0,-3):i,f=await fetch(`${u}/tx/${a.id}/status`);f.ok&&(c=(await f.json())?.confirmed===!0?1:null)}catch{}return{hash:a.id,status:c}}}}function ja(e,t){let r=Rr(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"),s=bn(a,new Uint8Array(64)),c=await Qe(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[s,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Fa(c)},sign:n=>bn(Buffer.from(n.messageBase64,"base64"),Ba.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 Qe(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await Qe(i,{jsonrpc:"2.0",id:1,method:"getSignatureStatuses",params:[[a],{searchTransactionHistory:!0}]}))?.value?.[0];if(c?.err)return{hash:a,status:0};let u=c?.confirmationStatus==="confirmed"||c?.confirmationStatus==="finalized"||c?.confirmations===null;return{hash:a,status:u?1:null}}}}function Wa(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 An({configDir:e,passphraseFile:t,credentialService:r,surfaceTransports:n={},host:o="127.0.0.1",port:i=9462,sessionMs:a=12e4}={}){let{JsonRpcProvider:s,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 u=Ca(e),f=()=>Object.freeze(rn(u.policy,u.policyKey,{sequenceAnchorFile:u.policyAnchor})),l=f();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(g=>String(g).startsWith("evm"))&&p.push("chains","spenders");for(let g of p)if(!Array.isArray(l[g])||l[g].length===0)throw new Error(`signer: ${g} allowlist is empty`);if(l.surfaces.some(g=>g==="evm-swap"||g==="evm-bridge"||g==="evm-nft")){for(let g of["providers"])if(!Array.isArray(l[g])||l[g].length===0)throw new Error(`signer: ${g} allowlist is empty`)}if(l.surfaces.some(g=>g==="evm-swap"||g==="evm-bridge")&&(!Array.isArray(l.tokens)||l.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(l.surfaces.some(g=>String(g).startsWith("evm"))&&(!Array.isArray(l.selectors)||l.selectors.length===0))throw new Error("signer: selectors allowlist is empty");if(l.surfaces.includes("sol")&&(!Array.isArray(l.programs)||l.programs.length===0))throw new Error("signer: programs allowlist is empty");if(R(l,"poly")&&(gr(l),!Array.isArray(l.polyTokens)||l.polyTokens.length===0))throw new Error("signer: polyTokens allowlist is empty");if(R(l,"lighter")&&(!Array.isArray(l.lighterMarkets)||l.lighterMarkets.length===0))throw new Error("signer: lighterMarkets allowlist is empty");if(R(l,"hl")){let g=Array.isArray(l.coins)?l.coins.map(String):[],A=Array.isArray(l.hlMarkets)?l.hlMarkets:[];if(g.filter(M=>M!=="*"&&M!=="#*").length&&!g.includes("*")&&A.length===0)throw new Error("signer: restricted hl coins require hlMarkets pairs")}let d=r?fn(r):O(t),m=Qt(u.vault),y=Zt(m,d),w;try{w=gn(y,m.meta)}finally{y.fill(0)}(En(l)||R(l,"hl")||R(l,"poly"))&&Fr("evm",w.evm,l.owners),R(l,"btc")&&Fr("btc",w.btc,l.owners),R(l,"sol")&&Fr("sol",w.sol,l.owners);let h=Array.isArray(l.chains)?l.chains.filter(g=>Number.isInteger(Number(g))&&String(g).trim()!==""):[],b=En(l);if(b&&(h.length!==1||!l.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(R(l,"btc")&&!(l.btcRpcUrl||l.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(R(l,"sol")&&!(l.solRpcUrl||l.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=b?new s(l.rpcUrl,Number(h[0])):null,S=w.evm&&(b||R(l,"hl")||R(l,"poly"))?E?new c(w.evm.secret).connect(E):new c(w.evm.secret):null,I=E?{simulate:async g=>{if((await E.getNetwork()).chainId!==BigInt(g.chainId))throw new Error("signer: RPC chain mismatch");return await E.call(g),!0},sign:g=>S.signTransaction(g),broadcast:async(g,A)=>{if((await E.getNetwork()).chainId!==BigInt(A.chainId))throw new Error("signer: RPC chain mismatch");let M={native:(await E.getBalance(A.from)).toString()},Ee=await E.broadcastTransaction(g),Z=await Ee.wait(),Ce={native:(await E.getBalance(A.from)).toString()};return{hash:Z?.hash??Ee.hash,status:Z?.status??null,verifiedBefore:M,verifiedAfter:Ce}}}:null,k=E?async g=>Ja(E,g):void 0,v={...I?{evm:I,"evm-swap":I,"evm-bridge":I,"evm-nft":I}:{},...w.btc?{btc:Ua(f,w.btc)}:{},...w.sol?{sol:ja(f,w.sol)}:{},...S&&R(l,"hl")?{hl:qa(f,S)}:{},...S&&R(l,"poly")?{poly:Da(f,S)}:{},...R(l,"lighter")?{lighter:$a(f)}:{}};Wa(v,n);let ye=_t({...v,...n}),Tn=new Set(Object.keys(v)),In=new Set(Object.keys(n||{})),qr=l.surfaces.filter(g=>!Tn.has(g)&&!In.has(g));if(qr.length)throw new Error(`signer: ${qr.join(",")} require local keys or injected surface transports`);let kn=Date.now(),$r=kn+a,tr=!1,On=()=>tr?!1:yn.existsSync(u.lock)?(tr=!0,!1):yn.existsSync(u.vault)&&Date.now()<$r,Ln=()=>(tr=!0,te(u.lock,`disarmed ${new Date().toISOString()}
|
|
13
|
+
`),!0),Be=Xt({host:o,port:i,token:Pa(u.token),policy:l,readPolicy:f,isArmed:On,disarm:Ln,sessionExpiresAtMs:$r,nowMs:Date.now,simulate:(g,A)=>Je(A,ye).simulate(g,A),estimateNetworkFees:k,sign:(g,A)=>Je(A,ye).sign(g,A),verifySigned:(g,A,L)=>Wt(L?.surface||"evm",g,A,L),broadcast:(g,A,L)=>Je(L,ye).broadcast(g,A,L),confirmArtifact:Va,decodeEconomics:(g,A)=>Sr(g,A),reserveLedger:(g,A)=>{let L=g?.version===1&&g?.surface?g:null,M=L?.artifact||g,Ee=L?.tradeId||M?.tradeId;if(!Ee)throw new Error("ledger: executable artifact requires a tradeId");let Z;if(L)Z=Sr(L,A);else{if(M?.value===void 0)throw new Error("ledger: executable artifact value required");let Ce=BigInt(M.value),Ur=BigInt(M.gasLimit??0),jr=BigInt(M.maxFeePerGas??M.gasPrice??0);if(Ur<=0n||jr<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let Wr=Ur*jr+BigInt(M.l1FeeWei??0)+BigInt(M.operatorFeeWei??0);Z={unit:"wei",value:Ce.toString(),notional:(Ce+Wr).toString(),fee:Wr.toString()}}if(Z.value===void 0||Z.notional===void 0)throw new Error("ledger: decoded value and notional required");return nn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:Ee,...Z,policy:A})},commitLedger:g=>an({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),releaseLedger:g=>sn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),settleFailedLedger:g=>cn({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),validateReservation:(g,A,L)=>on({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,reservation:g,policy:A,economics:L}),verifyFeeWaiver:(g,A)=>ln(g,A,u.policyKey),verifyTriggerAttestation:(g,A,L)=>un(g,A,u.policyKey,L),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),Dr=setTimeout(()=>Be.close(),a);return Dr.unref(),Be.on("close",()=>{clearTimeout(Dr)}),Be.listen(i,o),Be}var er="0x420000000000000000000000000000000000000F";function xn(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 Ja(e,t){if(!V(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 s=await e.call({to:er,data:o.encodeFunctionData("getL1Fee",[i])});a=o.decodeFunctionResult("getL1Fee",s)[0].toString()}catch{throw new Error("policy: rollup fee estimate required")}return{l1FeeWei:a,operatorFeeWei:await Ha(e,o,t.gasLimit)}}async function Ha(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:er,data:t.encodeFunctionData("getOperatorFee",[n])});return t.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!xn(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:er,data:t.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:er,data:t.encodeFunctionData("operatorFeeConstant")}),a=BigInt(t.decodeFunctionResult("operatorFeeScalar",o)[0]),s=BigInt(t.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+s).toString()}catch(o){if(!xn(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function Va(e,t,r){return process.stdin.isTTY?(process.stderr.write(Ra(e,t,r)),process.stdin.resume(),new Promise(n=>{let o=i=>{process.stdin.off("data",o),process.stdin.pause(),n(String(i).trim()===t)};process.stdin.once("data",o)})):!1}var vn=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
|
|
14
|
+
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,rr=(e,t,r)=>{let n=e.indexOf(t);return n>=0?e[n+1]:r};async function za(e=[],t={}){if(e.includes("--help"))return(t.out||process.stdout).write(vn+`
|
|
15
|
+
`),0;let r=rr(e,"--passphrase-file"),n=await An({configDir:Ga.join(t.configDir||Re(),"signer"),passphraseFile:r,credentialService:rr(e,"--credential-service"),port:Number(rr(e,"--port",9462)),sessionMs:Number(rr(e,"--session-seconds",120))*1e3});return(t.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
|
|
16
|
+
`),await new Promise(o=>n.on("close",o)),0}var Zu={name:"signer",summary:"run the short-lived loopback signer",usage:vn,run:e=>za(e.argv||[])};export{Zu as default,za as run};
|