@oracle-agent/oracle 0.24.9 → 0.24.10
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 +20 -16
- package/dist/assets/skills/oracle-desk-product/SKILL.md +3 -3
- package/dist/bin/desk-server.mjs +49 -49
- package/dist/bin/oracle-data-mcp.mjs +2 -2
- package/dist/bin/oracle-public-server.mjs +22 -22
- package/dist/bin/oracle-route.mjs +1 -1
- package/dist/bin/oracle-scan.mjs +1 -1
- package/dist/bin/oracle-upgrade.mjs +9 -9
- package/dist/bin/oracle.mjs +6 -6
- package/dist/cli/commands/chat.mjs +84 -84
- package/dist/cli/commands/doctor.mjs +4 -4
- package/dist/cli/commands/model.mjs +89 -89
- package/dist/cli/commands/receipt.mjs +3 -3
- package/dist/cli/commands/sign.mjs +11 -11
- package/dist/cli/commands/signer.mjs +13 -11
- package/dist/cli/commands/swap.mjs +1 -1
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +41 -41
- package/dist/index.mjs +56 -56
- package/dist/local-signer/index.mjs +3 -1
- package/dist/scanner/index.mjs +2 -2
- package/package.json +2 -1
- package/public/oracle-splash/downloads/index.html +3 -3
- package/public/oracle-splash/index.html +3 -3
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
import Vo from"node:path";import pe from"node:fs";import It from"node:os";import X from"node:path";import{fileURLToPath as Lt}from"node:url";var Tt=X.dirname(Lt(import.meta.url)),Xo=X.resolve(Tt,"../..");function hr(){return process.env.ORACLE_FAKE_HOME||It.homedir()}function Nt(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function me(){return Nt()?process.env.ORACLE_CONFIG_DIR||X.join(hr(),".config","oracle"):X.join(hr(),".config","oracle")}function Bt(){return X.join(me(),"desk.json")}function _t(){return X.join(me(),"env")}function K({force:e=!1}={}){if(K._done&&!e)return K._result||null;K._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=_t();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)),t(a[1],s)}}catch{}try{let o=Bt();if(pe.existsSync(o)){let i=JSON.parse(pe.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)),K._result=Object.keys(r).length?r:null,K._result}try{K()}catch{}import ht from"node:fs";import $ from"node:path";import Bo from"node:os";import{createHash as _o,randomBytes as ko}from"node:crypto";import{Transaction as sr}from"@scure/btc-signer";import{ed25519 as Co}from"@noble/curves/ed25519.js";import Qn from"node:http";import{timingSafeEqual as eo}from"node:crypto";import{createHash as Wn,randomBytes as Dn,timingSafeEqual as jn}from"node:crypto";import{base58 as jr}from"@scure/base";import{Interface as zt,MaxUint256 as Jt,isAddress as Kt,keccak256 as Fi,toUtf8Bytes as Ri}from"ethers";import{Interface as Gt,isAddress as hi}from"ethers";import{isAddress as ui}from"ethers";import{createHash as $t,createHmac as Mt,timingSafeEqual as Pt}from"node:crypto";import{readFileSync as kt}from"node:fs";import{homedir as Ct}from"node:os";import{join as he}from"node:path";function Ft(){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=Ct();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||he(r,".config","oracle")).trim();return[e,he(t,"exec.env")].filter(Boolean)}return[e,he(r,".config","oracle","exec.env"),he(r,".config","mad-desk","exec.env")].filter(Boolean)}function ne(e,r,t){let n=e??process.env[r]??process.env[t];if(!String(n||"").trim())for(let o of Ft())try{let i=kt(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 Z(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 ${Rt(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 Rt(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var wr=100;function Pe(e){return Array.isArray(e)?`[${e.map(Pe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Pe(e[r])}`).join(",")}}`:JSON.stringify(e??null)}function qt(e,{required:r=!1}={}){try{return ne(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(t){if(r)throw t;return null}}function Ut(e){let{signature:r,...t}=e;return t}function Wt(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 $t("sha256").update(Buffer.from(r.slice(2),"hex")).digest("hex")}function Dt(e,r){let t=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(r??""),"utf8");return t.length!==n.length||t.length===0?!1:Pt(t,n)}function jt(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 qe(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=qt(o,{required:a});if(a&&!s)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(s){let m=Mt("sha256",s).update(Pe(Ut(e))).digest("hex");if(!Dt(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>wr)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>wr||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{Z({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 w=l*BigInt(1e4-c),p=w/10000n;if(w%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=jt(i.data);if(e.calldataHash!=null){if(String(e.calldataHash)!==Wt(i.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch");if(m!=null&&m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is hash-bound but the calldata encodes ${m}, not the guard floor ${e.minAmountOut}`)}else{if(m==null){let g=String(i.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${g}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${m}`)}}return!0}var xi=new Gt(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Ht,isAddress as yi}from"ethers";var Ii=new Ht(["function approve(address spender,uint256 amount) returns (bool)"]),Li=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function gr(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 Wi=new zt(["function approve(address spender,uint256 amount) returns (bool)"]);function Er(e,r){let t=String(e||"").trim();if(!Kt(t))throw new Error(`${r} must be an address`);return t.toLowerCase()}function Xt(e,r="approval amount",{allowZero:t=!1}={}){let n=gr(e,r);if(t?n<0n:n<=0n)throw new Error(`${r} must be positive`);if(n>=Jt)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}var xr=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]),Zt=new Set(["0x39509351","0xf9255c1f"]);function P(e){let r=String(e||"").toLowerCase();return r.length<10?!1:xr.has(r.slice(0,10))}function oe(e){if(!P(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:Er(a,"approval spender"),token:c==null?null:Er(c,"approval token"),amount:Xt(s,"approval amount",{allowZero:!0}),selector:t,additive:Zt.has(t)}}import{createHash as Yt,createHmac as Qt,timingSafeEqual as en}from"node:crypto";var rn=2,Ue=300*1e3,br=(()=>{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===""?Ue:Number(e);return!Number.isFinite(r)||r<0?Ue:Math.min(r,br)}function We(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(We).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${We(e[t])}`).join(",")}}`}function Sr(e){let r=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return r.length>=16?r:""}function yr(e=process.env){return Sr(process.env)||Sr(e)}function nn(e=process.env){return String(process.env.ORACLE_STAMP_REQUIRE_MAC||"").trim()==="1"||String(e?.ORACLE_STAMP_REQUIRE_MAC||"").trim()==="1"}function on(e){let{oraclePrepared:r,prepareHash:t,prepareMac:n,note:o,...i}=e||{};return i}function an(e){let r=on(e);return Yt("sha256").update(We(r)).digest("hex")}function sn(e,r=yr()){return r?Qt("sha256",r).update(String(e)).digest("hex"):""}function cn(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:en(t,n)}catch{return!1}}function vr(e,{maxAgeMs:r=Ue,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)!==rn)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=an(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let c=yr(a),u=String(e.prepareMac||"");if(nn(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 g=sn(s,c);if(!u||!cn(u,g))throw new Error(`${i}: prepareMac mismatch \u2014 stamp not from trusted preparer`)}let l=Number(e.preparedAt),f=Number(e.expiresAt),w=tn(r),p=t-l,m=f-l;if(!Number.isFinite(p)||!Number.isFinite(f)||!Number.isFinite(m)||p<0||m<=0||m>br||p>w||t>f)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${p}, max=${w})`);if(n&&!new Set(n).has(e.provider))throw new Error(`${i}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${i}: kind ${e.kind} not allowed here`);return!0}var we=e=>String(e||"").toLowerCase(),un=new Set(["chainId","from","to","data","value","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","l1FeeWei","operatorFeeWei","nonce","type","accessList","slippageBps","expiresAtMs"]),fn=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function q(e){try{return fn.has(BigInt(e))}catch{return!1}}var F=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},Ar=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},ie=(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 ge(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=>!un.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(ie(e.to,r.destinations,"destination",we),ie(String(e.data||"0x").slice(0,10),r.selectors,"selector",p=>String(p).toLowerCase()),ie(e.from,r.owners,"owner",we),P(e.data)){let p;try{p=oe(e.data)}catch(g){throw new Error(`policy: malformed approval calldata: ${g?.message||g}`)}ie(p.spender,r.spenders,"spender",we),ie(p.token||e.to,r.erc20Tokens,"ERC-20 token",we);let m=F(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(F(e.value,"value")>F(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let a=F(e.gasLimit,"gasLimit");if(a>F(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");let s=e.maxFeePerGas??e.gasPrice,c=F(s,"feePerGas")*a,u=0n;try{if(q(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+=F(e.l1FeeWei,"l1FeeWei")),e.operatorFeeWei!==void 0&&(u+=F(e.operatorFeeWei,"operatorFeeWei")),q(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=F(n.l1FeeWei,"estimated l1FeeWei")+F(n.operatorFeeWei,"estimated operatorFeeWei");if(u<p)throw new Error("policy: rollup fee attestation understates estimate")}if(c+u>F(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");let f=Ar(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 w=Ar(r.maxTtlMs??12e4,"maxTtlMs");if(w<=0||e.expiresAtMs-t>w)throw new Error("policy: artifact TTL exceeds cap");return!0}import{createHash as Or}from"node:crypto";import{Address as ln,NETWORK as dn,OutScript as Ir,RawTx as pn,SigHash as Lr,TEST_NETWORK as mn,Transaction as hn}from"@scure/btc-signer";var Tr=(e,r)=>{if(e==null||e==="")throw new Error(`policy: ${r} required`);try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},wn=(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},gn=e=>Array.isArray(e)||e instanceof Uint8Array?e.length>0:e!=null,En=e=>/^(bc1|tb1|bcrt1)/i.test(String(e)),H=e=>En(e)?String(e).toLowerCase():String(e),De=(e,r)=>Array.isArray(r)&&r.some(t=>H(t)===H(e)),xn=(e,r)=>Buffer.from(e||[]).equals(Buffer.from(r||[]));function Sn(e){let r=Buffer.from(pn.encode(e)),t=Or("sha256").update(r).digest();return Buffer.from(Or("sha256").update(t).digest()).reverse().toString("hex")}function bn(e){if(!e.nonWitnessUtxo)throw new Error("envelope: PSBT input nonWitnessUtxo required");if(Sn(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)||!xn(e.witnessUtxo.script,r.script))throw new Error("envelope: Bitcoin witness UTXO mismatch");return r}function je(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(!De(t.network,r.chains))throw new Error("policy: chain not allowed");let n=["bitcoin","mainnet"].includes(String(t.network).toLowerCase())?dn:["testnet","signet","regtest"].includes(String(t.network).toLowerCase())?mn:null;if(!n)throw new Error("envelope: unsupported Bitcoin network");let o;try{o=hn.fromPSBT(wn(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=ln(n);for(let f=0;f<o.inputsLength;f++){let w=o.getInput(f);for(let g of["partialSig","tapKeySig","tapScriptSig","finalScriptSig","finalScriptWitness"])if(gn(w[g]))throw new Error("envelope: signed or finalized PSBT refused");if(w.sighashType!==void 0&&w.sighashType!==Lr.DEFAULT&&w.sighashType!==Lr.ALL)throw new Error("envelope: Bitcoin sighash must bind all inputs and outputs");let p=bn(w),m;try{let g=Ir.decode(p.script);if(!["wpkh"].includes(g.type))throw new Error("unsupported input");m=i.encode(g)}catch{throw new Error("envelope: unsupported Bitcoin input script")}if(!De(m,r.owners)||H(m)!==H(e.owner))throw new Error("envelope: Bitcoin input owner mismatch")}let a=new Set([e.owner,...r.changeAddresses||[]].map(f=>H(f))),s=0n,c=!1,u=[];for(let f=0;f<o.outputsLength;f++){let w=o.getOutput(f),p;try{p=i.encode(Ir.decode(w.script))}catch{throw new Error("envelope: unsupported Bitcoin output script")}let m=H(p);if(u.push(`${p}:${w.amount}`),m===H(e.destination)){c=!0,s+=w.amount;continue}if(De(p,r.destinations)){s+=w.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>Tr(r.maxFeeSats,"maxFeeSats"))throw new Error("policy: Bitcoin fee exceeds cap");if(s>Tr(r.maxValueSats,"maxValueSats"))throw new Error("policy: Bitcoin value exceeds cap");return Object.freeze({unit:"sats",value:s.toString(),notional:(s+l).toString(),fee:l.toString(),outputs:Object.freeze(u)})}function Ve(e,r){let{unit:t,value:n,notional:o,fee:i}=je(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}import{getCompiledTransactionMessageDecoder as yn}from"@solana/transaction-messages";var vn="11111111111111111111111111111111",An=5000n,ae=(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`)}},On=(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},Ee=(e,r)=>Array.isArray(r)&&r.some(t=>String(t)===String(e));function Ge(e,r){if(e.action!=="transfer")throw new Error("envelope: Solana decoder requires transfer action");let t=e?.artifact;if(Object.keys(t).some(m=>!["cluster","messageBase64","exactFeeLamports"].includes(m)))throw new Error("envelope: unexpected Solana artifact field");if(!Ee(t.cluster,r.chains))throw new Error("policy: chain not allowed");let n;try{n=yn().decode(On(t.messageBase64,"Solana message"))}catch(m){throw new Error(`envelope: invalid Solana message: ${m?.message||m}`)}if(n.version!=="legacy"&&Array.isArray(n.addressTableLookups)&&n.addressTableLookups.length)throw new Error("envelope: unresolved Solana address tables refused");if(n.header.numSignerAccounts!==1||n.staticAccounts[0]!==e.owner||!Ee(e.owner,r.owners))throw new Error("envelope: Solana owner mismatch");let o=0n,i=!1,a=[];if(!Array.isArray(n.instructions)||n.instructions.length===0)throw new Error("envelope: Solana instructions required");for(let m of n.instructions){let g=n.staticAccounts[m.programAddressIndex];if(!g||!Ee(g,r.programs))throw new Error("policy: Solana program not allowed");if(g!==vn)throw new Error("envelope: unsupported Solana program decoder");a.push(g);let x=m.accountIndices||[];if(x.length!==2||n.staticAccounts[x[0]]!==e.owner)throw new Error("envelope: Solana transfer owner mismatch");let d=n.staticAccounts[x[1]];if(d!==e.destination||!Ee(d,r.destinations))throw new Error("envelope: Solana destination mismatch");let E=Buffer.from(m.data||[]);if(E.length!==12||E.readUInt32LE(0)!==2)throw new Error("envelope: unsupported Solana system instruction");o+=E.readBigUInt64LE(4),i=!0}if(!i)throw new Error("envelope: Solana destination mismatch");if(o>ae(r.maxValueLamports,"maxValueLamports"))throw new Error("policy: Solana value exceeds cap");let s=ae(r.lamportsPerSignature,"lamportsPerSignature");if(s<An)throw new Error("policy: Solana per-signature fee is below the network minimum");let c=r.maxLamportsPerSignature===void 0?s:ae(r.maxLamportsPerSignature,"maxLamportsPerSignature");if(s>c)throw new Error("policy: Solana per-signature fee exceeds cap");let u=e?.artifact?.exactFeeLamports,l=BigInt(n.header.numSignerAccounts),f=l*s,w=l*c;if(u!==void 0){let m=ae(u,"exactFeeLamports");if(m<f)throw new Error("policy: Solana exact fee below the base signature fee");if(m>w)throw new Error("policy: Solana exact fee exceeds the per-signature bound")}let p=w;if(p>ae(r.maxFeeLamports,"maxFeeLamports"))throw new Error("policy: Solana fee exceeds cap");return Object.freeze({unit:"lamports",value:o.toString(),notional:(o+p).toString(),fee:p.toString(),programs:Object.freeze(a)})}function He(e,r){let{unit:t,value:n,notional:o,fee:i}=Ge(e,r);return Object.freeze({unit:t,value:n,notional:o,fee:i})}var Br=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol"]);var Je=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0}),In=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),_r=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"}}),Ln=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"}});var xe=(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`)}},Nr=(e,r)=>{let t=Number(e);if(!Number.isFinite(t))throw new Error(`policy: ${r} must be finite`);return t},Tn=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${r} allowlist is empty`);return e},B=(e,r,t)=>{if(!Tn(r,t).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${t} not allowed`)},ze=(e,r,t)=>{Array.isArray(r)&&r.length&&B(e,r,t)},V=(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},se=e=>String(e||"0x").slice(0,10).toLowerCase(),kr=e=>b(e.gasLimit,"gasLimit")*b(e.maxFeePerGas??e.gasPrice,"feePerGas")+b(e.l1FeeWei??0,"l1FeeWei")+b(e.operatorFeeWei??0,"operatorFeeWei");function be(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 R(e,r){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${r} address`);return`0x${e.slice(24)}`}function j(e,r){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${r} integer`)}}function Nn(e){if(se(e)!=="0x095ea7b3")return null;let r=be(e,2,"approval");return{kind:"approval",spender:R(r.word(0),"approval spender"),amount:j(r.word(1),"approval amount")}}function Bn(e,r){let t=r==="router02-exact-input-single"?7:8,n=be(e,t,"Uniswap v3 exactInputSingle"),o=t===7?4:5;return{kind:"action",action:"swap",inputToken:R(n.word(0),"input token"),outputToken:R(n.word(1),"output token"),recipient:R(n.word(3),"recipient"),amountIn:j(n.word(o),"amountIn"),minimumOut:j(n.word(o+1),"amountOutMinimum")}}function _n(e){let r=be(e,12,"Across depositV3",{dynamicTail:!0}),t=j(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:R(r.word(0),"depositor"),recipient:R(r.word(1),"recipient"),inputToken:R(r.word(2),"input token"),outputToken:R(r.word(3),"output token"),amountIn:j(r.word(4),"inputAmount"),minimumOut:j(r.word(5),"outputAmount"),destinationChainId:j(r.word(6),"destinationChainId")}}function kn(e,r){let t=se(e),n=_r[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{...Bn(e,n.layout),selector:t,provider:n.provider};if(n.action==="bridge")return{..._n(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function Cn(e){let r=be(e,4,"SeaDrop mintPublic");return{kind:"mint",action:"mint",contract:R(r.word(0),"mint NFT contract"),feeRecipient:R(r.word(1),"mint fee recipient"),recipient:R(r.word(2),"mint recipient"),quantity:j(r.word(3),"mint quantity")}}function Fn(e,r){let t=se(e),n=Ln[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{...Cn(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed NFT action")}function Se(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 Cr(e,r,t,{nowMs:n=Date.now(),networkFees:o,requireNetworkFees:i=!1}={}){let a=V(e.owner,"owner"),s=e.artifact,c=Number(s?.chainId??Se(e)[0]?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(B(c,r.chains,"chain"),s?.owner!==void 0&&V(s.owner,"batch owner")!==a)throw new Error("envelope: explicit batch owner mismatch");let u=Se(e);if(!u.length||u.length>8)throw new Error("envelope: bounded EVM transaction batch required");let l=0n,f=0n,w=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(V(p.from,"transaction owner")!==a)throw new Error("envelope: every batch leg must use the same owner");if(B(se(p.data),r.selectors,"selector"),l+=b(p.value??0,"value"),f+=b(p.gasLimit,"gasLimit"),w+=kr(p),q(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(w>b(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");return{transactions:u,chainId:c,owner:a,totalValue:l,totalGas:f,totalFee:w}}function Fr(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=xe(e.provider,"provider",64).toLowerCase();B(i,r.providers,"provider");let a=Cr(e,r,o,{nowMs:t}),s=[],c=-1;for(let p=0;p<a.transactions.length;p++){let m=a.transactions[p],g=Nn(m.data),x;if(g){if(c!==-1)throw new Error("envelope: approval must be before action");if(b(m.value??0,"value")!==0n)throw new Error("envelope: approval cannot transfer native value");let S=V(m.to,"approval token");if(B(S,r.tokens,"token"),B(g.spender,r.spenders,"spender"),g.amount>b(r.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");x={...g,token:S,index:p}}else{if(c!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");B(m.to,r.destinations,"destination"),x={...kn(m.data,i),target:V(m.to,"action target"),index:p},c=p}let d=b(m.value??0,"value"),E=b(m.gasLimit,"gasLimit");s.push({...x,value:d,gas:E,fee:kr(m)})}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(V(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(B(u.inputToken,r.tokens,"input token"),B(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(qe(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(p=>p.kind==="approval");if(!In.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 w=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:w}}function Rr(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=xe(e.provider||e.artifact?.provider||"opensea-nft","provider",64).toLowerCase();ze(n,r.providers,"provider");let o=e.artifact?.oraclePrepared===!0?e.artifact:e.prepared;o?.oraclePrepared===!0&&vr(o,{nowMs:t,providers:Array.isArray(r.providers)&&r.providers.length?r.providers:null,kinds:["nft-mint"],label:"local-signer"});let i=Cr(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=se(a.data);B(s,r.selectors,"selector"),B(a.to,r.destinations,"destination");let c=Fn(a.data,n),u=V(e.contract??e.artifact?.contract,"NFT contract");if(ze(u,r.nftContracts,"NFT contract"),c.contract!==u)throw new Error("envelope: mint calldata NFT contract mismatch");if(c.recipient!==i.owner)throw new Error("envelope: mint calldata recipient mismatch");ze(c.feeRecipient,r.nftFeeRecipients,"mint fee recipient");let l=b(e.quantity??e.artifact?.quantity,"quantity");if(l<=0n||l>b(r.maxMintQuantity??1,"maxMintQuantity"))throw new Error("policy: mint quantity exceeds cap");if(c.quantity!==l)throw new Error("envelope: mint calldata quantity mismatch");let f=b(e.totalWei??e.artifact?.totalWei,"totalWei");if(i.totalValue!==f)throw new Error("envelope: mint value does not match declared totalWei");if((e.priceWei!==void 0||e.artifact?.priceWei!==void 0)&&b(e.priceWei??e.artifact.priceWei,"priceWei")*l!==f)throw new Error("envelope: mint price does not match declared totalWei");if(f>b(r.maxMintTotalWei??r.maxValueWei,"maxMintTotalWei"))throw new Error("policy: mint total exceeds cap");return{...i,provider:n,decoded:[{...c,target:V(a.to,"mint target"),value:i.totalValue,gas:i.totalGas,fee:i.totalFee}]}}function Rn(e,{localsWaiver:r=!1}={}){if(!(e in Je))throw new Error("fee: unknown action");return r?0:Je[e]}function ye(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=xe(e.surface,"surface",16);if(!Br.has(s))throw new Error("envelope: unsupported public surface");let c=xe(e.action,"action",32);B(s,r.surfaces,"surface"),B(c,r.actions,"action"),B(e.owner,r.owners,"owner"),B(e.destination,r.destinations,"destination");let u=Nr(r.maxTtlMs,"maxTtlMs"),l=Nr(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")Fr(e,r,{nowMs:t,routeAttestationSecret:o});else if(s==="evm-nft")Rr(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");ge({...f,slippageBps:e.slippageBps,expiresAtMs:e.expiresAtMs},r,{nowMs:t,networkFees:i,requireNetworkFees:a});let m=String(f.data||"0x").toLowerCase(),g=b(f.value,"EVM value");if(m==="0x"){if(g===0n)throw new Error("envelope: native EVM transfer value required")}else if(P(m)){if(g!==0n)throw new Error("envelope: EVM approval cannot transfer native value")}else throw new Error("envelope: unsupported generic EVM calldata")}else s==="btc"?Ve(e,r):s==="sol"&&He(e,r);let w=Number(e.fee?.oracleFeeBps)===0&&Je[c]!==0;if(e.fee?.waiver||w&&!e.fee?.waiverAttestation)throw new Error("fee: verified waiver attestation required");if(w&&(typeof n!="function"||n(e.fee.waiverAttestation,e)!==!0))throw new Error("fee: waiver attestation invalid");let p=Rn(c,{localsWaiver:w});if(Number(e.fee?.oracleFeeBps)!==p)throw new Error("fee: final artifact fee mismatch");return!0}var Ke=Object.freeze([...Br]),oa=Object.freeze({..._r});function Xe(e,r){if(e.surface==="btc")return Ve(e,r);if(e.surface==="sol")return He(e,r);if(e.surface==="evm-swap"||e.surface==="evm-bridge"){let t=Fr(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=Rr(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 $r(e={}){let r={};for(let t of Ke){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 ve(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 Mr}from"node:crypto";import{ed25519 as $n}from"@noble/curves/ed25519.js";import{base58 as qr}from"@scure/base";import{RawTx as Ze,SigHash as z,Transaction as Ye}from"@scure/btc-signer";import{Transaction as Qe}from"ethers";var Y=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},Ae=e=>String(e||"").toLowerCase();function Mn(e,r){if(typeof e!="string")return!1;let t,n;try{t=Qe.from(e),n=Qe.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 Ae(t.from)!==Ae(r.from)||Ae(t.to)!==Ae(r.to)?!1:t.unsignedHash===n.unsignedHash}function Pn(e){let r=Buffer.from(Ze.encode(e)),t=Mr("sha256").update(r).digest();return Buffer.from(Mr("sha256").update(t).digest()).reverse().toString("hex")}function Pr(e){if(!e?.nonWitnessUtxo||!e?.witnessUtxo||Pn(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 qn(e,r){let t=Y(e),n=Y(r.psbt);if(!t||!n)return!1;try{let o=Ye.fromPSBT(n),i=Ye.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(!Pr(c)||!Pr(s))return!1;let u=(d,E)=>{if(d==null&&E==null)return!0;if(d==null||E==null)return!1;try{return Buffer.from(d).equals(Buffer.from(E))}catch{return!1}},l=(d,E)=>{if(d==null&&E==null)return!0;if(d==null||E==null)return!1;try{return Buffer.from(Ze.encode(d)).equals(Buffer.from(Ze.encode(E)))}catch{return u(d,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!==z.DEFAULT&&s.sighashType!==z.ALL)return!1;let f=d=>!(d instanceof Uint8Array)||d.length<9?!1:d[d.length-1]===z.ALL,w=d=>d instanceof Uint8Array?d.length===64?!0:d.length===65&&d[64]===z.ALL:!1;for(let d of s.partialSig||[]){let E=Array.isArray(d)?d[1]:d;if(!f(E))return!1}if(s.tapKeySig&&!w(s.tapKeySig))return!1;for(let d of s.tapScriptSig||[]){let E=Array.isArray(d)?d[1]:d;if(!w(E))return!1}let p=d=>d[d.length-1]===z.ALL,m=d=>d.length>=9&&d.length<=73&&d[1]===d.length-3&&d[2]===2,g=d=>{let E=!1;for(let S of d)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]!==z.ALL&&S[64]!==z.DEFAULT)return!1;E=!0}}return E};if(s.finalScriptWitness){let d;if(Array.isArray(s.finalScriptWitness))d=s.finalScriptWitness;else if(s.finalScriptWitness instanceof Uint8Array){let E=s.finalScriptWitness,S=L=>{let O=E[L];return O===void 0?null:O<253?{value:O,next:L+1}:O===253?{value:E[L+1]|E[L+2]<<8,next:L+3}:null},A=S(0);if(!A)return!1;d=[];let T=A.next;for(let L=0;L<A.value;L++){let O=S(T);if(!O||T+O.value>E.length)return!1;d.push(E.slice(O.next,O.next+O.value)),T=O.next+O.value}if(T!==E.length)return!1}else return!1;if(!d.length||!g(d))return!1}if(s.finalScriptSig instanceof Uint8Array&&s.finalScriptSig.length){let d=s.finalScriptSig,E=[],S=0;for(;S<d.length;){let A=d[S];if(A>=1&&A<=75){if(S+1+A>d.length)return!1;E.push(d.slice(S+1,S+1+A)),S+=1+A;continue}if(A===76){let T=d[S+1];if(T===void 0||S+2+T>d.length)return!1;E.push(d.slice(S+2,S+2+T)),S+=2+T;continue}return!1}if(!E.length||!g(E))return!1}if(![s.partialSig,s.tapKeySig,s.tapScriptSig,s.finalScriptSig,s.finalScriptWitness].some(d=>Array.isArray(d)||d instanceof Uint8Array?d.length>0:d!=null))return!1}return!0}catch{return!1}}function Ur(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 Un(e,r,t){let n=Y(e),o=Y(r.messageBase64);if(!n||!o)return!1;let i=Ur(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=qr.decode(String(t));return u.length===32&&$n.verify(s,c,u)}catch{return!1}}function Wr(e,r,t,n){return String(e).startsWith("evm")?Mn(r,t):e==="btc"?qn(r,t):e==="sol"?Un(r,t,n?.owner):!1}function Dr(e,r){try{if(String(e).startsWith("evm"))return Qe.from(r).hash;if(e==="btc"){let t=Y(r);if(!t)return null;let n=Ye.fromPSBT(t);return n.finalize(),n.extract(),n.id}if(e==="sol"){let t=Y(r);if(!t)return null;let n=Ur(t);if(!n||n.value!==1)return null;let o=t.subarray(n.offset,n.offset+64);return o.length===64?qr.encode(o):null}}catch{}return null}var Vn=e=>String(e||"").toLowerCase();function W(e){return Wn("sha256").update(JSON.stringify(e)).digest("hex")}function rr(e,r,t={}){return ge(e,r,t)}async function Gn(e,r={}){if(!q(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 Vr(e,r,t=!1){if(!q(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 Oe=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=Dn(32).toString("hex");return this.#e.set(o,{digest:W(r),owner:Vn(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(W(t),"hex");if(!jn(o,i))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(r)),n}clear(){this.#e.clear()}};function Hn(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(P(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 zn(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 Ie(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=jr.decode(t);return n.length===64&&jr.encode(n)===t}catch{return!1}return!1}function Gr(e,r,t){return!Ie(e,r)||!Ie(e,t)?!1:e==="sol"?String(r)===String(t):String(r).toLowerCase()===String(t).toLowerCase()}function Jn(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 er({artifact:e,envelope:r,nonce:t,deps:n,policy:o,confirmation:i,consumeNonce:a,nowMs:s}){let c=Jn(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 Kn(e){return e==="evm-swap"||e==="evm-bridge"||e==="evm-nft"}function Xn(e,r){return e&&Kn(e.surface)?Se(e):[r]}function Zn(e,r){let t=e?.hash??null,n=e?.transactionHash??null;if(t!=null&&n!=null&&!Gr(r,t,n))throw new Error("signer: receipt reports conflicting transaction hashes");return t||n||null}function Yn(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:zn(t,n)}}async function Hr(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,...d}=e||{};return d})(),i=Xn(n,o),a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,s=()=>typeof t.nowMs=="function"?t.nowMs():t.nowMs??Date.now(),c=await er({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:null,consumeNonce:!0,nowMs:s}),u=W(e),l=(x={})=>{n?ye(n,a,x):(rr(o,a,{nowMs:x.nowMs,networkFees:x.networkFees,requireNetworkFees:x.requireNetworkFees}),Hn(o))},f=async x=>{let d=n&&!String(n.surface||"").startsWith("evm")?void 0:await Gn(x,t);return{nowMs:s(),verifyFeeWaiver:t.verifyFeeWaiver,routeAttestationSecret:t.routeAttestationSecret,networkFees:d,requireNetworkFees:q(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 w=t.reserveLedger(n||e,a);if(!w)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 d=await f(x);if(Vr(x,d.networkFees,d.requireNetworkFees),!t.isArmed())throw new Error("signer: disarmed before signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=await er({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:c,consumeNonce:!1,nowMs:s}),l(d),t.validateReservation(w,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(W(e)!==u)throw new Error("signer: artifact mutated after signing");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=await er({artifact:e,envelope:n,nonce:r,deps:t,policy:a,confirmation:c,consumeNonce:!1,nowMs:s});let S=await f(x);Vr(x,S.networkFees,S.requireNetworkFees),l(S),t.validateReservation(w,a,n&&typeof t.decodeEconomics=="function"?t.decodeEconomics(n,a):void 0);let A=await t.broadcast(E,x,n),T=A?.status,L=n?.surface||"evm",O=Zn(A,L),$e=Dr(L,E);if(!Gr(L,O,$e))throw new Error("signer: receipt transaction hash does not match signed bytes");if(T===0||T==="0x0")throw Ie(L,O)?(t.settleFailedLedger(w),new Error("signer: broadcast did not return a successful receipt")):new Error("signer: failed broadcast requires a valid transaction hash");if(T!==1&&T!=="0x1")throw new Error("signer: broadcast did not return a successful receipt");if(!Ie(L,O))throw new Error("signer: successful broadcast requires a valid transaction hash");m.push(Yn(A,O))}}catch(x){throw p||t.releaseLedger(w),x}if(t.commitLedger(w),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 g={receipts:m,status:"success"};return n?.surface==="evm-bridge"&&(g.originStatus="success",g.destinationStatus="unverified",g.destinationSuccess=!1,g.note="Origin-chain receipts do not prove destination-chain settlement."),g}var zr=new Set(["127.0.0.1","::1","localhost"]),ro=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&eo(t,n)},_=(e,r,t)=>{let n=JSON.stringify(t);e.writeHead(r,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(n)}),e.end(n)};function to(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 Jr=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 Kr(e={}){let r=e.host||"127.0.0.1";if(!zr.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 Oe,n=e.origin||`http://${r}`;return Qn.createServer(async(i,a)=>{try{let s=String(i.headers.authorization||"").replace(/^Bearer /i,"");if(!ro(s,e.token))return _(a,401,{error:"unauthorized"});let c=to(i.headers.host);if(!zr.has(c))return _(a,403,{error:"host refused"});if(i.headers.origin&&i.headers.origin!==n)return _(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(Ke),f=Array.isArray(u?.surfaces)?u.surfaces.filter(w=>typeof w=="string"&&l.has(w)):[];return _(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(),_(a,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(i.method))return _(a,405,{error:"request refused"});if(i.method==="POST"&&String(i.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return _(a,415,{error:"request refused"});if(i.method==="POST"&&i.url==="/confirm"){if(e.autonomous===!0)return _(a,403,{error:"autonomous signer does not issue human confirmation nonces"});let u=await Jr(i),l=W(u.artifact),f=typeof e.readPolicy=="function"?e.readPolicy():e.policy;if(f?.confirmationMode!=="exact-human")return _(a,403,{error:"exact-human policy required"});let w=typeof e.nowMs=="function"?e.nowMs():Date.now();if(u.artifact?.version===1&&u.artifact?.surface)ye(u.artifact,f,{nowMs:w,verifyFeeWaiver:e.verifyFeeWaiver});else{let{tradeId:p,...m}=u.artifact||{};rr(m,f,{nowMs:w})}return typeof e.confirmArtifact!="function"?_(a,403,{error:"local human confirmation unavailable"}):await e.confirmArtifact(u.artifact,l,f)!==!0?_(a,400,{error:"exact human confirmation refused"}):_(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 Jr(i),l=await Hr(u.artifact,u.confirmationNonce,{...e,confirmations:t});return _(a,200,l)}return _(a,404,{error:"not found"})}catch(s){return e.onError?.(String(s?.message||s)),_(a,400,{error:"request refused"})}})}import{createCipheriv as Oa,createDecipheriv as no,randomBytes as oo,scryptSync as io}from"node:crypto";import v from"node:fs";import Q from"node:path";var ao="ORACLE-LOCAL-VAULT",so=1,Te=Object.freeze({N:1<<17,r:8,p:1}),co=256*1024*1024,uo=16*1024;function Le(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 fo(e,r,t=Te){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return io(n,r,32,{...t,maxmem:co})}function Xr(e,r){if(e?.magic!==ao||e?.version!==so)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!==Te.N||e.kdf.r!==Te.r||e.kdf.p!==Te.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=Le(e.kdf.salt,32,"salt"),o=Le(e.cipher.iv,12,"iv"),i=Le(e.tag,16,"tag"),a=Le(e.ciphertext,1,"ciphertext",{max:uo}),{ciphertext:s,tag:c,...u}=e,l=fo(r,n);try{let f=no("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 lo(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 po(e){let r=Q.dirname(e),t=v.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=v.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=v.openSync(e,v.constants.O_RDONLY|v.constants.O_NOFOLLOW)}catch(t){throw t.code==="ELOOP"?new Error("local-vault: refusing symlink"):t}try{let t=v.fstatSync(r);if(lo(t),t.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");let n=v.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 v.readFileSync(r,"utf8").replace(/[\r\n]+$/,"")}finally{v.closeSync(r)}}function Zr(e){return JSON.parse(I(e))}function G(e,r){v.mkdirSync(Q.dirname(e),{recursive:!0,mode:448}),po(e);let t=Q.join(Q.dirname(e),`.${Q.basename(e)}.${process.pid}.${oo(6).toString("hex")}.tmp`);try{let n=v.openSync(t,v.constants.O_CREAT|v.constants.O_EXCL|v.constants.O_WRONLY|v.constants.O_NOFOLLOW,384);try{v.writeFileSync(n,String(r)),v.fsyncSync(n)}finally{v.closeSync(n)}v.renameSync(t,e),v.chmodSync(e,384);let o=v.openSync(Q.dirname(e),"r");try{v.fsyncSync(o)}finally{v.closeSync(o)}}catch(n){try{v.unlinkSync(t)}catch{}throw n}}import{createHmac as ho,randomBytes as wo,timingSafeEqual as go}from"node:crypto";import k from"node:fs";import J from"node:path";import{homedir as tr}from"node:os";import{join as nr}from"node:path";var Yr=process.env.ORACLE_PUBLIC_DESKTOP==="1",mo=Yr?process.env.ORACLE_CONFIG_DIR||nr(tr(),".config","oracle"):nr(tr(),".config","oracle"),_a=Yr?mo:nr(tr(),".config","mad-desk");var $a="0".repeat(64),Ma=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 Ne(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(Ne).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+Ne(e[t])).join(",")+"}"}var Pa=Promise.resolve();function ee(e,r){if(!e)throw new Error("ledger: separate freshness anchor required");let t=a=>{try{return k.realpathSync(a)}catch{return J.resolve(a)}},n=t(J.dirname(J.resolve(e))),o=t(J.dirname(J.resolve(r))),i=(a,s)=>s===a||s.startsWith(a+J.sep);if(i(n,o)||i(o,n))throw new Error("ledger: separate freshness anchor required")}var Eo=864e5,C=(e,r)=>ho("sha256",r).update(Ne(e)).digest("hex"),U=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&go(t,n)},xo=e=>{if(!e||typeof e!="object"||Array.isArray(e)||!("triggerAttestation"in e))return e;let{triggerAttestation:r,...t}=e;return t};function So(e,r){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!U(e.integrity.mac,C(e.policy,r)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function _e(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(!U(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 bo(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=_e(e,t);i=s.present&&s.ledgerInitialized===!0}catch{i=!1}let a={policySequence:Number(r),policyMac:String(n)};i&&(a.ledgerInitialized=!0),G(e,JSON.stringify({marker:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:C(a,t)}})+`
|
|
2
|
-
`)}function yo(e,r){let t=_e(e,r);if(!t.present)throw new Error("policy: sequence anchor required");if(t.ledgerInitialized)return!0;if(t.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");return bo(e,t.sequence,r,t.policyMac,{ledgerInitialized:!0}),!0}function Qr(e,r,{sequenceAnchorFile:t}={}){if(!t)throw new Error("policy: sequence anchor required");let n=I(r),o;try{o=JSON.parse(I(e))}catch(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=So(o,n);ee(t,e);let a=_e(t,n),s=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(s!==a.sequence)throw new Error("policy: rolled back to a superseded policy");if(a.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!U(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function ue(e,r,t,n,o){let i=`${e}.continuity`,a;try{let s=JSON.parse(I(e));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!U(s?.integrity?.mac,C(s.ledger,r)))throw new Error("integrity verification failed");if(a=s.ledger,!Number.isFinite(a?.windowStartMs)||!Array.isArray(a?.entries)||a.sequence!==void 0&&(!Number.isSafeInteger(a.sequence)||a.sequence<0))throw new Error("invalid ledger")}catch(s){if(s?.code==="ENOENT"){if(k.existsSync(i)||k.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=_e(o,r);if(c.present&&c.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:t,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${s?.message||s}`)}try{let s=JSON.parse(I(i));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!U(s?.integrity?.mac,C(s.marker,r)))throw new Error("continuity verification failed");if(s.marker?.version===2&&(s.marker.sequence!==a.sequence||!U(s.marker.ledgerMac,C(a,r))))throw new Error("continuity rollback detected");if(s.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(k.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(I(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!U(c?.integrity?.mac,C(c.marker,r))||c.marker?.version!==1||c.marker.sequence!==a.sequence||!U(c.marker.ledgerMac,C(a,r)))throw new Error("checkpoint rollback detected")}}catch(s){throw new Error(`ledger: corrupt or unreadable: ${s?.message||s}`)}if(t-a.windowStartMs>=Eo){let s=a.entries.map(c=>c.state==="reserved"?c:{...c,state:"consumed",value:"0",notional:"0"});return{windowStartMs:t,entries:s,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function Be(e,r,t){return e.filter(n=>(n.unit||"wei")===t).reduce((n,o)=>n+BigInt(o[r]??0),0n)}function et(e,r){let t=r==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:r==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:r==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:null;if(!t)throw new Error("ledger: unsupported accounting unit");for(let n of t)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return t.map(n=>BigInt(e[n]))}function fe(e,r){let t=`${e}.lock`,n=wo(16).toString("hex"),o;try{o=k.openSync(t,k.constants.O_CREAT|k.constants.O_EXCL|k.constants.O_WRONLY|(k.constants.O_NOFOLLOW||0),384),k.writeFileSync(o,n),k.fsyncSync(o)}catch(i){throw o!==void 0&&k.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return r()}finally{k.closeSync(o);try{I(t)===n&&k.unlinkSync(t)}catch{}}}function ce(e,r,t,n,o){let i=`${e}.continuity`,a={...r,sequence:(r.sequence??0)+1},s=C(a,t);G(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:s}})+`
|
|
3
|
-
`);let c={version:2,sequence:a.sequence,ledgerMac:s};G(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:C(c,t)}})+`
|
|
4
|
-
`);let
|
|
5
|
-
`)
|
|
6
|
-
`)
|
|
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 xi(e,r){let t=Ue(e,r);if(!t.present)throw new Error("policy: sequence anchor required");if(t.ledgerInitialized)return!0;if(t.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");return Ei(e,t.sequence,r,t.policyMac,{ledgerInitialized:!0}),!0}function bt(e,r,{sequenceAnchorFile:t}={}){if(!t)throw new Error("policy: sequence anchor required");let n=I(r),o;try{o=JSON.parse(I(e))}catch(c){throw new Error(`policy: cannot read sealed policy: ${c?.message||c}`)}let i=gi(o,n);ce(t,e);let a=Ue(t,n),s=Number(i.policySequence||0);if(!a.present)throw new Error("policy: sequence anchor is missing for an existing policy");if(s!==a.sequence)throw new Error("policy: rolled back to a superseded policy");if(a.policyMac==null)throw new Error("policy: sequence anchor does not bind this sealed policy");if(!G(a.policyMac,o?.integrity?.mac))throw new Error("policy: anchor does not match this sealed policy");return i}function Ee(e,r,t,n,o){let i=`${e}.continuity`,a;try{let s=JSON.parse(I(e));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!G(s?.integrity?.mac,C(s.ledger,r)))throw new Error("integrity verification failed");if(a=s.ledger,!Number.isFinite(a?.windowStartMs)||!Array.isArray(a?.entries)||a.sequence!==void 0&&(!Number.isSafeInteger(a.sequence)||a.sequence<0))throw new Error("invalid ledger")}catch(s){if(s?.code==="ENOENT"){if(R.existsSync(i)||R.existsSync(n))throw new Error("ledger: missing after initialization");if(o){let c=Ue(o,r);if(c.present&&c.ledgerInitialized)throw new Error("ledger: missing after initialization")}return{windowStartMs:t,entries:[],sequence:0}}throw new Error(`ledger: corrupt or unreadable: ${s?.message||s}`)}try{let s=JSON.parse(I(i));if(s?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!G(s?.integrity?.mac,C(s.marker,r)))throw new Error("continuity verification failed");if(s.marker?.version===2&&(s.marker.sequence!==a.sequence||!G(s.marker.ledgerMac,C(a,r))))throw new Error("continuity rollback detected");if(s.marker?.version!==2&&a.sequence!==void 0)throw new Error("continuity rollback detected");if(R.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(I(n));if(c?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!G(c?.integrity?.mac,C(c.marker,r))||c.marker?.version!==1||c.marker.sequence!==a.sequence||!G(c.marker.ledgerMac,C(a,r)))throw new Error("checkpoint rollback detected")}}catch(s){throw new Error(`ledger: corrupt or unreadable: ${s?.message||s}`)}if(t-a.windowStartMs>=hi){let s=a.entries.map(c=>c.state==="reserved"?c:{...c,state:"consumed",value:"0",notional:"0"});return{windowStartMs:t,entries:s,sequence:a.sequence??0}}return{...a,sequence:a.sequence??0}}function $e(e,r,t){return e.filter(n=>(n.unit||"wei")===t).reduce((n,o)=>n+BigInt(o[r]??0),0n)}function yt(e,r){let t=r==="wei"?["maxDailyValueWei","maxDailyNotional","maxPerTrade"]:r==="sats"?["maxDailyValueSats","maxDailyNotionalSats","maxPerTradeSats"]:r==="lamports"?["maxDailyValueLamports","maxDailyNotionalLamports","maxPerTradeLamports"]:null;if(!t)throw new Error("ledger: unsupported accounting unit");for(let n of t)if(e[n]===void 0||e[n]===null||e[n]==="")throw new Error(`ledger: ${n} required`);return t.map(n=>BigInt(e[n]))}function xe(e,r){let t=`${e}.lock`,n=pi(16).toString("hex"),o;try{o=R.openSync(t,R.constants.O_CREAT|R.constants.O_EXCL|R.constants.O_WRONLY|(R.constants.O_NOFOLLOW||0),384),R.writeFileSync(o,n),R.fsyncSync(o)}catch(i){throw o!==void 0&&R.closeSync(o),i?.code==="EEXIST"?new Error("ledger: busy"):i}try{return r()}finally{R.closeSync(o);try{I(t)===n&&R.unlinkSync(t)}catch{}}}function ge(e,r,t,n,o){let i=`${e}.continuity`,a={...r,sequence:(r.sequence??0)+1},s=C(a,t);Y(e,JSON.stringify({ledger:a,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:s}})+`
|
|
5
|
+
`);let c={version:2,sequence:a.sequence,ledgerMac:s};Y(i,JSON.stringify({marker:c,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:C(c,t)}})+`
|
|
6
|
+
`);let u={version:1,sequence:a.sequence,ledgerMac:s};R.mkdirSync(re.dirname(n),{recursive:!0,mode:448}),Y(n,JSON.stringify({marker:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:C(u,t)}})+`
|
|
7
|
+
`),o&&xi(o,t)}function vt({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,unit:i="wei",value:a=0,notional:s=0,fee:c,policy:u,nowMs:l=Date.now()}){let f=String(o??"");if(!/^[A-Za-z0-9._:-]{1,128}$/.test(f))throw new Error("ledger: bounded tradeId required");ce(t,e);let d=I(r);return xe(e,()=>{let p=Ee(e,d,l,t,n);if(p.entries.some(y=>String(y.tradeId)===f))throw new Error("ledger: replayed tradeId");let m=BigInt(a),w=BigInt(s),[x,h,E]=yt(u,i);if(m<0n||w<0n||w>E)throw new Error("ledger: per-trade cap exceeded");if($e(p.entries,"value",i)+m>x||$e(p.entries,"notional",i)+w>h)throw new Error("ledger: daily cap exceeded");let S={tradeId:f,unit:i,value:m.toString(),notional:w.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:l};return p.entries.push(S),ge(e,p,d,t,n),structuredClone(S)})}function At({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:s=Date.now()}){ce(t,e);let c=I(r);return xe(e,()=>{let u=Ee(e,c,s,t,n),l=u.entries.find(w=>String(w.tradeId)===String(o?.tradeId??"")&&w.state==="reserved");if(!l||l.unit!==o.unit||l.value!==o.value||l.notional!==o.notional)throw new Error("ledger: reservation unavailable");if(a){if(a.unit!==l.unit)throw new Error("ledger: reserved unit no longer matches decoded economics");if(BigInt(a.value)>BigInt(l.value)||BigInt(a.notional)>BigInt(l.notional))throw new Error("ledger: reservation understates economics decoded under the current policy")}let f=l.unit||"wei",[d,p,m]=yt(i,f);if(BigInt(l.notional)>m)throw new Error("ledger: per-trade cap exceeded");if($e(u.entries,"value",f)>d||$e(u.entries,"notional",f)>p)throw new Error("ledger: daily cap exceeded");return structuredClone(l)})}function Tt({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ce(t,e);let a=I(r);return xe(e,()=>{let s=Ee(e,a,i,t,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,ge(e,s,a,t,n),structuredClone(c)})}function Ot({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ce(t,e);let a=I(r);return xe(e,()=>{let s=Ee(e,a,i,t,n),c=s.entries.findIndex(l=>String(l.tradeId)===String(o??"")&&l.state==="reserved");if(c<0)throw new Error("ledger: reservation unavailable");let[u]=s.entries.splice(c,1);return ge(e,s,a,t,n),structuredClone(u)})}function It({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ce(t,e);let a=I(r);return xe(e,()=>{let s=Ee(e,a,i,t,n),c=s.entries.find(l=>String(l.tradeId)===String(o??"")&&l.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",ge(e,s,a,t,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=u.toString(),c.settledAs="fee-only",ge(e,s,a,t,n),structuredClone(c))})}function Nt(e,r,t,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:X(wi(r))};return G(e.mac,C(o,I(t)))}function Si(e){let r={...e?.fee||{}};return delete r.waiverAttestation,{...e,fee:r}}function Lt(e,r,t,n=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.waiverId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>n||e.expiresAtMs<=n||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let o={waiverId:e.waiverId,owner:String(r.owner).toLowerCase(),action:String(r.action),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:X(Si(r))};return G(e.mac,C(o,I(t)))}import{spawnSync as bi}from"node:child_process";function kt(e="oracle-local-signer",r=process.env.USER||process.env.USERNAME||"oracle"){let t,n;if(process.platform==="darwin")t="/usr/bin/security",n=["find-generic-password","-s",e,"-a",r,"-w"];else if(process.platform==="linux")t="secret-tool",n=["lookup","service",e,"account",r];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let o=bi(t,n,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),i=String(o.stdout||"").replace(/[\r\n]+$/,"");if(o.status!==0||i.length<12)throw new Error("signer: OS credential passphrase unavailable");return i}import{Wallet as gr}from"ethers";import{base58 as Rt}from"@scure/base";import{ed25519 as yi}from"@noble/curves/ed25519.js";import{NETWORK as Ct,TEST_NETWORK as Ft,WIF as vi,p2wpkh as _t}from"@scure/btc-signer";import{pubECDSA as Ai}from"@scure/btc-signer/utils.js";var Ti=e=>{let r=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(r)||r.length%2?null:Buffer.from(r,"hex")},Oi=e=>{let r=String(e||"").trim();if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r))return null;let t=Buffer.from(r,"base64");return t.toString("base64")===r?t:null},ue=(e,r)=>{if(!(e instanceof Uint8Array))throw new Error(`${r}: key bytes required`);if(e.length===32)return Buffer.from(e);if(e.length===64)return Buffer.from(e.subarray(0,32));throw new Error(`${r}: expected 32-byte private key material`)};function Er(e,r){let t=String(r||"").trim();if(e==="evm")return new gr(t).privateKey;if(e==="btc")for(let i of[Ct,Ft])try{return Buffer.from(vi(i).decode(t))}catch{}if(e==="sol")try{return ue(Rt.decode(t),"sol")}catch{}let n=Ti(t);if(n)return e==="evm"?new gr(`0x${n.toString("hex")}`).privateKey:ue(n,e);let o=Oi(t);if(o)return ue(o,e);if(t.startsWith("[")||t.startsWith("{")){let i=JSON.parse(t);if(Array.isArray(i))return ue(Uint8Array.from(i),e);let a=i.privateKey??i.secretKey??i.key;if(a)return Er(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function Bt(e,r){if(e==="evm"){let t=new gr(String(r));return{kind:e,secret:t.privateKey,addresses:[t.address.toLowerCase()]}}if(e==="btc"){let t=ue(r,"btc"),n=Ai(t);return{kind:e,secret:t.toString("hex"),addresses:[_t(n,Ct).address,_t(n,Ft).address]}}if(e==="sol"){let t=ue(r,"sol");return{kind:e,secret:t.toString("hex"),addresses:[Rt.encode(yi.getPublicKey(t))]}}throw new Error(`unsupported signer kind ${e}`)}function Mt(e,r={}){let t=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");if(String(r.kind||"")!=="multichain")return{[r.kind||"evm"]:Bt(r.kind||"evm",Er(r.kind||"evm",t))};let n=JSON.parse(t),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=Bt(i,Er(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function xr(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}function _i(e){let r=process.env.ORACLE_SIGNER_STATE_DIR||D.join(process.env.XDG_STATE_HOME||D.join(Ii.homedir(),".local","state"),"oracle"),t=Ni("sha256").update(D.resolve(e)).digest("hex").slice(0,16);return{vault:D.join(e,"vault.json"),policy:D.join(e,"signer-policy.json"),policyKey:D.join(e,"policy-integrity-key"),policyAnchor:D.join(r,`signer-policy-${t}.high-water`),ledger:D.join(e,"signer-ledger.json"),ledgerAnchor:D.join(r,`signer-ledger-${t}.high-water`),token:D.join(e,"signer-token"),lock:D.join(r,`signer-${t}.lock`)}}function Bi(e){try{return I(e)}catch(t){if(t.code!=="ENOENT")throw t}let r=Li(32).toString("hex");return Y(e,r+`
|
|
8
|
+
`),r}function br(e,r,t){if(!r)throw new Error(`signer: ${e} key is required by policy`);let n=new Set((t||[]).map(o=>String(o).toLowerCase()));if(!r.addresses.some(o=>n.has(String(o).toLowerCase())))throw new Error(`signer: ${e} vault address is not an allowed policy owner`);return!0}function qt(e){return e.surfaces.some(r=>String(r).startsWith("evm"))}function De(e,r){return e.surfaces.includes(r)}function Ri(e,r,t){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"}`),W(String(c.data||"0x")))try{let l=de(String(c.data||"0x"));i.push(`LEG ${u} APPROVAL token=${l.token||c.to||"n/a"} spender=${l.spender} amount=${l.amount}`)}catch{i.push(`LEG ${u} APPROVAL spender=undecodable amount=undecodable`)}},s=String(o.data||"0x");if(W(s))try{let c=de(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=Ye(n,t);i.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(n?.surface==="sol"){let c=or(n,t);i.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}return`
|
|
7
9
|
Confirm exact action
|
|
8
10
|
${i.join(`
|
|
9
11
|
`)}
|
|
10
|
-
Type digest ${r}: `}async function
|
|
11
|
-
`),!0),
|
|
12
|
-
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,
|
|
13
|
-
`),0;let t=
|
|
14
|
-
`),await new Promise(o=>n.on("close",o)),0}var
|
|
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),Se=gt({host:o,port:i,token:Bi(u.token),policy:f,readPolicy:l,isArmed:Gt,disarm:Ht,sessionExpiresAtMs:vr,nowMs:Date.now,simulate:(g,A)=>Be(A,v).simulate(g,A),estimateNetworkFees:N,sign:(g,A)=>Be(A,v).sign(g,A),verifySigned:(g,A,L)=>ut(L?.surface||"evm",g,A,L),broadcast:(g,A,L)=>Be(L,v).broadcast(g,A,L),confirmArtifact:Ui,decodeEconomics:(g,A)=>ur(g,A),reserveLedger:(g,A)=>{let L=g?.version===1&&g?.surface?g:null,j=L?.artifact||g,fe=L?.tradeId||j?.tradeId;if(!fe)throw new Error("ledger: executable artifact requires a tradeId");let Z;if(L)Z=ur(L,A);else{if(j?.value===void 0)throw new Error("ledger: executable artifact value required");let be=BigInt(j.value),Tr=BigInt(j.gasLimit??0),Or=BigInt(j.maxFeePerGas??j.gasPrice??0);if(Tr<=0n||Or<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let Ir=Tr*Or+BigInt(j.l1FeeWei??0)+BigInt(j.operatorFeeWei??0);Z={unit:"wei",value:be.toString(),notional:(be+Ir).toString(),fee:Ir.toString()}}if(Z.value===void 0||Z.notional===void 0)throw new Error("ledger: decoded value and notional required");return vt({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:fe,...Z,policy:A})},commitLedger:g=>Tt({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),releaseLedger:g=>Ot({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),settleFailedLedger:g=>It({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:g.tradeId}),validateReservation:(g,A,L)=>At({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,reservation:g,policy:A,economics:L}),verifyFeeWaiver:(g,A)=>Lt(g,A,u.policyKey),verifyTriggerAttestation:(g,A,L)=>Nt(g,A,u.policyKey,L),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),Ar=setTimeout(()=>Se.close(),a);return Ar.unref(),Se.on("close",()=>{clearTimeout(Ar)}),Se.listen(i,o),Se}var We="0x420000000000000000000000000000000000000F";function Ut(e){let r=e?.code;if(r==="CALL_EXCEPTION"||r==="BAD_DATA")return!0;let t=String(e?.shortMessage||e?.message||e);return/network|timeout|ECONN|ENOTFOUND|EAI_AGAIN|server error|fetch failed|socket/i.test(t)?!1:/execution reverted|revert|invalid opcode|function selector|could not decode/i.test(t)}async function qi(e,r){if(!J(r?.chainId))return{l1FeeWei:"0",operatorFeeWei:"0"};if(!e||typeof e.call!="function")throw new Error("policy: rollup fee estimate required");let{Interface:t,Transaction:n}=await import("ethers"),o=new t(["function getL1Fee(bytes) view returns (uint256)","function getOperatorFee(uint256) view returns (uint256)","function operatorFeeScalar() view returns (uint32)","function operatorFeeConstant() view returns (uint64)"]),i;try{i=n.from({chainId:r.chainId,to:r.to,data:r.data,value:r.value,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce??0,type:r.type,accessList:r.accessList}).unsignedSerialized}catch{throw new Error("policy: rollup fee estimate required")}let a;try{let s=await e.call({to:We,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 $i(e,o,r.gasLimit)}}async function $i(e,r,t){let n;try{n=BigInt(t)}catch{throw new Error("policy: rollup fee estimate required")}if(n<0n)throw new Error("policy: rollup fee estimate required");try{let o=await e.call({to:We,data:r.encodeFunctionData("getOperatorFee",[n])});return r.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Ut(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:We,data:r.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:We,data:r.encodeFunctionData("operatorFeeConstant")}),a=BigInt(r.decodeFunctionResult("operatorFeeScalar",o)[0]),s=BigInt(r.decodeFunctionResult("operatorFeeConstant",i)[0]);return(n*a/1000000n+s).toString()}catch(o){if(!Ut(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function Ui(e,r,t){return process.stdin.isTTY?(process.stderr.write(Ri(e,r,t)),process.stdin.resume(),new Promise(n=>{let o=i=>{process.stdin.off("data",o),process.stdin.pause(),n(String(i).trim()===r)};process.stdin.once("data",o)})):!1}var Wt=`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.`,Je=(e,r,t)=>{let n=e.indexOf(r);return n>=0?e[n+1]:t};async function ji(e=[],r={}){if(e.includes("--help"))return(r.out||process.stdout).write(Wt+`
|
|
15
|
+
`),0;let t=Je(e,"--passphrase-file"),n=await jt({configDir:Di.join(r.configDir||ve(),"signer"),passphraseFile:t,credentialService:Je(e,"--credential-service"),port:Number(Je(e,"--port",9462)),sessionMs:Number(Je(e,"--session-seconds",120))*1e3});return(r.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
|
|
16
|
+
`),await new Promise(o=>n.on("close",o)),0}var yc={name:"signer",summary:"run the short-lived loopback signer",usage:Wt,run:e=>ji(e.argv||[])};export{yc as default,ji as run};
|