@oracle-agent/oracle 0.24.8 → 0.24.9
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 +49 -45
- package/SECURITY.md +1 -1
- package/SETUP.md +16 -13
- package/dist/assets/profiles/_template/SOUL.md +2 -2
- package/dist/assets/profiles/oracle/SOUL.md +11 -13
- package/dist/assets/profiles/profile.schema.json +1 -1
- package/dist/assets/profiles/robinhood-agent/SOUL.md +5 -5
- package/dist/assets/skills/multi-venue-prepare-only-ranking/SKILL.md +1 -1
- package/dist/assets/skills/oracle-action-semantics/SKILL.md +5 -5
- package/dist/assets/skills/oracle-chat/SKILL.md +8 -8
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/assets/skills/oracle-receipts/SKILL.md +2 -2
- package/dist/bin/desk-server.mjs +80 -36
- package/dist/bin/oracle-data-mcp.mjs +51 -7
- package/dist/bin/oracle-gateway.mjs +13 -15
- package/dist/bin/oracle-init.mjs +9 -9
- package/dist/bin/oracle-public-server.mjs +48 -4
- package/dist/bin/oracle-route.mjs +66 -22
- package/dist/bin/oracle-scan.mjs +58 -14
- package/dist/cli/commands/chat.mjs +140 -96
- package/dist/cli/commands/doctor.mjs +6 -6
- package/dist/cli/commands/eval.mjs +17 -17
- package/dist/cli/commands/farm.mjs +72 -28
- package/dist/cli/commands/follow.mjs +61 -17
- package/dist/cli/commands/model.mjs +147 -103
- package/dist/cli/commands/receipt.mjs +3 -3
- package/dist/cli/commands/resolve.mjs +55 -11
- package/dist/cli/commands/setup.mjs +27 -27
- package/dist/cli/commands/sign.mjs +14 -13
- package/dist/cli/commands/signer.mjs +12 -17
- package/dist/cli/commands/strategy.mjs +50 -6
- package/dist/cli/commands/swap.mjs +72 -29
- package/dist/cli/commands/venues.mjs +3 -3
- package/dist/data/desk-data.mjs +78 -34
- package/dist/data/names.mjs +46 -2
- package/dist/data/providers/farming.mjs +46 -2
- package/dist/index.mjs +83 -39
- package/dist/local-signer/index.mjs +1 -1
- package/dist/router/index.mjs +46 -2
- package/dist/router/prepare-bridge.mjs +46 -2
- package/dist/scanner/index.mjs +48 -4
- package/dist/strategy/index.mjs +47 -3
- package/package.json +5 -3
- package/public/install.ps1 +1 -1
- package/public/install.sh +5 -4
- package/public/oracle-splash/_variants/ice.html +3 -3
- package/public/oracle-splash/_variants/ivory.html +3 -3
- package/public/oracle-splash/downloads/index.html +5 -5
- package/public/oracle-splash/index.html +7 -7
- package/public/oracle-splash/install.ps1 +1 -1
- package/public/oracle-splash/install.sh +5 -4
|
@@ -1,19 +1,14 @@
|
|
|
1
|
-
import at from"node:path";import K from"node:fs";import Je from"node:os";import M from"node:path";import{fileURLToPath as ze}from"node:url";var Ke=M.dirname(ze(import.meta.url)),dt=M.resolve(Ke,"../..");function Se(){return process.env.ORACLE_FAKE_HOME||Je.homedir()}function Xe(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function X(){return Xe()?process.env.ORACLE_CONFIG_DIR||M.join(Se(),".config","oracle"):M.join(Se(),".config","oracle")}function Ye(){return M.join(X(),"desk.json")}function Ze(){return M.join(X(),"env")}function B({force:e=!1}={}){if(B._done&&!e)return B._result||null;B._done=!0;let r={},t=(o,a)=>{if(a==null)return;let i=String(a).trim();i&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=i,r[o]=i))};try{let o=Ze();if(K.existsSync(o))for(let a of K.readFileSync(o,"utf8").split(/\r?\n/)){let i=a.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let f=i[2];(f.startsWith('"')&&f.endsWith('"')||f.startsWith("'")&&f.endsWith("'"))&&(f=f.slice(1,-1)),t(i[1],f)}}catch{}try{let o=Ye();if(K.existsSync(o)){let a=JSON.parse(K.readFileSync(o,"utf8"));a&&typeof a=="object"&&(t("ORACLE_DESK_URL",a.deskUrl||a.dataUrl||a.url),t("ORACLE_DATA_URL",a.dataUrl||a.deskUrl||a.url),t("ORACLE_API_URL",a.apiUrl||a.dataUrl||a.deskUrl),t("ORACLE_PUBLIC_URL",a.publicUrl||a.deskUrl||a.dataUrl),t("ORACLE_EXEC_URL",a.execUrl),t("MAD_DESK_URL",a.deskUrl||a.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)),B._result=Object.keys(r).length?r:null,B._result}try{B()}catch{}import Ve from"node:fs";import L from"node:path";import{randomBytes as et}from"node:crypto";import kr from"node:http";import{timingSafeEqual as Lr}from"node:crypto";import{createHash as Or,randomBytes as _r,timingSafeEqual as Nr}from"node:crypto";import{Interface as mr,MaxUint256 as Xt,isAddress as Yt,keccak256 as Zt,toUtf8Bytes as Qt}from"ethers";import{Interface as lr,isAddress as Ct}from"ethers";import{isAddress as yt}from"ethers";import{createHash as nr,createHmac as or,timingSafeEqual as ar}from"node:crypto";import{readFileSync as Qe}from"node:fs";import{homedir as er}from"node:os";import{join as Y}from"node:path";function rr(){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=er();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||Y(r,".config","oracle")).trim();return[e,Y(t,"exec.env")].filter(Boolean)}return[e,Y(r,".config","oracle","exec.env"),Y(r,".config","mad-desk","exec.env")].filter(Boolean)}function V(e,r,t){let n=e??process.env[r]??process.env[t];if(!String(n||"").trim())for(let o of rr())try{let a=Qe(o,"utf8"),i=a.match(new RegExp(`^${r}=(.*)$`,"m"))||a.match(new RegExp(`^${t}=(.*)$`,"m"));if(i&&(n=i[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 D(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 ${tr(r)})`);let o=Number(e?.issuedAtMs),a=Number(e?.expiresAtMs);if(!Number.isFinite(a))throw new Error(`${t}: expiresAtMs is required and must be a finite number`);if(n>a)throw new Error(`${t} expired at ${a}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${t}: issuedAtMs must be a finite number when present`);if(a<=o)throw new Error(`${t}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:a}}function tr(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var ve=100;function oe(e){return Array.isArray(e)?`[${e.map(oe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${oe(e[r])}`).join(",")}}`:JSON.stringify(e??null)}function ir(e,{required:r=!1}={}){try{return V(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(t){if(r)throw t;return null}}function sr(e){let{signature:r,...t}=e;return t}function cr(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 nr("sha256").update(Buffer.from(r.slice(2),"hex")).digest("hex")}function ur(e,r){let t=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(r??""),"utf8");return t.length!==n.length||t.length===0?!1:ar(t,n)}function fr(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 a=10;a+64<=r.length;a+=64)n.push(r.slice(a,a+64));let o=a=>n[a]==null?null:BigInt("0x"+n[a]);switch(t){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let a=o(0);if(a==null)return null;let i=Number(a)/32;return!Number.isInteger(i)||i<0?null:o(i+4)}case"0xb858183f":{let a=o(0);if(a==null)return null;let i=Number(a)/32;return!Number.isInteger(i)||i<0?null:o(i+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 ae(e,{nowMs:r=Date.now(),chainId:t,venue:n,secret:o,tx:a,requireSigned:i=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let f=ir(o,{required:i});if(i&&!f)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(f){let m=or("sha256",f).update(oe(sr(e))).digest("hex");if(!ur(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 d=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(d)||d<0||d>ve)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(s)||s<0||s>ve||d>s)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{D({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),c=BigInt(e.minAmountOut??0);if(l<=0n||c<=0n)throw new Error("auto-slippage guard amounts must be positive");let E=l*BigInt(1e4-d)/10000n;if(c<E)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(a?.data&&e.minAmountOut!=null)if(e.calldataHash!=null){if(String(e.calldataHash)!==cr(a.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch")}else{let m=fr(a.data);if(m==null){let h=String(a.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${h}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(m!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${m}`)}return!0}var Rt=new lr(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as pr,isAddress as Dt}from"ethers";var qt=new pr(["function approve(address spender,uint256 amount) returns (bool)"]),Ut=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var an=new mr(["function approve(address spender,uint256 amount) returns (bool)"]);var ie=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]);var ye=new Set(["evm","evm-swap","evm-bridge","btc","sol"]),Ae=Object.freeze({swap:5,bridge:5,perps:0,nft:0}),Oe=new Set(["evm-swap","evm-bridge"]),hr=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),ce=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"}}),gr=new Set(["0x04e45aaf","0x414bf389","0xc04b8d59","0xb858183f","0xa026383e","0x38ed1739","0x5c11d795","0x7ff36ab5","0xb6f9de95","0x18cbafe5","0x791ac947"]),wr=new Set(["0xa9059cbb","0x23b872dd","0x42842e0e","0xb88d4fde","0xf242432a","0x2eb2c2d6","0xa22cb465","0xd0e30db0","0x2e1a7d4d","0x3593564c","0x24856bc3","0xac9650d8","0x5ae401dc"]),se=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`envelope: bounded ${r} required`);return e},x=(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`)}},xr=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${r} allowlist is empty`);return e},v=(e,r,t)=>{if(!xr(r,t).map(n=>String(n).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${t} not allowed`)},G=(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},P=e=>String(e||"0x").slice(0,10).toLowerCase();function ue(e){return ie.has(P(e))}function H(e){let r=P(e);return gr.has(r)||wr.has(r)||Object.hasOwn(ce,r)||ie.has(r)}function fe(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:a=>o.slice(10+a*64,10+(a+1)*64)}}function I(e,r){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${r} address`);return`0x${e.slice(24)}`}function C(e,r){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${r} integer`)}}function br(e){if(P(e)!=="0x095ea7b3")return null;let r=fe(e,2,"approval");return{kind:"approval",spender:I(r.word(0),"approval spender"),amount:C(r.word(1),"approval amount")}}function Er(e,r){let t=r==="router02-exact-input-single"?7:8,n=fe(e,t,"Uniswap v3 exactInputSingle"),o=t===7?4:5;return{kind:"action",action:"swap",inputToken:I(n.word(0),"input token"),outputToken:I(n.word(1),"output token"),recipient:I(n.word(3),"recipient"),amountIn:C(n.word(o),"amountIn"),minimumOut:C(n.word(o+1),"amountOutMinimum")}}function Sr(e){let r=fe(e,12,"Across depositV3",{dynamicTail:!0}),t=C(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 a=Math.ceil(o/32)*64;if(r.hex.length!==n+64+a)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:I(r.word(0),"depositor"),recipient:I(r.word(1),"recipient"),inputToken:I(r.word(2),"input token"),outputToken:I(r.word(3),"output token"),amountIn:C(r.word(4),"inputAmount"),minimumOut:C(r.word(5),"outputAmount"),destinationChainId:C(r.word(6),"destinationChainId")}}function vr(e,r){let t=P(e),n=ce[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{...Er(e,n.layout),selector:t,provider:n.provider};if(n.action==="bridge")return{...Sr(e),selector:t,provider:n.provider};throw new Error("envelope: unsupported reviewed EVM action")}function de(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 le(e,r,{nowMs:t=Date.now(),routeAttestationSecret:n}={}){let o=String(e?.surface||"");if(!Oe.has(o))throw new Error("envelope: strict EVM swap/bridge surface required");let a=se(e.provider,"provider",64).toLowerCase();v(a,r.providers,"provider");let i=G(e.owner,"owner"),f=e.artifact,d=Number(f?.chainId);if(!Number.isSafeInteger(d)||d<=0)throw new Error("envelope: explicit batch chainId required");if(v(d,r.chains,"chain"),G(f?.owner,"batch owner")!==i)throw new Error("envelope: explicit batch owner mismatch");let s=de(e);if(!s.length||s.length>8)throw new Error("envelope: bounded EVM transaction batch required");let l=0n,c=0n,E=0n,m=[],h=-1;for(let b=0;b<s.length;b++){let w=s[b];if(!w||typeof w!="object"||Array.isArray(w))throw new Error("envelope: structured EVM transaction required");if(Number(w.chainId)!==d)throw new Error("envelope: every batch leg must use the same chain");if(G(w.from,"transaction owner")!==i)throw new Error("envelope: every batch leg must use the same owner");let ne=P(w.data);v(ne,r.selectors,"selector");let R=br(w.data),T;if(R){if(h!==-1)throw new Error("envelope: approval must be before action");let _=G(w.to,"approval token");if(v(_,r.tokens,"token"),v(R.spender,r.spenders,"spender"),R.amount>x(r.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");T={...R,token:_,index:b}}else{if(h!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");v(w.to,r.destinations,"destination"),T={...vr(w.data,a),target:G(w.to,"action target"),index:b},h=b}let U=x(w.value??0,"value"),u=x(w.gasLimit,"gasLimit"),S=x(w.maxFeePerGas??w.gasPrice,"feePerGas");l+=U,c+=u,E+=u*S,m.push({...T,value:U,gas:u,fee:u*S})}if(h<0)throw new Error("envelope: reviewed swap/bridge action required");if(l>x(r.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(c>x(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(E>x(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");let g=m[h],$=o==="evm-swap"?"swap":"bridge";if(g.action!==$||e.action!==$)throw new Error("envelope: surface/action/calldata mismatch");if(g.recipient!==i)throw new Error("envelope: decoded recipient must equal owner");if(g.depositor&&g.depositor!==i)throw new Error("envelope: decoded bridge depositor must equal owner");if(v(g.inputToken,r.tokens,"input token"),v(g.outputToken,r.tokens,"output token"),g.amountIn<=0n||g.amountIn>x(r.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(g.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(ae(e.autoSlippage,{nowMs:t,chainId:d,venue:a,tx:s[h],secret:n,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(g.minimumOut!==x(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(g.action==="bridge"&&x(e.toChainId,"toChainId")!==g.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let O=m.filter(b=>b.kind==="approval");if(hr.has(g.inputToken)){if(O.length)throw new Error("envelope: native-value action must not include token approval")}else{if(O.length!==1)throw new Error("envelope: exactly one approval is required before action");let b=O[0];if(b.index>=h)throw new Error("envelope: approval must be before action");if(b.token!==g.inputToken)throw new Error("envelope: approval token does not match decoded input token");if(b.spender!==g.target)throw new Error("envelope: approval spender does not match decoded action target");if(b.amount!==g.amountIn)throw new Error("envelope: approval amount must exactly match decoded action amount")}let z=Object.freeze({quoteAmountOut:x(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:x(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{transactions:s,decoded:m,action:g,totalValue:l,totalGas:c,totalFee:E,chainId:d,owner:i,provider:a,authenticatedQuote:z}}function Ar(e,{localsWaiver:r=!1}={}){if(!(e in Ae))throw new Error("fee: unknown action");return r?0:Ae[e]}function _e(e,r,{nowMs:t=Date.now(),routeAttestationSecret:n}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let o=se(e.surface,"surface",16);if(!ye.has(o))throw new Error("envelope: unsupported public surface");let a=se(e.action,"action",32);if(v(o,r.surfaces,"surface"),v(a,r.actions,"action"),v(e.owner,r.owners,"owner"),v(e.destination,r.destinations,"destination"),!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=t||e.expiresAtMs-t>Number(r.maxTtlMs))throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>Number(r.maxSlippageBps))throw new Error("policy: slippage exceeds cap");let i=e.artifact;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("envelope: structured artifact required");if(Oe.has(o))le(e,r,{nowMs:t,routeAttestationSecret:n});else if(o==="evm"){if(ue(i.data))throw new Error("envelope: approval requires a strict decoded surface");if(a==="swap"||a==="bridge"||H(i.data))throw new Error("envelope: strict EVM swap/bridge surface required");v(Number(i.chainId),r.chains,"chain");let d=P(i.data);if(v(d,r.selectors,"selector"),String(i.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: owner mismatch");if(String(i.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(x(i.value??0,"value")>x(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=x(i.gasLimit,"gasLimit"),l=x(i.maxFeePerGas??i.gasPrice,"feePerGas");if(s>x(r.maxGasLimit,"maxGasLimit")||s*l>x(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: gas/fee exceeds cap")}else throw o==="btc"||o==="sol"?new Error("envelope: btc/sol require decoded payload; caller-authored outputs and programIds are refused"):new Error("envelope: unsupported public surface");let f=Ar(a,{localsWaiver:e.fee?.waiver==="locals-only-verified"});if(Number(e.fee?.oracleFeeBps)!==f)throw new Error("fee: final artifact fee mismatch");return!0}var yr=Object.freeze([...ye]),fn=Object.freeze({...ce});function Ne(e={}){let r={};for(let t of yr){let n=e[t];if(n){if(typeof n.sign!="function"||typeof n.broadcast!="function")throw new Error(`adapter: ${t} requires sign and broadcast functions`);r[t]=Object.freeze({sign:(o,a)=>n.sign(structuredClone(o),structuredClone(a)),broadcast:(o,a,i)=>n.broadcast(o,structuredClone(a),structuredClone(i))})}}return Object.freeze(r)}function pe(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}var me=e=>String(e||"").toLowerCase(),j=(e,r)=>{try{let t=BigInt(e??0);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},Z=(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 k(e){return Or("sha256").update(JSON.stringify(e)).digest("hex")}function Tr(e,r,{nowMs:t=Date.now()}={}){if(!e||!r)throw new Error("policy: artifact and policy required");if(ue(e.data))throw new Error("envelope: approval requires a strict decoded surface");if(H(e.data))throw new Error("envelope: strict EVM swap/bridge surface required");if(Z(Number(e.chainId),r.chains,"chain",Number),Z(e.to,r.destinations,"destination",me),Z(String(e.data||"0x").slice(0,10),r.selectors,"selector",a=>String(a).toLowerCase()),Z(e.from,r.owners,"owner",me),j(e.value,"value")>j(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let n=j(e.gasLimit,"gasLimit");if(n>j(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");if(j(e.maxFeePerGas??e.gasPrice,"feePerGas")*n>j(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>Number(r.maxSlippageBps))throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=t)throw new Error("policy: artifact expired");return!0}var Q=class{#e=new Map;constructor({now:r=Date.now}={}){this.now=r}issue({artifact:r,owner:t,ttlMs:n=6e4}){if(n<=0||n>12e4)throw new Error("confirmation: ttl out of range");let o=_r(32).toString("hex");return this.#e.set(o,{digest:k(r),owner:me(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"),a=Buffer.from(k(t),"hex");if(!Nr(o,a))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(r)),n}clear(){this.#e.clear()}};function Ir(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 Cr(e){let r=e?.status,t=r===1||r==="0x1"?"success":r===0||r==="0x0"?"failed":"pending",n=e?.verifiedBefore??e?.before,o=e?.verifiedAfter??e?.after;return{transactionHash:e?.hash||e?.transactionHash||null,status:t,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:Ir(n,o)}}function Te(e){return e?.surface==="evm-swap"||e?.surface==="evm-bridge"}function W(e,r,t=Date.now(),{routeAttestationSecret:n}={}){let o=e?.version===1&&e?.surface?e:null;return o?(_e(o,r,{nowMs:t,routeAttestationSecret:n}),Te(o)?le(o,r,{nowMs:t,routeAttestationSecret:n}):null):(Tr(e,r,{nowMs:t}),null)}async function Ie(e,r,t){if(!t.isArmed())throw new Error("signer: disarmed");let n=e?.version===1&&e?.surface?e:null,o=()=>typeof t.nowMs=="function"?t.nowMs():t.nowMs??Date.now(),a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,i=a?.confirmationMode||"exact-human";if(t.autonomous===!0){if(t.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(typeof t.verifyTriggerAttestation!="function"||await t.verifyTriggerAttestation(n?.triggerAttestation,e)!==!0)throw new Error("signer: autonomous trigger attestation required")}else{if(i==="auto-within-rails")throw new Error("signer: auto-within-rails requires autonomous trading with authenticated trigger attestation");if(i!=="exact-human")throw new Error("signer: unsupported confirmation mode");if(!t.confirmations||typeof t.confirmations.consume!="function")throw new Error("signer: exact confirmation store required");t.confirmations.consume(r,e)}let f=k(e),d=W(e,a,o(),{routeAttestationSecret:t.routeAttestationSecret});typeof t.reserveLedger=="function"&&t.reserveLedger(n||e,a,d);let s=n&&Te(n)?de(n):[n?n.artifact:e],l=[],c=[];for(let h=0;h<s.length;h++){if(!t.isArmed())throw new Error("signer: disarmed before signing");if(k(e)!==f)throw new Error("signer: artifact mutated before signing");h>0&&(a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,d=W(e,a,o(),{routeAttestationSecret:t.routeAttestationSecret}));let g=await t.sign(s[h],n);if(l.push(g),!t.isArmed())throw new Error("signer: disarmed before broadcast");if(k(e)!==f)throw new Error("signer: artifact mutated before broadcast");a=typeof t.readPolicy=="function"?t.readPolicy():t.policy,d=W(e,a,o(),{routeAttestationSecret:t.routeAttestationSecret});let $=await t.broadcast(g,s[h],n),O=Cr($);if(c.push(O),O.status!=="success")break}let E=c.length===s.length&&c.every(h=>h.status==="success")?"success":c.some(h=>h.status==="failed")?"failed":"pending",m={prepared:e,signed:s.length===1?l[0]:l,receipt:c[0]||null,receipts:c,status:E};return n?.surface==="evm-bridge"&&(m.originStatus=E,m.destinationStatus="unverified",m.destinationSuccess=!1,m.note="Origin-chain receipts do not prove destination-chain settlement."),m}var Ce=new Set(["127.0.0.1","::1","localhost"]),$r=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&Lr(t,n)},A=(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)},ke=e=>new Promise((r,t)=>{let n=0,o=[],a=!1;e.on("data",i=>{n+=i.length,n>64*1024&&!a?(a=!0,t(new Error("request refused")),e.resume()):a||o.push(i)}),e.on("end",()=>{if(!a)try{r(JSON.parse(Buffer.concat(o).toString()||"{}"))}catch{t(new Error("request refused"))}}),e.on("error",t)});function Le(e={}){let r=e.host||"127.0.0.1";if(!Ce.has(r))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");let t=e.confirmations||new Q,n=e.origin||`http://${r}`;return kr.createServer(async(a,i)=>{try{let f=String(a.headers.authorization||"").replace(/^Bearer /i,"");if(!$r(f,e.token))return A(i,401,{error:"unauthorized"});let d=String(a.headers.host||"").replace(/^\[|\](?=:|$)/g,"").split(":")[0];if(!Ce.has(d))return A(i,403,{error:"host refused"});if(a.headers.origin&&a.headers.origin!==n)return A(i,403,{error:"origin refused"});if(a.method==="GET"&&a.url==="/status")return A(i,200,{ok:!0,armed:e.isArmed?.()===!0,sessionExpiresAtMs:e.sessionExpiresAtMs||null});if(a.method==="POST"&&a.url==="/disarm")return e.disarm?.(),t.clear(),A(i,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(a.method))return A(i,405,{error:"request refused"});if(a.method==="POST"&&String(a.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return A(i,415,{error:"request refused"});if(a.method==="POST"&&a.url==="/confirm"){let s=await ke(a),l=k(s.artifact);if(e.autonomous!==!0){if(typeof e.confirmArtifact!="function")return A(i,403,{error:"local human confirmation unavailable"});let c=typeof e.readPolicy=="function"?e.readPolicy():e.policy,E=typeof e.nowMs=="function"?e.nowMs():e.nowMs??Date.now(),m=W(s.artifact,c,E);if(await e.confirmArtifact(s.artifact,l,m)!==!0)return A(i,400,{error:"exact human confirmation refused"})}return A(i,200,{confirmationNonce:t.issue({artifact:s.artifact,owner:s.artifact?.from,ttlMs:s.ttlMs})})}if(a.method==="POST"&&a.url==="/execute"){let s=await ke(a),l=await Ie(s.artifact,s.confirmationNonce,{...e,confirmations:t});return A(i,200,l)}return A(i,404,{error:"not found"})}catch(f){return e.onError?.(String(f?.message||f)),A(i,400,{error:"request refused"})}})}import{createCipheriv as En,createDecipheriv as Rr,randomBytes as Br,scryptSync as Mr}from"node:crypto";import p from"node:fs";import F from"node:path";var Dr="ORACLE-LOCAL-VAULT",Pr=1,re=Object.freeze({N:1<<17,r:8,p:1}),jr=256*1024*1024,Fr=16*1024;function ee(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 qr(e,r,t=re){let n=String(e??"");if(n.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return Mr(n,r,32,{...t,maxmem:jr})}function $e(e,r){if(e?.magic!==Dr||e?.version!==Pr)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!==re.N||e.kdf.r!==re.r||e.kdf.p!==re.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(c=>!["address","kind","createdAt"].includes(c))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||!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(c=>!t.includes(c)))throw new Error("local-vault: unexpected vault field");let n=ee(e.kdf.salt,32,"salt"),o=ee(e.cipher.iv,12,"iv"),a=ee(e.tag,16,"tag"),i=ee(e.ciphertext,1,"ciphertext",{max:Fr}),{ciphertext:f,tag:d,...s}=e,l=qr(r,n);try{let c=Rr("aes-256-gcm",l,o);return c.setAAD(Buffer.from(JSON.stringify(s))),c.setAuthTag(a),Buffer.concat([c.update(i),c.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{l.fill(0)}}function Re(e){let r=p.lstatSync(e);if(r.isSymbolicLink())throw new Error("local-vault: refusing symlink");if(!r.isFile())throw new Error("local-vault: secret source must be a regular file");if(r.uid!==process.getuid?.())throw new Error("local-vault: secret source must be owned by this user");if(r.nlink!==1)throw new Error("local-vault: refusing hard-linked secret source");if((r.mode&63)!==0)throw new Error("local-vault: secret source must be owner-only (0600)")}function Ur(e){let r=F.dirname(e),t=p.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");try{let n=p.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 N(e){let r=p.lstatSync(e);Re(e);let t=p.openSync(e,p.constants.O_RDONLY|p.constants.O_NOFOLLOW);try{let n=p.fstatSync(t);if(r.dev!==n.dev||r.ino!==n.ino||n.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");return p.readFileSync(t,"utf8").replace(/[\r\n]+$/,"")}finally{p.closeSync(t)}}function Be(e){return Re(e),JSON.parse(p.readFileSync(e,"utf8"))}function J(e,r){p.mkdirSync(F.dirname(e),{recursive:!0,mode:448}),Ur(e);let t=F.join(F.dirname(e),`.${F.basename(e)}.${process.pid}.${Br(6).toString("hex")}.tmp`);try{let n=p.openSync(t,p.constants.O_CREAT|p.constants.O_EXCL|p.constants.O_WRONLY|p.constants.O_NOFOLLOW,384);try{p.writeFileSync(n,String(r)),p.fsyncSync(n)}finally{p.closeSync(n)}p.renameSync(t,e),p.chmodSync(e,384);let o=p.openSync(F.dirname(e),"r");try{p.fsyncSync(o)}finally{p.closeSync(o)}}catch(n){try{p.unlinkSync(t)}catch{}throw n}}import{createHash as Gr,createHmac as Hr,timingSafeEqual as Wr,verify as Jr}from"node:crypto";import{homedir as he}from"node:os";import{join as ge}from"node:path";var Me=process.env.ORACLE_PUBLIC_DESKTOP==="1",Vr=Me?process.env.ORACLE_CONFIG_DIR||ge(he(),".config","oracle"):ge(he(),".config","oracle"),_n=Me?Vr:ge(he(),".config","mad-desk");var kn="0".repeat(64),Ln=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 q(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(q).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+q(e[t])).join(",")+"}"}var $n=Promise.resolve();var zr=864e5,we=(e,r)=>Hr("sha256",r).update(q(e)).digest("hex"),xe=(e,r)=>{let t=Buffer.from(String(e)),n=Buffer.from(String(r));return t.length===n.length&&Wr(t,n)};function Pe(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let r of Object.values(e))Pe(r);return e}function Kr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("trigger attestation: artifact object required");let r=structuredClone(e);return delete r.triggerAttestation,Pe(r)}function Xr(e){return Gr("sha256").update(q(Kr(e))).digest("hex")}function Yr(e,r){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!xe(e.integrity.mac,we(e.policy,r)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function je(e,r){let t=N(r),n;try{n=JSON.parse(N(e))}catch(o){throw new Error(`policy: cannot read sealed policy: ${o?.message||o}`)}return Yr(n,t)}function Zr(e,r,t){try{let n=JSON.parse(N(e));if(!xe(n?.integrity?.mac,we(n.ledger,r)))throw new Error("integrity verification failed");let o=n.ledger;if(!Number.isFinite(o?.windowStartMs)||!Array.isArray(o?.entries))throw new Error("invalid ledger");return t-o.windowStartMs>=zr?{windowStartMs:t,entries:[]}:o}catch(n){if(n?.code==="ENOENT")return{windowStartMs:t,entries:[]};throw new Error(`ledger: corrupt or unreadable: ${n?.message||n}`)}}function De(e,r){return e.reduce((t,n)=>t+BigInt(n[r]??0),0n)}function Fe({file:e,keyFile:r,tradeId:t,value:n=0,notional:o=0,policy:a,nowMs:i=Date.now()}){if(!/^[A-Za-z0-9._:-]{1,128}$/.test(String(t||"")))throw new Error("ledger: bounded tradeId required");let f=N(r),d=Zr(e,f,i);if(d.entries.some(h=>h.tradeId===t))throw new Error("ledger: replayed tradeId");let s=BigInt(n),l=BigInt(o),c=BigInt(a.maxDailyValueWei),E=BigInt(a.maxDailyNotional??a.maxDailyValueWei),m=BigInt(a.maxPerTrade??a.maxValueWei);if(s<0n||l<0n||l>m)throw new Error("ledger: per-trade cap exceeded");if(De(d.entries,"value")+s>c||De(d.entries,"notional")+l>E)throw new Error("ledger: daily cap exceeded");return d.entries.push({tradeId:String(t),value:s.toString(),notional:l.toString(),atMs:i}),J(e,JSON.stringify({ledger:d,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:we(d,f)}})+`
|
|
2
|
-
`)
|
|
3
|
-
`)
|
|
4
|
-
`)
|
|
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 u={version:1,sequence:a.sequence,ledgerMac:s};k.mkdirSync(J.dirname(n),{recursive:!0,mode:448}),G(n,JSON.stringify({marker:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:C(u,t)}})+`
|
|
5
|
+
`),o&&yo(o,t)}function rt({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");ee(t,e);let w=I(r);return fe(e,()=>{let p=ue(e,w,l,t,n);if(p.entries.some(A=>String(A.tradeId)===f))throw new Error("ledger: replayed tradeId");let m=BigInt(a),g=BigInt(s),[x,d,E]=et(u,i);if(m<0n||g<0n||g>E)throw new Error("ledger: per-trade cap exceeded");if(Be(p.entries,"value",i)+m>x||Be(p.entries,"notional",i)+g>d)throw new Error("ledger: daily cap exceeded");let S={tradeId:f,unit:i,value:m.toString(),notional:g.toString(),fee:c===void 0?"0":BigInt(c).toString(),state:"reserved",atMs:l};return p.entries.push(S),ce(e,p,w,t,n),structuredClone(S)})}function tt({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,reservation:o,policy:i,economics:a,nowMs:s=Date.now()}){ee(t,e);let c=I(r);return fe(e,()=>{let u=ue(e,c,s,t,n),l=u.entries.find(g=>String(g.tradeId)===String(o?.tradeId??"")&&g.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",[w,p,m]=et(i,f);if(BigInt(l.notional)>m)throw new Error("ledger: per-trade cap exceeded");if(Be(u.entries,"value",f)>w||Be(u.entries,"notional",f)>p)throw new Error("ledger: daily cap exceeded");return structuredClone(l)})}function nt({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ee(t,e);let a=I(r);return fe(e,()=>{let s=ue(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,ce(e,s,a,t,n),structuredClone(c)})}function ot({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ee(t,e);let a=I(r);return fe(e,()=>{let s=ue(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 ce(e,s,a,t,n),structuredClone(u)})}function it({file:e,keyFile:r,anchorFile:t,policyAnchorFile:n,tradeId:o,nowMs:i=Date.now()}){ee(t,e);let a=I(r);return fe(e,()=>{let s=ue(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",ce(e,s,a,t,n),structuredClone(c)):(c.state="committed",c.committedAtMs=i,c.value="0",c.notional=u.toString(),c.settledAs="fee-only",ce(e,s,a,t,n),structuredClone(c))})}function at(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:W(xo(r))};return U(e.mac,C(o,I(t)))}function vo(e){let r={...e?.fee||{}};return delete r.waiverAttestation,{...e,fee:r}}function st(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:W(vo(r))};return U(e.mac,C(o,I(t)))}import{spawnSync as Ao}from"node:child_process";function ct(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=Ao(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 or}from"ethers";import{base58 as lt}from"@scure/base";import{ed25519 as Oo}from"@noble/curves/ed25519.js";import{NETWORK as dt,TEST_NETWORK as pt,WIF as Io,p2wpkh as ut}from"@scure/btc-signer";import{pubECDSA as Lo}from"@scure/btc-signer/utils.js";var To=e=>{let r=String(e||"").trim().replace(/^0x/i,"");return!/^[0-9a-fA-F]+$/.test(r)||r.length%2?null:Buffer.from(r,"hex")},No=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},re=(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 ir(e,r){let t=String(r||"").trim();if(e==="evm")return new or(t).privateKey;if(e==="btc")for(let i of[dt,pt])try{return Buffer.from(Io(i).decode(t))}catch{}if(e==="sol")try{return re(lt.decode(t),"sol")}catch{}let n=To(t);if(n)return e==="evm"?new or(`0x${n.toString("hex")}`).privateKey:re(n,e);let o=No(t);if(o)return re(o,e);if(t.startsWith("[")||t.startsWith("{")){let i=JSON.parse(t);if(Array.isArray(i))return re(Uint8Array.from(i),e);let a=i.privateKey??i.secretKey??i.key;if(a)return ir(e,Array.isArray(a)?JSON.stringify(a):String(a))}throw new Error(`${e}: unsupported private key format`)}function ft(e,r){if(e==="evm"){let t=new or(String(r));return{kind:e,secret:t.privateKey,addresses:[t.address.toLowerCase()]}}if(e==="btc"){let t=re(r,"btc"),n=Lo(t);return{kind:e,secret:t.toString("hex"),addresses:[ut(n,dt).address,ut(n,pt).address]}}if(e==="sol"){let t=re(r,"sol");return{kind:e,secret:t.toString("hex"),addresses:[lt.encode(Oo.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"]:ft(r.kind||"evm",ir(r.kind||"evm",t))};let n=JSON.parse(t),o={};for(let i of["evm","btc","sol"])n[i]&&(o[i]=ft(i,ir(i,n[i])));if(!Object.keys(o).length)throw new Error("local-vault: multichain vault is empty");return o}function ar(e){if(!e)throw new Error("signer: key record required");return Buffer.from(e.secret.replace(/^0x/,""),"hex")}function Fo(e){let r=process.env.ORACLE_SIGNER_STATE_DIR||$.join(process.env.XDG_STATE_HOME||$.join(Bo.homedir(),".local","state"),"oracle"),t=_o("sha256").update($.resolve(e)).digest("hex").slice(0,16);return{vault:$.join(e,"vault.json"),policy:$.join(e,"signer-policy.json"),policyKey:$.join(e,"policy-integrity-key"),policyAnchor:$.join(r,`signer-policy-${t}.high-water`),ledger:$.join(e,"signer-ledger.json"),ledgerAnchor:$.join(r,`signer-ledger-${t}.high-water`),token:$.join(e,"signer-token"),lock:$.join(r,`signer-${t}.lock`)}}function Ro(e){try{return I(e)}catch(t){if(t.code!=="ENOENT")throw t}let r=ko(32).toString("hex");return G(e,r+`
|
|
6
|
+
`),r}function cr(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 wt(e){return e.surfaces.some(r=>String(r).startsWith("evm"))}function ke(e,r){return e.surfaces.includes(r)}function $o(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"}`),P(String(c.data||"0x")))try{let l=oe(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(P(s))try{let c=oe(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=je(n,t);i.push(`amount=${c.value} sats fee=${c.fee} sats outputs=${c.outputs.join(",")}`)}if(n?.surface==="sol"){let c=Ge(n,t);i.push(`amount=${c.value} lamports fee=${c.fee} lamports programs=${c.programs.join(",")}`)}return`
|
|
5
7
|
Confirm exact action
|
|
6
|
-
${
|
|
8
|
+
${i.join(`
|
|
7
9
|
`)}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
to=${e.to} selector=${String(e.data||"0x").slice(0,10)} value=${e.value}
|
|
14
|
-
gas=${e.gasLimit} maxFeePerGas=${e.maxFeePerGas??e.gasPrice}
|
|
15
|
-
slippageBps=${e.slippageBps} expiresAtMs=${e.expiresAtMs}
|
|
16
|
-
Type digest ${r}: `}async function ot(e,r,t){return process.stdin.isTTY?(process.stderr.write(nt(e,r,t)),process.stdin.resume(),new Promise(n=>{let o=a=>{process.stdin.off("data",o),process.stdin.pause(),n(String(a).trim()===r)};process.stdin.once("data",o)})):!1}var He=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
|
|
17
|
-
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,te=(e,r,t)=>{let n=e.indexOf(r);return n>=0?e[n+1]:t};async function it(e=[],r={}){if(e.includes("--help"))return(r.out||process.stdout).write(He+`
|
|
18
|
-
`),0;let t=te(e,"--passphrase-file"),n=await Ge({configDir:at.join(r.configDir||X(),"signer"),passphraseFile:t,credentialService:te(e,"--credential-service"),port:Number(te(e,"--port",9462)),sessionMs:Number(te(e,"--session-seconds",120))*1e3});return(r.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
|
|
19
|
-
`),await new Promise(o=>n.on("close",o)),0}var Qn={name:"signer",summary:"run the short-lived loopback signer",usage:He,run:e=>it(e.argv||[])};export{Qn as default,it as run};
|
|
10
|
+
Type digest ${r}: `}async function Ce(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 gt(e,r){return Buffer.concat([Buffer.from([1]),Buffer.from(r),Buffer.from(e)]).toString("base64")}async function xt(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 Ce(n,{jsonrpc:"1.0",id:"oracle",method:r,params:t})}async function Mo(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 xt(e,"gettxout",[r,Number(t),!0]))throw new Error("signer: Bitcoin input unavailable for simulation");return!0}function Po(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 qo(e,r){let t=ar(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 Mo(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 xt(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 Uo(e,r){let t=ar(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=gt(a,new Uint8Array(64)),c=await Ce(i,{jsonrpc:"2.0",id:1,method:"simulateTransaction",params:[s,{encoding:"base64",sigVerify:!1,replaceRecentBlockhash:!1}]});return Po(c)},sign:n=>gt(Buffer.from(n.messageBase64,"base64"),Co.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 Ce(i,{jsonrpc:"2.0",id:1,method:"sendTransaction",params:[n,{encoding:"base64",skipPreflight:!1,maxRetries:3}]}),c=(await Ce(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 St({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=Fo(e),l=()=>Object.freeze(Qr(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 h of["surfaces","actions","chains","destinations","spenders","owners"])if(!Array.isArray(f[h])||f[h].length===0)throw new Error(`signer: ${h} allowlist is empty`);if(f.surfaces.some(h=>h==="evm-swap"||h==="evm-bridge"||h==="evm-nft")){for(let h of["providers"])if(!Array.isArray(f[h])||f[h].length===0)throw new Error(`signer: ${h} allowlist is empty`)}if(f.surfaces.some(h=>h==="evm-swap"||h==="evm-bridge")&&(!Array.isArray(f.tokens)||f.tokens.length===0))throw new Error("signer: tokens allowlist is empty");if(f.surfaces.some(h=>String(h).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(h=>h==="hl"||h==="poly"))throw new Error("signer: hl/poly are not public signer families");let w=t?ct(t):I(r),p=Zr(u.vault),m=Xr(p,w),g;try{g=mt(m,p.meta)}finally{m.fill(0)}wt(f)&&cr("evm",g.evm,f.owners),ke(f,"btc")&&cr("btc",g.btc,f.owners),ke(f,"sol")&&cr("sol",g.sol,f.owners);let x=f.chains.filter(h=>Number.isInteger(Number(h))&&String(h).trim()!==""),d=wt(f);if(d&&(x.length!==1||!f.rpcUrl))throw new Error("signer: EVM surfaces require one chain and one RPC URL");if(ke(f,"btc")&&!(f.btcRpcUrl||f.bitcoinRpcUrl))throw new Error("signer: btcRpcUrl required for Bitcoin broadcast");if(ke(f,"sol")&&!(f.solRpcUrl||f.solanaRpcUrl))throw new Error("signer: solRpcUrl required for Solana simulation and broadcast");let E=d?new s(f.rpcUrl,Number(x[0])):null,S=d?new c(g.evm.secret).connect(E):null,A=E?{simulate:async h=>{if((await E.getNetwork()).chainId!==BigInt(h.chainId))throw new Error("signer: RPC chain mismatch");return await E.call(h),!0},sign:h=>S.signTransaction(h),broadcast:async(h,y)=>{if((await E.getNetwork()).chainId!==BigInt(y.chainId))throw new Error("signer: RPC chain mismatch");let M={native:(await E.getBalance(y.from)).toString()},te=await E.broadcastTransaction(h),D=await te.wait(),de={native:(await E.getBalance(y.from)).toString()};return{hash:D?.hash??te.hash,status:D?.status??null,verifiedBefore:M,verifiedAfter:de}}}:null,T=E?async h=>Wo(E,h):void 0,L={...A?{evm:A,"evm-swap":A,"evm-bridge":A,"evm-nft":A}:{},...g.btc?{btc:qo(l,g.btc)}:{},...g.sol?{sol:Uo(l,g.sol)}:{}},O=$r({...L,...n}),$e=new Set(Object.keys(L)),yt=new Set(Object.keys(n||{})),ur=f.surfaces.filter(h=>!$e.has(h)&&!yt.has(h));if(ur.length)throw new Error(`signer: ${ur.join(",")} require local keys or injected surface transports`);let vt=Date.now(),fr=vt+a,Me=!1,At=()=>Me?!1:ht.existsSync(u.lock)?(Me=!0,!1):ht.existsSync(u.vault)&&Date.now()<fr,Ot=()=>(Me=!0,G(u.lock,`disarmed ${new Date().toISOString()}
|
|
11
|
+
`),!0),le=Kr({host:o,port:i,token:Ro(u.token),policy:f,readPolicy:l,isArmed:At,disarm:Ot,sessionExpiresAtMs:fr,nowMs:Date.now,simulate:(h,y)=>ve(y,O).simulate(h,y),estimateNetworkFees:T,sign:(h,y)=>ve(y,O).sign(h,y),verifySigned:(h,y,N)=>Wr(N?.surface||"evm",h,y,N),broadcast:(h,y,N)=>ve(N,O).broadcast(h,y,N),confirmArtifact:jo,decodeEconomics:(h,y)=>Xe(h,y),reserveLedger:(h,y)=>{let N=h?.version===1&&h?.surface?h:null,M=N?.artifact||h,te=N?.tradeId||M?.tradeId;if(!te)throw new Error("ledger: executable artifact requires a tradeId");let D;if(N)D=Xe(N,y);else{if(M?.value===void 0)throw new Error("ledger: executable artifact value required");let de=BigInt(M.value),dr=BigInt(M.gasLimit??0),pr=BigInt(M.maxFeePerGas??M.gasPrice??0);if(dr<=0n||pr<=0n)throw new Error("ledger: legacy EVM artifact requires gasLimit and fee per gas");let mr=dr*pr+BigInt(M.l1FeeWei??0)+BigInt(M.operatorFeeWei??0);D={unit:"wei",value:de.toString(),notional:(de+mr).toString(),fee:mr.toString()}}if(D.value===void 0||D.notional===void 0)throw new Error("ledger: decoded value and notional required");return rt({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:te,...D,policy:y})},commitLedger:h=>nt({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:h.tradeId}),releaseLedger:h=>ot({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:h.tradeId}),settleFailedLedger:h=>it({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,tradeId:h.tradeId}),validateReservation:(h,y,N)=>tt({file:u.ledger,keyFile:u.policyKey,anchorFile:u.ledgerAnchor,policyAnchorFile:u.policyAnchor,reservation:h,policy:y,economics:N}),verifyFeeWaiver:(h,y)=>st(h,y,u.policyKey),verifyTriggerAttestation:(h,y,N)=>at(h,y,u.policyKey,N),autonomous:process.env.ORACLE_AUTONOMOUS_TRADING==="1",env:process.env}),lr=setTimeout(()=>le.close(),a);return lr.unref(),le.on("close",()=>{clearTimeout(lr)}),le.listen(i,o),le}var Fe="0x420000000000000000000000000000000000000F";function Et(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 Wo(e,r){if(!q(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:Fe,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 Do(e,o,r.gasLimit)}}async function Do(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:Fe,data:r.encodeFunctionData("getOperatorFee",[n])});return r.decodeFunctionResult("getOperatorFee",o)[0].toString()}catch(o){if(!Et(o))throw new Error("policy: rollup fee estimate required")}try{let o=await e.call({to:Fe,data:r.encodeFunctionData("operatorFeeScalar")}),i=await e.call({to:Fe,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(!Et(o))throw new Error("policy: rollup fee estimate required");return"0"}}async function jo(e,r,t){return process.stdin.isTTY?(process.stderr.write($o(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 bt=`oracle signer (--credential-service oracle-local-signer | --passphrase-file <0600 file>) [--port 9462] [--session-seconds 120]
|
|
12
|
+
Starts a loopback-only, short-lived local signer. No secret may be passed directly or through the environment.`,Re=(e,r,t)=>{let n=e.indexOf(r);return n>=0?e[n+1]:t};async function Go(e=[],r={}){if(e.includes("--help"))return(r.out||process.stdout).write(bt+`
|
|
13
|
+
`),0;let t=Re(e,"--passphrase-file"),n=await St({configDir:Vo.join(r.configDir||me(),"signer"),passphraseFile:t,credentialService:Re(e,"--credential-service"),port:Number(Re(e,"--port",9462)),sessionMs:Number(Re(e,"--session-seconds",120))*1e3});return(r.out||process.stdout).write(`Oracle signer listening on loopback for a short-lived session.
|
|
14
|
+
`),await new Promise(o=>n.on("close",o)),0}var vs={name:"signer",summary:"run the short-lived loopback signer",usage:bt,run:e=>Go(e.argv||[])};export{vs as default,Go as run};
|