@oracle-agent/oracle 0.22.15 → 0.22.16
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/SETUP.md +30 -4
- package/artifacts/specialist-packs/oracle-full-crypto.json +3 -1
- package/dist/bin/desk-server.mjs +17 -17
- package/dist/bin/oracle-data-mcp.mjs +6 -6
- package/dist/bin/oracle-public-server.mjs +4 -4
- package/dist/bin/oracle-route.mjs +1 -1
- package/dist/bin/oracle.mjs +20 -9
- package/dist/cli/commands/arm.mjs +17 -0
- package/dist/cli/commands/chat.mjs +1 -1
- package/dist/cli/commands/doctor.mjs +6 -6
- package/dist/cli/commands/model.mjs +1 -1
- package/dist/cli/commands/revoke.mjs +40 -0
- package/dist/cli/commands/snipe.mjs +39 -0
- package/dist/cli/commands/swap.mjs +2 -2
- package/dist/cli/commands/vault.mjs +29 -0
- package/dist/data/desk-data.mjs +14 -14
- package/dist/index.mjs +20 -20
- package/dist/local-vault/index.mjs +6 -0
- package/dist/router/index.mjs +1 -1
- package/dist/router/prepare-bridge.mjs +1 -1
- package/package.json +3 -2
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
var f=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var A=f(()=>{});import{readFileSync as tr}from"node:fs";import{homedir as rr}from"node:os";import{join as te}from"node:path";function nr(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let r=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return r?[r]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),t=rr();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let r=(process.env.ORACLE_CONFIG_DIR||te(t,".config","oracle")).trim();return[e,te(r,"exec.env")].filter(Boolean)}return[e,te(t,".config","oracle","exec.env"),te(t,".config","mad-desk","exec.env")].filter(Boolean)}function C(e,t,r){let n=e??process.env[t]??process.env[r];if(!String(n||"").trim())for(let o of nr())try{let a=tr(o,"utf8"),i=a.match(new RegExp(`^${t}=(.*)$`,"m"))||a.match(new RegExp(`^${r}=(.*)$`,"m"));if(i&&(n=i[1].trim(),n))break}catch{}if(!String(n||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return n}var M=f(()=>{});function m(e,t,r="guard"){let n=Number(t);if(t==null||!Number.isFinite(n))throw new Error(`${r}: current time must be a finite number (got ${or(t)})`);let o=Number(e?.issuedAtMs),a=Number(e?.expiresAtMs);if(!Number.isFinite(a))throw new Error(`${r}: expiresAtMs is required and must be a finite number`);if(n>a)throw new Error(`${r} expired at ${a}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${r}: issuedAtMs must be a finite number when present`);if(a<=o)throw new Error(`${r}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:a}}function or(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var T=f(()=>{});import{createHash as ar,createHmac as ir,timingSafeEqual as sr}from"node:crypto";function Se(e){return Array.isArray(e)?`[${e.map(Se).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Se(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function cr(e,{required:t=!1}={}){try{return C(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(r){if(t)throw r;return null}}function ur(e){let{signature:t,...r}=e;return r}function lr(e){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<10||t.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return ar("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function dr(e,t){let r=Buffer.from(String(e??""),"utf8"),n=Buffer.from(String(t??""),"utf8");return r.length!==n.length||r.length===0?!1:sr(r,n)}function pr(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let r=t.slice(0,10).toLowerCase(),n=[];for(let a=10;a+64<=t.length;a+=64)n.push(t.slice(a,a+64));let o=a=>n[a]==null?null:BigInt("0x"+n[a]);switch(r){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 re(e,{nowMs:t=Date.now(),chainId:r,venue:n,secret:o,tx:a,requireSigned:i=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let s=cr(o,{required:i});if(i&&!s)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(s){let b=ir("sha256",s).update(Se(ur(e))).digest("hex");if(!dr(e.signature,b))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>Je)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(u)||u<0||u>Je||c>u)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{m({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},t,"auto-slippage quote")}catch(b){throw new Error(`${b.message}; re-quote before signing`)}if(r!=null&&Number(e.chainId)!==Number(r))throw new Error("auto-slippage guard chain mismatch");if(n&&String(e.venue).toLowerCase()!==String(n).toLowerCase())throw new Error("auto-slippage guard venue mismatch");let l=BigInt(e.quoteAmountOut??0),d=BigInt(e.minAmountOut??0);if(l<=0n||d<=0n)throw new Error("auto-slippage guard amounts must be positive");let I=l*BigInt(1e4-c)/10000n;if(d<I)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)!==lr(a.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch")}else{let b=pr(a.data);if(b==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(b!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${b}`)}return!0}var Je,x=f(()=>{M();T();Je=100});var Ie=f(()=>{});var Oo,To,v=f(()=>{Oo=300*1e3,To=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Contract as Bo,JsonRpcProvider as Fo}from"ethers";var Qe=f(()=>{});var Po,ne=f(()=>{Qe();Po=Object.freeze({swap:5,bridge:5,perps:0,nft:0})});var et=f(()=>{A();x();Ie();v();ne()});var tt=f(()=>{A();x();v();ne()});var Ce=f(()=>{});var rt=f(()=>{A();x();Ce();v()});var pa,nt=f(()=>{pa=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});import{TypedDataEncoder as ba,getAddress as ga,isAddress as Ea}from"ethers";var Ca,ka,Na,_a,ot=f(()=>{A();x();nt();Ie();v();Ca=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),ka=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Na=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),_a=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function H(e){return at.get(Number(e))||null}function ae(e,t=process.env){let r=H(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}function ie(e){return at.has(Number(e))}var V,at,se=f(()=>{V={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},at=new Map(Object.values(V).map(e=>[e.chainId,e]))});import{Interface as br,getAddress as Fa}from"ethers";var $a,U=f(()=>{A();se();$a=new br(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"])});var Pa,ce=f(()=>{A();Pa=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"})});import{Interface as it,getAddress as Va,isAddress as Ha}from"ethers";var za,Xa,ke=f(()=>{U();ce();x();v();za=new it(["function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)","function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]),Xa=new it(["function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"])});import{AbiCoder as Er,Interface as st,getAddress as Qa,isAddress as Za,keccak256 as ei}from"ethers";var ai,ii,si,ct=f(()=>{U();ce();x();v();ai=Er.defaultAbiCoder(),ii=new st(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)"]),si=new st(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"])});import{createCipheriv as Zn,createDecipheriv as Vt,randomBytes as eo,scryptSync as Ht,timingSafeEqual as to}from"node:crypto";var ge="ORACLE-VAULT",ze=1,jt=1<<17,Wt=8,Gt=1,Kt=256*1024*1024,zt=32;function Xt(e,t,r={}){let n=String(e??"");if(n.length<8)throw new Error("local-vault: passphrase must be at least 8 characters");return Ht(n,t,zt,{N:r.N??jt,r:r.r??Wt,p:r.p??Gt,maxmem:Kt})}function Ke(e,t,r){let n=Vt("aes-256-gcm",e,Buffer.from(t.iv,"base64"));return r&&n.setAAD(Buffer.from(r,"utf8")),n.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([n.update(Buffer.from(t.ct,"base64")),n.final()])}function Ee(e,t){if(!e||e.magic!==ge)throw new Error("local-vault: not an Oracle vault file");if(Number(e.version)!==ze)throw new Error(`local-vault: unsupported vault version ${e.version}`);let r=e.kdf||{};if(r.name!=="scrypt")throw new Error(`local-vault: unsupported kdf ${r.name}`);let{wrappedDek:n,payload:o,...a}=e,i=JSON.stringify(a),s=Xt(t,Buffer.from(r.salt,"base64"),r),c;try{c=Ke(s,n,i)}catch{throw s.fill(0),new Error("local-vault: wrong passphrase or tampered vault")}s.fill(0);try{return Ke(c,o,i)}catch{throw new Error("local-vault: vault payload failed authentication")}finally{c.fill(0)}}function xe(e){try{return(typeof e=="string"?JSON.parse(e):e)?.magic===ge}catch{return!1}}import E from"node:fs";import Xe from"node:fs";import Yt from"node:os";import O from"node:path";function Ye(e=process.env){return e.ORACLE_CONFIG_DIR?O.resolve(e.ORACLE_CONFIG_DIR):e.ORACLE_FAKE_HOME?O.join(O.resolve(e.ORACLE_FAKE_HOME),".config","oracle"):O.join(Yt.homedir(),".config","oracle")}function ye(e=process.env){let t=Ye(e);Xe.mkdirSync(t,{recursive:!0,mode:448});try{Xe.chmodSync(t,448)}catch{}return t}function z(e=process.env){return O.join(ye(e),"keys","default.vault")}function X(e=process.env){return O.join(ye(e),"local-session.json")}function Y(e=process.env){return O.join(ye(e),"local-arm.json")}var po=1800*1e3;function J(e){return JSON.parse(E.readFileSync(e,"utf8"))}function Q(e=process.env){let t=e.ORACLE_VAULT_PATH||z(e),r=X(e),n=Y(e),o=!1,a=null;try{E.existsSync(t)&&(o=!0,a=JSON.parse(E.readFileSync(t,"utf8"))?.meta||null)}catch{o=E.existsSync(t)}let i=!1,s=null,c=null;try{if(E.existsSync(r)){let d=J(r);d?.expiresAt&&Date.parse(d.expiresAt)>Date.now()&&d?.vaultPath&&(i=!0,s=d.expiresAt,c=d.address||null)}}catch{i=!1}let u=!1,l=null;try{E.existsSync(n)&&(l=J(n),u=l?.armed===!0,u&&l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(u=!1))}catch{u=!1}return{vaultPath:t,vaultExists:o,vaultMeta:a,unlocked:i,sessionExpiresAt:s,address:c,armed:u,arm:l,plane:"local-self-custody",note:"Keys never leave this machine. Public HTTP plane stays prepare-only."}}function Z(e=process.env,t={}){let r=X(e);if(!E.existsSync(r))throw new Error("local-vault: locked \u2014 run oracle vault unlock");let n=J(r);if(!n?.vaultPath||!n.expiresAt||Date.parse(n.expiresAt)<=Date.now()){try{E.unlinkSync(r)}catch{}throw new Error("local-vault: session expired \u2014 run oracle vault unlock")}let o=t.passphrase??e.ORACLE_LOCAL_VAULT_PASS;if(!o)throw new Error("local-vault: passphrase required to decrypt vault for signing");let a=n.vaultPath||e.ORACLE_VAULT_PATH||z(e),i=E.readFileSync(a,"utf8");if(!xe(i))throw new Error("local-vault: vault file is not an Oracle vault envelope");let s=Ee(JSON.parse(i),o),c=s.toString("utf8").trim();return s.fill(0),{material:c,address:n.address||null,expiresAt:n.expiresAt,vaultPath:a}}function ee(e=process.env){let t=Y(e);if(!E.existsSync(t))throw new Error("local-vault: disarmed \u2014 run oracle arm --max <eth> --chain <id>");let r=J(t);if(r.armed!==!0)throw new Error("local-vault: disarmed \u2014 run oracle arm");if(r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())throw new Error("local-vault: arm session expired \u2014 re-arm");return r}import{Wallet as Lc,JsonRpcProvider as Rc,getAddress as Bc,isAddress as Fc,parseUnits as $c}from"ethers";var mo=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),Ae=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),ve=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var er=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"});et();tt();rt();A();x();Ce();v();ot();ke();ct();A();var Oi=Object.freeze({across:["across"],relay:["relaychain","relay"],lifi:["jumper-(li.fi-powered)","lifi"],stargate:["stargate-v2","stargate-v1","stargate"],hop:["hop-protocol","hop"],debridge:["debridge"],synapse:["synapse"],connext:["connext"],cbridge:["celer-bridge","celer-cbridge","cbridge"],celer:["celer-bridge","celer-cbridge","cbridge"],squid:["squid"],symbiosis:["symbiosis"],wormhole:["wormhole"],mayan:["mayan"],allbridge:["allbridge"],thorchain:["thorchain"]});ne();v();var zi=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"});var Xi=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase()));U();ce();U();U();var Es=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);ke();se();import{readFileSync as xn,writeFileSync as $t,mkdirSync as Ue,renameSync as yn,unlinkSync as An,rmSync as vn}from"node:fs";import{dirname as Dt,join as Sn}from"node:path";var Ar=["0x000000000022d473030f116ddee9f6b43ac78ba3"],vr={4663:["0xcaf681a66d020601342297493863e78c959e5cb2","0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7","0x1f7d7550b1b028f7571e69a784071f0205fd2efa","0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360d0400a0fd4f2af552add042d716f1d168","0xb477751b76cf82d00a686a1232f5fcd772414af3","0xff5cb29241f002ffed2eaa224e3e996d24a6e8d1"],8453:["0x2626664c2603336e57b271c5c0b26f421741e481","0x6ff5693b99212da76ad316178a184ab56d299b43","0x3d4e44eb1374240ce5f1b871ab261cd16335b76a","0x33128a8fc17869897dce68ed026d694621f6fdfd","0x4200000000000000000000000000000000000006","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913","0xbe6d8f0d05cc4be24d5167a3ef062215be6d18a5","0x254cf9e1e6e233aa1ac962cb9b05b2cfeaae15b0","0x5e7bb104d84c7cb9b682aac2f3d509f5f406809a","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x888888888889758f76e7103c6cbf23abbf58f946","0x3f170631ed9821ca51a59d996ab095162438dc10","0x4f37a9d177470499a2dd084621020b023fcffc1f","0xc92e8bdf79f0507f65a392b0ab4667716bfe0110"],42161:["0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","0x61ffe014ba17989e743c5f6cb21bf9697530b21e","0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0xaf88d065e77c8cc2239327c5edb3a432268e5831","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9","0x888888888889758f76e7103c6cbf23abbf58f946","0xeaedc32a51c510d35ebc11088fd5ff2b47aacf2e","0x2191718cd32d02b8e60badffea33e4b5dd9a0a0d","0xc92e8bdf79f0507f65a392b0ab4667716bfe0110","0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41","0x7452c558d45f8afc8c83dae62c3f8a5be19c71f6"],1:["0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x4cd00e387622c35bddb9b4c962c136462338bc31","0x6a000f20005980200259b80c5102003040001068","0xae563e3f8219521950555f5962419c8919758ea2","0x45312ea0eff7e09c83cbe249fa1d7598c4c8cd4e","0xc92e8bdf79f0507f65a392b0ab4667716bfe0110"],137:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x0dcded3545d565ba3b19e683431381007245d983"],10:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xe2fa4e1d17725e72dcdafe943ecf45df4b9e285b","0x0dcded3545d565ba3b19e683431381007245d983"],56:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xa72c85c258a81761433b4e8da60505fe3dd551cc"],43114:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xf39ca6ede9bf7820a952b52f3c94af526bab9015","0x0dcded3545d565ba3b19e683431381007245d983","0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2","0x820f5ffc5b525cd4d88cd91acf2c28f16530cc68"],999:["0x0a0758d937d1059c356d4714e57f5df0239bce1a","0xd2002373543ce3527023c75e7518c274a51ce712"],2741:["0x4f8c9056bb8a3616693a76922fa35d53c056e5b3"],988:["0x026f252016a7c47cdef1f05a3fc9e20c92a49c37","0xff5cb29241f002ffed2eaa224e3e996d24a6e8d1","0x817997ca8394e26cce3de3a076a4889b27dbf9de","0x3dea4be5615974f31624404ef288ba3b36dfeb83","0xeaf7ac0fdf150cdd89340fb762d83848de6a7b83","0x779ded0c9e1022225f8e0630b35a9b54be713736","0xbc6f7725f08232c151b528bdfcaaf89993ca86ee"]},Sr={1:["0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x4cd00e387622c35bddb9b4c962c136462338bc31","0x6a000f20005980200259b80c5102003040001068","0xae563e3f8219521950555f5962419c8919758ea2","0x45312ea0eff7e09c83cbe249fa1d7598c4c8cd4e"],10:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xe2fa4e1d17725e72dcdafe943ecf45df4b9e285b","0x0dcded3545d565ba3b19e683431381007245d983"],56:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xa72c85c258a81761433b4e8da60505fe3dd551cc"],137:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x0dcded3545d565ba3b19e683431381007245d983"],988:["0x026f252016a7c47cdef1f05a3fc9e20c92a49c37","0xff5cb29241f002ffed2eaa224e3e996d24a6e8d1","0x3dea4be5615974f31624404ef288ba3b36dfeb83","0xbc6f7725f08232c151b528bdfcaaf89993ca86ee"],999:["0x0a0758d937d1059c356d4714e57f5df0239bce1a","0xd2002373543ce3527023c75e7518c274a51ce712"],2741:["0x4f8c9056bb8a3616693a76922fa35d53c056e5b3"],4663:["0xcaf681a66d020601342297493863e78c959e5cb2","0xb477751b76cf82d00a686a1232f5fcd772414af3","0xff5cb29241f002ffed2eaa224e3e996d24a6e8d1"],8453:["0x2626664c2603336e57b271c5c0b26f421741e481","0x6ff5693b99212da76ad316178a184ab56d299b43","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x888888888889758f76e7103c6cbf23abbf58f946","0x3f170631ed9821ca51a59d996ab095162438dc10","0x4f37a9d177470499a2dd084621020b023fcffc1f"],42161:["0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45","0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0x888888888889758f76e7103c6cbf23abbf58f946","0xeaedc32a51c510d35ebc11088fd5ff2b47aacf2e","0x2191718cd32d02b8e60badffea33e4b5dd9a0a0d"],43114:["0x1231deb6f5749ef6ce6943a275a1d3e7486f4eae","0xf39ca6ede9bf7820a952b52f3c94af526bab9015","0x0dcded3545d565ba3b19e683431381007245d983"]};function ut(e,t){let r=String(t||"").trim().toLowerCase();return r?(Sr[Number(e)]||[]).includes(r):!1}function P(e){let t=vr[Number(e)]||[];return new Set([...t,...Ar].map(r=>String(r).trim().toLowerCase()).filter(Boolean))}import{existsSync as Ir}from"node:fs";import{homedir as Ne}from"node:os";import{join as j}from"node:path";var lt=process.env.ORACLE_PUBLIC_DESKTOP==="1",dt=lt?process.env.ORACLE_CONFIG_DIR||j(Ne(),".config","oracle"):j(Ne(),".config","oracle"),Cr=lt?dt:j(Ne(),".config","mad-desk");function B(e,t,r=""){let n=process.env[e];if(n!=null&&String(n).trim()!=="")return n;let o=t?process.env[t]:void 0;return o!=null&&String(o).trim()!==""?o:r}function pt(e,t){return String(B(e,t,""))}function ft(e,t,r){let n=B(t,r,"");if(n)return n;let o=j(dt,e);return Ir(o)?o:j(Cr,e)}x();import{Interface as rn,MaxUint256 as nn,isAddress as on,keccak256 as an,toUtf8Bytes as sn}from"ethers";import{createHmac as Dr,timingSafeEqual as Ur}from"node:crypto";import{Interface as Pr,isAddress as qr}from"ethers";x();M();T();import{createHash as kr,createHmac as Nr,timingSafeEqual as _r}from"node:crypto";import{isAddress as Or}from"ethers";function de(e){return Array.isArray(e)?`[${e.map(de).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${de(e[t])}`).join(",")}}`:JSON.stringify(e)}function le(e,t){let r=String(e||"").trim();if(!Or(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Tr(e){let t=String(e||"0x").toLowerCase();if(!/^0x(?:[0-9a-f]{2})*$/.test(t))throw new Error("route attestation calldata must be hex bytes");return t}function mt(e){return`0x${kr("sha256").update(String(e)).digest("hex")}`}function Lr(e,t){return`0x${Nr("sha256",String(e)).update(t).digest("hex")}`}function Rr(e,t){let r=Buffer.from(String(e||"").replace(/^0x/,""),"hex"),n=Buffer.from(String(t||"").replace(/^0x/,""),"hex");return r.length===n.length&&r.length>0&&_r(r,n)}function Br(e){return C(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}function Fr(e){let{signature:t,...r}=e;return r}function W(e){return mt(Tr(e))}function $r(e){if(!e)throw new Error("route attestation requires slippage guard");return mt(de(e))}function ht(e,t={},{chainId:r,nowMs:n=Date.now(),secret:o}={}){if(m(e||{},n,"route attestation"),!e||e.mode!=="route-attestation")throw new Error("route attestation required");if(Number(e.expiresAtMs)<=Number(n))throw new Error("route attestation expired");if(Number(e.chainId)!==Number(r??t.chainId))throw new Error("route attestation chain mismatch");let a=le(t.to,"route tx.to");if(le(e.destination,"route destination")!==a)throw new Error("route attestation destination mismatch");if(t.from&&e.sender&&le(e.sender,"route sender")!==le(t.from,"route tx.from"))throw new Error("route attestation sender mismatch");if(String(e.value)!==String(t.value??"0"))throw new Error("route attestation value mismatch");if(e.calldataHash!==W(t.data||"0x"))throw new Error("route attestation calldata mismatch");if(e.slippageHash!==$r(t.slippageGuard??t.madSlippage))throw new Error("route attestation slippage mismatch");let i=Lr(Br(o),de(Fr(e)));if(!Rr(e.signature,i))throw new Error("route attestation signature mismatch");return re(t.slippageGuard??t.madSlippage,{chainId:Number(r??t.chainId),venue:a,nowMs:n,secret:o,tx:{...t,chainId:Number(r??t.chainId),to:a,data:t.data},requireSigned:!0}),!0}M();T();var Mr=new Pr(["function approve(address spender,uint256 amount) returns (bool)"]);function pe(e){return Array.isArray(e)?`[${e.map(pe).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${pe(e[t])}`).join(",")}}`:JSON.stringify(e)}function k(e,t){let r=String(e||"").trim();if(!qr(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Vr(e,t="vault amount"){try{let r=BigInt(String(e));if(r<=0n)throw new Error("nonpositive");return r.toString()}catch{throw new Error(`${t} must be a positive integer string`)}}function Hr(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x095ea7b3"))throw new Error("approval calldata required");let[r,n]=Mr.decodeFunctionData("approve",t);return{spender:k(r,"approval spender"),amount:Vr(n,"approval amount")}}function wt(e,t){return`0x${Dr("sha256",String(e)).update(t).digest("hex")}`}function bt(e,t){let r=Buffer.from(String(e||"").replace(/^0x/,""),"hex"),n=Buffer.from(String(t||"").replace(/^0x/,""),"hex");return r.length===n.length&&r.length>0&&Ur(r,n)}function gt(e){return C(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}function Et(e){let{signature:t,...r}=e;return r}function xt(e,t={},{chainId:r,nowMs:n=Date.now(),secret:o}={}){if(m(e||{},n,"vault attestation"),!e||e.mode!=="vault-attestation")throw new Error("vault attestation required");if(Number(e.expiresAtMs)<=Number(n))throw new Error("vault attestation expired");let a=Number(r??t.chainId);if(Number(e.chainId)!==a)throw new Error("vault attestation chain mismatch");let i=k(t.to,"vault tx.to");if(k(e.vault,"vault")!==i)throw new Error("vault attestation destination mismatch");if(t.from&&k(e.owner,"vault owner")!==k(t.from,"vault tx.from"))throw new Error("vault attestation owner mismatch");if((t.value==null?"0":String(BigInt((String(t.value).startsWith("0x"),String(t.value)))))!=="0")throw new Error("vault attestation value mismatch");if(e.calldataHash!==W(t.data||"0x"))throw new Error("vault attestation calldata mismatch");let c=wt(gt(o),pe(Et(e)));if(!bt(e.signature,c))throw new Error("vault attestation signature mismatch");return!0}function yt(e,t={},r={},{chainId:n,nowMs:o=Date.now(),secret:a}={}){if(!e||e.mode!=="vault-attestation")throw new Error("vault attestation required");if(String(e.action)!=="deposit")throw new Error("vault approval requires deposit attestation");if(m(e,o,"vault approval attestation"),Number(e.expiresAtMs)<=Number(o))throw new Error("vault attestation expired");let i=wt(gt(a),pe(Et(e)));if(!bt(e.signature,i))throw new Error("vault attestation signature mismatch");let s=Number(t.chainId??n);if(Number(e.chainId)!==s)throw new Error("vault attestation chain mismatch");let c=Hr(t.data);if(k(e.asset,"vault asset")!==k(t.to,"approval token"))throw new Error("vault attestation asset mismatch");if(k(e.vault,"vault")!==c.spender)throw new Error("vault attestation spender mismatch");if(String(e.amount)!==c.amount||String(r.amount)!==c.amount)throw new Error("vault attestation amount mismatch");if(r.provider&&String(r.provider)!==String(e.provider))throw new Error("vault attestation provider mismatch");return!0}import{createHmac as jr,timingSafeEqual as Wr}from"node:crypto";import{Interface as Gr,isAddress as Kr}from"ethers";M();T();var zr=new Gr(["function approve(address spender,uint256 amount) returns (bool)"]),Xr=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});function _e(e){return Array.isArray(e)?`[${e.map(_e).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${_e(e[t])}`).join(",")}}`:JSON.stringify(e)}function S(e,t){let r=String(e||"").trim();if(!Kr(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Yr(e,t="gmx amount"){try{let r=BigInt(String(e));if(r<=0n)throw new Error("nonpositive");return r.toString()}catch{throw new Error(`${t} must be a positive integer string`)}}function Jr(e,t){return`0x${jr("sha256",String(e)).update(t).digest("hex")}`}function Qr(e,t){let r=Buffer.from(String(e||"").replace(/^0x/,""),"hex"),n=Buffer.from(String(t||"").replace(/^0x/,""),"hex");return r.length===n.length&&r.length>0&&Wr(r,n)}function Zr(e){return C(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}function en(e){let{signature:t,...r}=e;return r}function tn(e){let t=String(e||"").toLowerCase();if(!t.startsWith("0x095ea7b3"))throw new Error("approval calldata required");let[r,n]=zr.decodeFunctionData("approve",t);return{spender:S(r,"approval spender"),amount:Yr(n,"approval amount")}}function Oe(e,t){let r=Xr[Number(e)];return!!r&&S(t,"gmx exchange router")===r}function At(e,t){let r=Jr(Zr(t),_e(en(e)));if(!Qr(e.signature,r))throw new Error("gmx attestation signature mismatch")}function vt(e,t={},{chainId:r,nowMs:n=Date.now(),secret:o}={}){if(!e||e.mode!=="gmx-order-attestation")throw new Error("gmx order attestation required");if(Number(e.expiresAtMs)<=Number(n))throw new Error("gmx attestation expired");At(e,o);let a=Number(r??t.chainId);if(Number(e.chainId)!==a)throw new Error("gmx attestation chain mismatch");let i=S(t.to,"gmx tx.to");if(S(e.exchangeRouter,"gmx exchangeRouter")!==i)throw new Error("gmx attestation destination mismatch");if(!Oe(a,i))throw new Error("gmx exchangeRouter mismatch for chain");if(t.from&&S(e.account,"gmx account")!==S(t.from,"gmx tx.from"))throw new Error("gmx attestation account mismatch");m(e||{},n,"gmx order attestation");let s=t.value==null?"0":String(BigInt((String(t.value).startsWith("0x"),String(t.value))));if(String(e.value)!==s||String(e.executionFee)!==s)throw new Error("gmx attestation value mismatch");if(e.calldataHash!==W(t.data||"0x"))throw new Error("gmx attestation calldata mismatch");return!0}function St(e,t={},r={},{chainId:n,nowMs:o=Date.now(),secret:a}={}){if(!e||e.mode!=="gmx-order-attestation")throw new Error("gmx order attestation required");if(m(e,o,"gmx approval attestation"),Number(e.expiresAtMs)<=Number(o))throw new Error("gmx attestation expired");At(e,a);let i=Number(t.chainId??n);if(Number(e.chainId)!==i)throw new Error("gmx attestation chain mismatch");let s=tn(t.data);if(S(e.initialCollateralToken,"gmx collateral")!==S(t.to,"approval token"))throw new Error("gmx attestation collateral mismatch");if(S(e.router,"gmx router")!==s.spender)throw new Error("gmx attestation spender mismatch");if(String(e.initialCollateralDeltaAmount)!==s.amount||String(r.amount)!==s.amount)throw new Error("gmx attestation amount mismatch");if(r.provider&&String(r.provider)!==String(e.provider))throw new Error("gmx attestation provider mismatch");return!0}function It(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let r=String(e??"").trim();if(r==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(r)}`)}}T();var Te=2e4,cn=new rn(["function approve(address spender,uint256 amount) returns (bool)"]);function g(e,t){let r=String(e||"").trim();if(!on(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function Re(e,t="approval amount",{allowZero:r=!1}={}){let n=It(e,t);if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=nn)throw new Error("unlimited approvals are refused; use an exact bounded amount");return n.toString()}function Le(e){return Array.isArray(e)?`[${e.map(Le).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Le(e[t])}`).join(",")}}`:JSON.stringify(e)}var un=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]);function G(e){let t=String(e||"").toLowerCase();return t.length<10?!1:un.has(t.slice(0,10))}function Be(e){if(!G(e))throw new Error("approval calldata required");let t=String(e||"").toLowerCase(),r=t.slice(0,10),n=t.slice(10).match(/.{1,64}/g)||[],o=c=>n[c]?"0x"+n[c].slice(24):null,a=c=>n[c]?BigInt("0x"+n[c]):null,i=null,s=null;switch(r){case"0x095ea7b3":case"0x39509351":i=o(0),s=a(1);break;case"0x61f49ed6":case"0xeb5625d9":case"0xf9255c1f":i=o(1),s=a(2);break;case"0xd505accf":i=o(1),s=a(2);break;case"0x8fcbaf0c":{i=o(1),s=a(4)===0n?0n:(1n<<256n)-1n;break}case"0x87517c45":i=o(1),s=a(2);break;default:throw new Error(`approval selector ${r} is recognised but not decodable; refusing to bound it`)}if(i==null||s==null)throw new Error("invalid approve calldata");return{spender:g(i,"approval spender"),amount:Re(s,"approval amount",{allowZero:!0}),selector:r}}function ln({chainId:e,token:t,spender:r,amount:n,provider:o,routeVenue:a,routeGuard:i,purpose:s,nowMs:c=Date.now(),ttlMs:u=Te}={}){let l=String(s||"").trim(),d={mode:"approval",chainId:Number(e),token:g(t,"approval token"),spender:g(r,"approval spender"),amount:Re(n,"approval amount",{allowZero:l==="revoke"}),provider:String(o||"").trim()||"unknown",routeVenue:g(a||r,"approval route venue"),issuedAtMs:Number(c),expiresAtMs:Number(c)+Number(u||Te)};if(l&&(d.purpose=l),!Number.isFinite(d.chainId))throw new Error("approval chainId required");if(!Number.isFinite(d.issuedAtMs)||!Number.isFinite(d.expiresAtMs)||d.expiresAtMs<=d.issuedAtMs)throw new Error("approval guard expiry invalid");return i&&(d.routeGuardHash=an(sn(Le(i)))),d}function Ct(e,{chainId:t,provider:r,nowMs:n=Date.now(),ttlMs:o=Te}={}){let a=g(e?.token,"approval token"),i=g(e?.spender,"approval spender"),s=ln({chainId:t,token:a,spender:i,amount:"0",provider:r,routeVenue:i,purpose:"revoke",nowMs:n,ttlMs:o});return{chainId:Number(t),to:a,data:cn.encodeFunctionData("approve",[i,"0"]),value:"0x0",madApproval:s}}function kt(e,t={},{chainId:r,nowMs:n=Date.now()}={}){if(!e||e.mode!=="approval")throw new Error("approval guard required");let o=Number(t.chainId??r);if(Number(e.chainId)!==o)throw new Error(`approval chain mismatch: expected ${o}, got ${e.chainId}`);let a=g(t.to,"approval token");if(g(e.token,"approval token")!==a)throw new Error("approval token mismatch");let i=Be(t.data);if(g(e.spender,"approval spender")!==i.spender)throw new Error("approval spender mismatch");let s=String(e.purpose||"")==="revoke";if(i.amount==="0"&&!s)throw new Error("zero approval amount requires revoke purpose");if(Re(e.amount,"approval amount",{allowZero:s})!==i.amount)throw new Error("approval amount mismatch");if((t.value==null?0n:BigInt((String(t.value).startsWith("0x"),String(t.value))))!==0n)throw new Error("approval tx value must be zero");let{now:u}=m(e,n,"approval guard");if(Number(e.issuedAtMs)>u+5e3)throw new Error("approval guard issued in the future");let l=P(o);if(!l.has(i.spender)){if(s)return{chainId:o,token:a,spender:i.spender,amount:i.amount,provider:e.provider||null,purpose:"revoke"};if(String(e.provider||"")==="morpho")return yt(t.madVault||t.vaultGuard,t,e,{chainId:o,nowMs:n}),{chainId:o,token:a,spender:i.spender,amount:i.amount,provider:e.provider||null,purpose:e.purpose||null};throw new Error(`approval spender ${i.spender} not allowlisted for chain ${o}`)}if(String(e.provider||"")==="gmx"&&St(t.madGmx||t.gmxGuard,t,e,{chainId:o,nowMs:n}),e.routeVenue&&!l.has(g(e.routeVenue,"approval route venue")))throw new Error(`approval route venue ${e.routeVenue} not allowlisted for chain ${o}`);return{chainId:o,token:a,spender:i.spender,amount:i.amount,provider:e.provider||null,purpose:e.purpose||null}}import{Interface as dn,isAddress as pn}from"ethers";T();var Fe=2e4,Nt=new dn(["function setApprovalForAll(address operator,bool approved)"]),fn="0xa22cb465";function N(e,t){let r=String(e||"").trim();if(!pn(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function $e(e,t){if(e===!0||e===!1)return e;if(e===1||e==="1"||e===1n)return!0;if(e===0||e==="0"||e===0n)return!1;throw new Error(`${t} must be boolean`)}function K(e){let t=String(e||"").toLowerCase();return t.length>=10&&t.slice(0,10)===fn}function De(e){if(!K(e))throw new Error("setApprovalForAll calldata required");let[t,r]=Nt.decodeFunctionData("setApprovalForAll",e);return{operator:N(t,"nft operator"),approved:$e(r,"nft approved")}}function mn({chainId:e,collection:t,operator:r,approved:n,provider:o,purpose:a,nowMs:i=Date.now(),ttlMs:s=Fe}={}){let c=$e(n,"nft approved"),u={mode:"nft-operator-approval",chainId:Number(e),collection:N(t,"nft collection"),operator:N(r,"nft operator"),approved:c,provider:String(o||"").trim()||"unknown",purpose:a||(c?"grant":"revoke"),issuedAtMs:Number(i),expiresAtMs:Number(i)+Number(s||Fe)};if(!Number.isFinite(u.chainId))throw new Error("nft operator chainId required");if(!Number.isFinite(u.issuedAtMs)||!Number.isFinite(u.expiresAtMs)||u.expiresAtMs<=u.issuedAtMs)throw new Error("nft operator guard expiry invalid");return u}function _t(e,{chainId:t,provider:r,nowMs:n=Date.now(),ttlMs:o=Fe}={}){let a=N(e?.collection||e?.token||e?.contract,"nft collection"),i=N(e?.operator||e?.spender,"nft operator");return{chainId:Number(t),to:a,data:Nt.encodeFunctionData("setApprovalForAll",[i,!1]),value:"0x0",nftApprovalGuard:mn({chainId:t,collection:a,operator:i,approved:!1,provider:r,purpose:"revoke",nowMs:n,ttlMs:o})}}function Ot(e,t={},{chainId:r,nowMs:n=Date.now()}={}){if(!e||e.mode!=="nft-operator-approval")throw new Error("nft operator guard required");let o=Number(t.chainId??r);if(Number(e.chainId)!==o)throw new Error(`nft operator chain mismatch: expected ${o}, got ${e.chainId}`);let a=N(t.to,"nft collection");if(N(e.collection,"nft collection")!==a)throw new Error("nft collection mismatch");let i=De(t.data);if(N(e.operator,"nft operator")!==i.operator)throw new Error("nft operator mismatch");if($e(e.approved,"nft approved")!==i.approved)throw new Error("nft approved mismatch");if((t.value==null?0n:BigInt((String(t.value).startsWith("0x"),String(t.value))))!==0n)throw new Error("nft operator approval tx value must be zero");let{now:c}=m(e,n,"nft operator guard");if(Number(e.issuedAtMs)>c+5e3)throw new Error("nft operator guard issued in the future");let u=String(e.purpose||"");if(!i.approved&&u==="revoke")return{chainId:o,collection:a,operator:i.operator,approved:!1,purpose:"revoke",provider:e.provider||null};if(!P(o).has(i.operator))throw new Error(`nft operator ${i.operator} not allowlisted for chain ${o}`);return{chainId:o,collection:a,operator:i.operator,approved:i.approved,purpose:u||"grant",provider:e.provider||null}}import{Interface as hn,MaxUint256 as wn,isAddress as bn}from"ethers";var Lt="0xa9059cbb",Rt="0x23b872dd";var Tt=new hn(["function transfer(address to,uint256 amount) returns (bool)","function transferFrom(address from,address to,uint256 amount) returns (bool)"]);function F(e,t){let r=String(e||"").trim();if(!bn(r))throw new Error(`${t} must be an address`);return r.toLowerCase()}function q(e,t="token transfer amount",{allowZero:r=!1}={}){if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`)}let n;try{n=BigInt(String(e))}catch{throw new Error(`${t} must be an integer string`)}if(r?n<0n:n<=0n)throw new Error(`${t} must be positive`);if(n>=wn)throw new Error("unbounded token transfer amount refused");return n.toString()}function gn(e={}){let t=e.value==null?"0":String(e.value);return BigInt(t)}function Bt(e){let t=String(e||"").toLowerCase();return t.startsWith(Lt)||t.startsWith(Rt)}function En(e){let t=String(e||"").toLowerCase();try{if(t.startsWith(Lt)){let[r,n]=Tt.decodeFunctionData("transfer",e);return{kind:"transfer",recipient:F(r,"token transfer recipient"),amount:q(n)}}if(t.startsWith(Rt)){let[r,n,o]=Tt.decodeFunctionData("transferFrom",e);return{kind:"transferFrom",from:F(r,"token transfer source"),recipient:F(n,"token transfer recipient"),amount:q(o)}}}catch(r){throw/token transfer/.test(String(r?.message||r))?r:new Error("invalid token transfer calldata")}throw new Error("token transfer calldata required")}function Ft(e,t={},{chainId:r,nowMs:n=Date.now()}={}){if(!e||e.mode!=="token-transfer")throw new Error("token transfer guard required");let o=Number(n);if(!Number.isFinite(o))throw new Error("token transfer guard: current time must be a finite number");let a=Number(e.issuedAtMs),i=Number(e.expiresAtMs);if(!Number.isFinite(a)||!Number.isFinite(i))throw new Error("token transfer guard: issuedAtMs and expiresAtMs are required and must be finite");if(i<=a)throw new Error("token transfer guard: expiry must be after issuance");if(o>i)throw new Error(`token transfer guard expired at ${i}, now ${o}`);let s=Number(t.chainId??r);if(Number(e.chainId)!==s)throw new Error(`token transfer chain mismatch: expected ${s}, got ${e.chainId}`);let c=F(t.to,"token transfer token");if(F(e.token,"token transfer token")!==c)throw new Error("token transfer token mismatch");let u=En(t.data);if(String(e.kind)!==u.kind)throw new Error("token transfer kind mismatch");if(F(e.recipient,"token transfer recipient")!==u.recipient)throw new Error("token transfer recipient mismatch");if(u.kind==="transferFrom"&&F(e.from,"token transfer source")!==u.from)throw new Error("token transfer source mismatch");if(e.amount==null&&e.maxAmount==null)throw new Error("token transfer guard must bind an amount or a maxAmount \u2014 a capless guard authorizes any size");if(e.amount!=null&&e.maxAmount!=null&&BigInt(q(e.amount))>BigInt(q(e.maxAmount)))throw new Error("token transfer guard amount exceeds its own maxAmount");if(e.amount!=null&&q(e.amount)!==u.amount)throw new Error("token transfer amount mismatch");if(e.maxAmount!=null&&BigInt(u.amount)>BigInt(q(e.maxAmount)))throw new Error("token transfer amount exceeds guard maxAmount");if(gn(t)!==0n)throw new Error("token transfer tx value must be zero");if(Number(e.expiresAtMs)<=Number(n))throw new Error("token transfer guard expired");if(Number(e.issuedAtMs)>Number(n)+5e3)throw new Error("token transfer guard issued in the future");return{chainId:s,token:c,kind:u.kind,from:u.from||null,recipient:u.recipient,amount:u.amount,provider:e.provider||null,purpose:e.purpose||null}}var In=[1,8453,42161,137,10,56,43114,999,4663,2741,988];function Cn(e,t){return new Set(pt(e,t).split(",").map(r=>r.trim().toLowerCase()).filter(Boolean))}function kn(){let e=String(B("ORACLE_ALLOWED_CHAINS","MAD_ALLOWED_CHAINS","")).trim();return e?new Set(e.split(",").map(t=>Number(t.trim())).filter(Number.isFinite)):new Set(In.map(Number))}function me(e,t,r){let n=String(B(e,t,"")).trim();try{return BigInt(n||r)}catch{return BigInt(r)}}function Nn(){return me("ORACLE_MAX_TX_VALUE_WEI","MAD_MAX_TX_VALUE_WEI","50000000000000000")}function _n(){return me("ORACLE_MAX_DAILY_VALUE_WEI","MAD_MAX_DAILY_VALUE_WEI","150000000000000000")}function On(){return me("ORACLE_MAX_GAS_LIMIT","MAD_MAX_GAS_LIMIT","5000000")}function Tn(){return me("ORACLE_MAX_TX_FEE_WEI","MAD_MAX_TX_FEE_WEI","5000000000000000")}function he(){return ft("policy-daily.json","ORACLE_POLICY_STATE","MAD_POLICY_STATE")}function fe(e){if(e==null)return 0n;if(typeof e=="number"&&(!Number.isInteger(e)||!Number.isSafeInteger(e)))throw new Error(`exec-policy: value ${e} is not an exact integer \u2014 pass wei as a decimal string or BigInt`);try{return typeof e=="string"&&e.startsWith("0x"),BigInt(e)}catch{throw new Error(`exec-policy: cannot interpret ${JSON.stringify(String(e))} as an integer wei amount`)}}function Pe(e,t){if(e==null||e==="")return null;try{let r=(typeof e=="string"&&e.startsWith("0x"),BigInt(e));if(r<0n)throw new Error("negative");return r}catch{throw new Error(`policy: ${t} must be a non-negative integer`)}}function Ln(e={}){let t=Pe(e.gasLimit??e.gas,"gasLimit");if(t!=null){let n=On();if(t>n)throw new Error(`policy: gasLimit ${t} exceeds cap ${n} (ORACLE_MAX_GAS_LIMIT)`)}let r=Pe(e.maxFeePerGas??e.gasPrice,"maxFeePerGas/gasPrice");if(t!=null&&r!=null){let n=t*r,o=Tn();if(n>o)throw new Error(`policy: gas fee ceiling ${n} exceeds max tx fee ${o} (ORACLE_MAX_TX_FEE_WEI)`)}}var _=!1;function Rn(){let e=()=>({windowStart:Date.now(),spentWei:"0"}),t;try{t=JSON.parse(xn(he(),"utf8"))}catch(o){if(o?.code==="ENOENT")return e();throw _=!0,new Error(`policy: daily spend ledger cannot be read or is corrupt: ${o?.message||o}`)}let r=Number(t?.windowStart),n;try{n=BigInt(t?.spentWei)}catch{throw _=!0,new Error("policy: daily spend ledger is corrupt: invalid spentWei")}if(!Number.isFinite(r)||r<=0||n<0n)throw _=!0,new Error("policy: daily spend ledger is corrupt: invalid window");return Date.now()-r>1440*60*1e3?e():(_=!1,{windowStart:r,spentWei:n.toString()})}function Bn(e){let t=he(),r=`${t}.${process.pid}.tmp`;try{Ue(Dt(t),{recursive:!0}),$t(r,JSON.stringify(e),{mode:384}),yn(r,t),_=!1}catch(n){_=!0;try{An(r)}catch{}throw new Error(`policy: daily spend ledger cannot be written or persisted: ${n?.message||n}`)}}function Fn(e){let t=he(),r=`${t}.lock`,n=Sn(r,"owner.json");function o(){$t(n,JSON.stringify({pid:process.pid,createdAtMs:Date.now()}),{mode:384})}function a(){vn(r,{recursive:!0,force:!0})}function i(){Ue(Dt(t),{recursive:!0}),Ue(r,{mode:448});try{o()}catch(s){try{a()}catch(c){throw new Error(`owner metadata write failed (${s?.message||s}); new lock cleanup also failed (${c?.message||c})`)}throw s}}try{i()}catch(s){throw s?.code!=="EEXIST"?new Error(`policy: daily spend ledger lock cannot be acquired: ${s?.message||s}`):new Error(`policy: daily spend ledger lock is busy or stale at ${r}; manual operator recovery required`)}try{return e()}finally{try{a()}catch(s){throw _=!0,new Error(`policy: daily spend ledger lock cannot be released: ${s?.message||s}`)}}}function $n(e){if(_&&String(process.env.ORACLE_ALLOW_EPHEMERAL_CAPS||"")!=="1")throw new Error(`policy: refusing to ${e} \u2014 the daily spend ledger at ${he()} is not writable, so the daily cap would reset on restart. Fix the path, or set ORACLE_ALLOW_EPHEMERAL_CAPS=1 to accept memory-only caps.`)}function Dn(e={},{chainId:t,to:r,from:n,data:o}={}){if(e?.emergencyCancel?.mode!=="cancel")return!1;if(o!=="0x")throw new Error("policy: emergency cancel must carry empty calldata");if(!/^0x[0-9a-f]{40}$/.test(String(r||"")))throw new Error("policy: emergency cancel target must be the sender");if(r!==n)throw new Error("policy: emergency cancel must send to self");if(Number(e.emergencyCancel.chainId??e.chainId)!==Number(t))throw new Error("policy: emergency cancel chain mismatch");if(fe(e.value)!==0n)throw new Error("policy: emergency cancel value must be zero");if(Pe(e.nonce??e.emergencyCancel.nonce,"nonce")==null)throw new Error("policy: emergency cancel nonce required");return!0}function we(e={},t="broadcast"){let r=String(t??"").trim().toLowerCase();if(r!=="sign"&&r!=="broadcast")throw new Error(`policy: unknown phase ${JSON.stringify(t)}, expected "sign" or "broadcast"`);t=r,$n(t);let n=Number(e.chainId);if(!kn().has(n))throw new Error(`policy: chainId ${n} not in ORACLE_ALLOWED_CHAINS`);let o=String(e.to||"").toLowerCase(),a=String(e.data||"0x").toLowerCase(),i=a!=="0x"&&G(a),s=a!=="0x"&&K(a),c=String(e.from||"").toLowerCase(),u=null,l=null;Ln(e),i&&(u=kt(e.madApproval||e.approvalGuard,{...e,chainId:n,to:o,data:a},{chainId:n})),s&&(l=Ot(e.nftApprovalGuard||e.madNftApproval,{...e,chainId:n,to:o,data:a},{chainId:n})),!i&&a!=="0x"&&Bt(a)&&Ft(e.madTokenTransfer||e.tokenTransferGuard,{...e,chainId:n,to:o,data:a},{chainId:n}),!i&&o&&Oe(n,o)&&vt(e.madGmx||e.gmxGuard,{...e,chainId:n,to:o,data:a},{chainId:n});let d=Cn("ORACLE_DEST_ALLOWLIST","MAD_DEST_ALLOWLIST");for(let w of P(n))d.add(w);if(!e.to||String(e.to).trim()===""){if(!(String(B("ORACLE_ALLOW_CREATE","MAD_ALLOW_CREATE","0")).trim()==="1"))throw new Error("policy: contract creation (tx without `to`) is disabled \u2014 set ORACLE_ALLOW_CREATE=1 to permit deploys");if(fe(e.value)>0n)throw new Error("policy: contract creation may not carry native value")}if(o&&!d.has(o)){let w=u?.purpose==="revoke"||l?.purpose==="revoke",y=Dn(e,{chainId:n,to:o,from:c,data:a}),$=e.madRoute||e.routeAttestation,Ge=e.madVault||e.vaultGuard;if(!(w||y)){if(!$&&!Ge)throw d.size===0?new Error(`policy: no destination allowlist configured for chain ${n} \u2014 set ORACLE_DEST_ALLOWLIST or add the chain's venues before sending`):new Error(`policy: destination ${o} not allowlisted for chain ${n} (env ORACLE_DEST_ALLOWLIST or venues.mjs)`)}!w&&!y&&($?ht($,{...e,chainId:n,to:o,data:a},{chainId:n}):xt(Ge,{...e,chainId:n,to:o,data:a},{chainId:n}))}if(o&&a!=="0x"&&ut(n,o))try{re(e.slippageGuard??e.madSlippage,{chainId:n,venue:o,tx:{...e,chainId:n,to:o,data:a},requireSigned:!0})}catch(w){let y=String(w?.message||w);throw/required/.test(y)?w:new Error(`policy: ${y}`)}if(!(String(B("ORACLE_VALUE_CAPS_ENABLED","MAD_VALUE_CAPS_ENABLED","1")).trim()!=="0"))return!0;let h=fe(e.value),We=Nn();if(h>We)throw new Error(`policy: tx value ${h} exceeds per-tx cap ${We} (ORACLE_MAX_TX_VALUE_WEI)`);return t==="broadcast"&&h>0n&&Fn(()=>{let w=Rn(),y=fe(w.spentWei),$=_n();if(y+h>$)throw new Error(`policy: daily native spend ${y+h} would exceed cap ${$} (ORACLE_MAX_DAILY_VALUE_WEI)`);Bn({windowStart:w.windowStart,spentWei:(y+h).toString()})}),!0}import{isAddress as Un}from"ethers";function Ut(e){return(Array.isArray(e)?e:String(e||"").split(",")).map(r=>String(r||"").trim()).filter(Boolean).map(r=>{if(!Un(r))throw new Error(`arm policy address ${r} is invalid`);return r.toLowerCase()})}function Pn(e){return(Array.isArray(e)?e:String(e||"").split(",")).map(r=>String(r||"").trim().toLowerCase()).filter(Boolean).map(r=>{if(!/^0x[0-9a-f]{8}$/.test(r))throw new Error(`arm policy selector ${r} is invalid`);return r})}function qn(e,t={}){let r=Number(e.chainId),n=Array.isArray(t.chains)?t.chains.map(o=>Number(o)).filter(Number.isFinite):[];if(n.length&&!n.includes(r))throw new Error(`arm policy: chain ${r} not allowed`)}function Mn(e={}){return e?.emergencyCancel?.mode==="cancel"||e?.madApproval?.purpose==="revoke"||e?.approvalGuard?.purpose==="revoke"||e?.nftApprovalGuard?.purpose==="revoke"||e?.madNftApproval?.purpose==="revoke"}function Vn(e){if(e==null||e==="")return 0n;if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("arm policy: tx value must be exact wei");return BigInt(e)}let t=String(e);return t.startsWith("0x"),BigInt(t)}function qe(e={},t={}){if(t.armed!==!0)throw new Error("arm policy: local vault is disarmed");qn(e,t);let r=Mn(e),n=String(e.to||"").toLowerCase(),o=String(e.data||"0x").toLowerCase(),a=t.maxSpendWei!=null?BigInt(String(t.maxSpendWei)):null;if(a!=null&&Vn(e.value)>a)throw new Error(`arm policy: tx value exceeds maxSpendWei ${a}`);let i=Ut(t.destinations||t.destinationAllowlist||[]);if(!r&&i.length&&!i.includes(n))throw new Error(`arm policy: destination ${n} not allowed`);let s=Pn(t.selectors||t.selectorAllowlist||[]);if(!r&&s.length&&o!=="0x"&&!s.includes(o.slice(0,10)))throw new Error(`arm policy: selector ${o.slice(0,10)} not allowed`);let c=Ut(t.spenders||t.operators||t.spenderAllowlist||[]);if(!r&&c.length&&G(o)){let u=Be(o);if(!c.includes(u.spender))throw new Error(`arm policy: approval spender ${u.spender} not allowed`)}if(!r&&c.length&&K(o)){let u=De(o);if(u.approved&&!c.includes(u.operator))throw new Error(`arm policy: nft operator ${u.operator} not allowed`)}return!0}import{Wallet as Hn,JsonRpcProvider as jn,getAddress as be,isAddress as Wn,parseUnits as Gn}from"ethers";se();function qt(e){if(e==null||e==="")return null;if(/^\d+$/.test(String(e)))return Number(e);let t=String(e).toLowerCase(),r=Object.entries(V).find(([n,o])=>n===t||String(o.name).toLowerCase()===t);return r?r[1].chainId:null}function Kn(e,t){let r=String(e||"").trim();if(!Wn(r))throw new Error(`${t} must be an address`);return be(r)}function Me(e){if(e==null||e==="")return;let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new Error("nonce must be a non-negative safe integer");return t}function Pt(e,t){if(e==null||e==="")return;let r=Number(e);if(!Number.isFinite(r)||r<=0)throw new Error(`${t} must be positive gwei`);return Gn(String(e),"gwei").toString()}function Ve(e={},t={}){let r={...e},n=Pt(t.priorityGwei??t.priority,"priority fee"),o=Pt(t.maxFeeGwei??t.maxFee,"max fee");if(n&&(r.maxPriorityFeePerGas=n),o&&(r.maxFeePerGas=o),n&&o&&BigInt(o)<BigInt(n))throw new Error("max fee must be >= priority fee");let a=t.gasLimit??t.gas;return a!=null&&a!==""&&(r.gasLimit=String(a)),r}function Mt({chainId:e,from:t,nonce:r,priorityGwei:n,maxFeeGwei:o,gasLimit:a}={}){let i=Kn(t,"cancel sender"),s=Ve({chainId:Number(e),from:i,to:i,value:"0",data:"0x",nonce:Me(r),emergencyCancel:{mode:"cancel",chainId:Number(e),from:i,nonce:Me(r)}},{priorityGwei:n,maxFeeGwei:o,gasLimit:a});if(!Number.isFinite(s.chainId))throw new Error("chainId required");if(s.nonce==null)throw new Error("nonce required for same-nonce emergency cancel");return s}function zn(e={}){let t=qt(e.chain??e.chainId??"base");if(!t||!ie(t))throw new Error(`unsupported or unknown chain ${e.chain??e.chainId??""}`);let r=Me(e.nonce),n=String(e.type||e.kind||"erc20").toLowerCase(),o;if(n==="cancel"||n==="nonce-cancel")o=Mt({chainId:t,from:e.owner||e.from,nonce:r,priorityGwei:e.priorityGwei,maxFeeGwei:e.maxFeeGwei,gasLimit:e.gasLimit});else if(n==="erc20"||n==="token")o=Ct({token:e.token||e.contract,spender:e.spender||e.operator},{chainId:t,provider:"local-emergency",nowMs:e.nowMs??Date.now()}),r!=null&&(o.nonce=r),o=Ve(o,e);else if(n==="nft"||n==="erc721"||n==="erc1155"||n==="operator")o=_t({collection:e.collection||e.token||e.contract,operator:e.operator||e.spender},{chainId:t,provider:"local-emergency",nowMs:e.nowMs??Date.now()}),r!=null&&(o.nonce=r),o=Ve(o,e);else throw new Error(`unsupported emergency revoke type ${n}`);return we(o,"sign"),{chainId:t,transactions:[o]}}async function He(e={}){let t=e.env||process.env,r=Q(t),n;try{n=zn(e)}catch(l){return{ok:!1,failureKind:"prepare-error",error:l.message||String(l),backendSigner:!1}}let o={ok:!0,mode:e.execute?"local-execute":"prepare-only",chainId:n.chainId,chain:H(n.chainId)?.name||String(n.chainId),transactions:n.transactions,backendSigner:!1,requiresWalletSignature:!e.execute,requiresLocalVault:!0,localVault:!0,warning:"Emergency revoke/cancel is not a guarantee: it can race pending or standing approvals, but cannot interrupt an atomic approval+drain transaction once mined."};if(!e.execute)return o;let a,i;try{a=ee(t),i=Z(t,{passphrase:e.passphrase})}catch(l){return{ok:!1,failureKind:"not-ready",error:l.message||String(l),status:r}}if(Array.isArray(a.chains)&&a.chains.length){let l=a.chains.map(d=>qt(d)).filter(Boolean);if(l.length&&!l.includes(n.chainId))return{ok:!1,failureKind:"chain-not-allowed",error:`chain ${n.chainId} not in arm allowlist ${a.chains.join(",")}`}}let s=e.rpcUrl||ae(n.chainId,t);if(!s)return{ok:!1,failureKind:"rpc-missing",error:`no RPC for chain ${n.chainId}`};let c=new Hn(Xn(i.material),new jn(s,n.chainId)),u=[];try{for(let l of n.transactions){let d=l.from?be(l.from):c.address;if(be(d)!==be(c.address))return{ok:!1,failureKind:"sender-mismatch",error:`vault address ${c.address} != emergency sender ${d}`};let I={...l};delete I.from,delete I.emergencyCancel,delete I.madApproval,delete I.nftApprovalGuard,qe({...l,from:c.address},a),we({...l,from:c.address},"broadcast");let b=await c.sendTransaction(I),h=e.wait===!1?null:await b.wait();u.push({hash:b.hash,receipt:h?{status:h.status,blockNumber:h.blockNumber,gasUsed:h.gasUsed?.toString?.()}:null})}return{...o,ok:!0,executed:!0,sent:u,note:"Signed and broadcast from the local encrypted vault only."}}catch(l){return{ok:!1,failureKind:"execute-failed",error:l.message||String(l),prepared:o,sent:u}}}function Xn(e){let t=String(e||"").trim();if(t.startsWith("{"))try{let r=JSON.parse(t);t=r.privateKey||r.private_key||r.key||t}catch{}return!t.startsWith("0x")&&/^[0-9a-fA-F]{64}$/.test(t)&&(t=`0x${t}`),t}var je=`oracle revoke emergency [options]
|
|
2
|
+
|
|
3
|
+
Local emergency revoke/cancel. Prepare-only by default; --execute signs and
|
|
4
|
+
broadcasts from THIS machine's encrypted vault only.
|
|
5
|
+
|
|
6
|
+
Examples:
|
|
7
|
+
oracle revoke emergency --type erc20 --token 0xToken --spender 0xSpender --chain base
|
|
8
|
+
oracle revoke emergency --type nft --collection 0xNFT --operator 0xOperator --chain base
|
|
9
|
+
oracle revoke emergency --type cancel --owner 0xYou --nonce 42 --chain base
|
|
10
|
+
oracle revoke emergency --type erc20 --token 0xToken --spender 0xSpender --nonce 42 --execute --pass-env ORACLE_LOCAL_VAULT_PASS
|
|
11
|
+
|
|
12
|
+
Options:
|
|
13
|
+
--type <erc20|nft|cancel>
|
|
14
|
+
--chain <id|name>
|
|
15
|
+
--token <addr> ERC20 token for approve(spender,0)
|
|
16
|
+
--spender <addr> ERC20 spender
|
|
17
|
+
--collection <addr> NFT collection for setApprovalForAll(operator,false)
|
|
18
|
+
--operator <addr> NFT operator
|
|
19
|
+
--owner <addr> sender for same-nonce cancel prepare
|
|
20
|
+
--nonce <n> same nonce replacement
|
|
21
|
+
--priority-gwei <n> high priority fee for race mode
|
|
22
|
+
--max-fee-gwei <n> max fee for race mode
|
|
23
|
+
--gas-limit <n>
|
|
24
|
+
--execute local sign+broadcast only
|
|
25
|
+
--pass-env <VAR> env var holding vault passphrase for --execute
|
|
26
|
+
--rpc <url>
|
|
27
|
+
--no-wait
|
|
28
|
+
--json
|
|
29
|
+
`;function p(e,t){let r=e.find(o=>o.startsWith(`--${t}=`));if(r)return r.split("=").slice(1).join("=");let n=e.indexOf(`--${t}`);return n>=0&&e[n+1]&&!e[n+1].startsWith("--")?e[n+1]:null}function Yn(e){let t=p(e,"pass-env");if(t){let r=process.env[t];if(!r)throw new Error(`env ${t} is empty`);return r}return process.env.ORACLE_LOCAL_VAULT_PASS||void 0}var lu={name:"revoke",summary:"prepare or locally execute emergency approval revokes/cancels",group:"local",usage:je,async run(e){let t=e.argv||[];if(!t.length||t.includes("--help")||t.includes("-h"))return process.stdout.write(je+`
|
|
30
|
+
`),0;if(t[0]!=="emergency")return process.stderr.write(je+`
|
|
31
|
+
`),1;let n=t.slice(1),o=n.includes("--execute")||n.includes("--fire"),a=await He({type:p(n,"type")||p(n,"kind")||"erc20",chain:p(n,"chain"),token:p(n,"token")||p(n,"contract"),spender:p(n,"spender"),collection:p(n,"collection")||p(n,"nft"),operator:p(n,"operator"),owner:p(n,"owner")||p(n,"from"),nonce:p(n,"nonce"),priorityGwei:p(n,"priority-gwei")||p(n,"priority"),maxFeeGwei:p(n,"max-fee-gwei")||p(n,"max-fee"),gasLimit:p(n,"gas-limit")||p(n,"gas"),execute:o,passphrase:o?Yn(n):void 0,rpcUrl:p(n,"rpc"),wait:!n.includes("--no-wait")});if(n.includes("--json"))return process.stdout.write(JSON.stringify(a,null,2)+`
|
|
32
|
+
`),a.ok?0:1;if(!a.ok)return process.stderr.write(`revoke failed: ${a.error||a.failureKind}
|
|
33
|
+
`),1;process.stdout.write(`mode: ${a.mode}
|
|
34
|
+
`),process.stdout.write(`chain: ${a.chain} (${a.chainId})
|
|
35
|
+
`),process.stdout.write(`txs: ${a.transactions.length}
|
|
36
|
+
`);for(let[i,s]of a.transactions.entries())process.stdout.write(`tx[${i}].to: ${s.to}
|
|
37
|
+
`),s.nonce!=null&&process.stdout.write(`tx[${i}].nonce: ${s.nonce}
|
|
38
|
+
`);if(a.sent?.length)for(let i of a.sent)process.stdout.write(`hash: ${i.hash}
|
|
39
|
+
`);return process.stdout.write(`${a.warning}
|
|
40
|
+
`),0}};export{lu as default};
|