@oracle-agent/oracle 0.35.43 → 0.35.44

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.
Files changed (63) hide show
  1. package/dist/agent-sessions.mjs +19 -19
  2. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  3. package/dist/bin/desk-server.mjs +28 -28
  4. package/dist/bin/oracle-data-mcp.mjs +19 -19
  5. package/dist/bin/oracle-gateway.mjs +42 -42
  6. package/dist/bin/oracle-investigate.mjs +5 -5
  7. package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
  8. package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
  9. package/dist/bin/oracle-mev-shadow.mjs +6 -6
  10. package/dist/bin/oracle-public-server.mjs +5 -5
  11. package/dist/bin/oracle-route.mjs +18 -18
  12. package/dist/bin/oracle-scan.mjs +11 -11
  13. package/dist/bin/oracle.mjs +12 -12
  14. package/dist/cli/commands/agent-session.mjs +21 -21
  15. package/dist/cli/commands/airdrop.mjs +10 -10
  16. package/dist/cli/commands/chat.mjs +218 -217
  17. package/dist/cli/commands/data.mjs +244 -8
  18. package/dist/cli/commands/doctor.mjs +5 -5
  19. package/dist/cli/commands/eval.mjs +157 -153
  20. package/dist/cli/commands/extension-policy.mjs +1 -1
  21. package/dist/cli/commands/farm.mjs +17 -17
  22. package/dist/cli/commands/fees.mjs +3 -3
  23. package/dist/cli/commands/follow.mjs +17 -17
  24. package/dist/cli/commands/mcp.mjs +6 -6
  25. package/dist/cli/commands/mint.mjs +10 -10
  26. package/dist/cli/commands/model.mjs +222 -221
  27. package/dist/cli/commands/quickstart.mjs +7 -7
  28. package/dist/cli/commands/receipt.mjs +8 -8
  29. package/dist/cli/commands/resolve.mjs +10 -10
  30. package/dist/cli/commands/sign.mjs +11 -11
  31. package/dist/cli/commands/signer.mjs +20 -20
  32. package/dist/cli/commands/snipe.mjs +11 -11
  33. package/dist/cli/commands/strategy.mjs +5 -5
  34. package/dist/cli/commands/swap.mjs +11 -11
  35. package/dist/cli/commands/venues.mjs +2 -2
  36. package/dist/data/desk-data.mjs +26 -26
  37. package/dist/data/names.mjs +3 -3
  38. package/dist/data/providers/farming.mjs +2 -2
  39. package/dist/data/providers/lp-destination-discovery.mjs +4 -4
  40. package/dist/index.mjs +44 -44
  41. package/dist/investigator/index.mjs +2 -2
  42. package/dist/launch-radar/index.mjs +5 -5
  43. package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
  44. package/dist/local-signer/index.mjs +3 -3
  45. package/dist/local-signer/runtime.mjs +16 -16
  46. package/dist/nft/universal-mint-router.mjs +4 -4
  47. package/dist/notifications/index.mjs +7 -7
  48. package/dist/router/index.mjs +3 -3
  49. package/dist/router/prepare-bridge.mjs +2 -2
  50. package/dist/router/prepare-route.mjs +3 -3
  51. package/dist/scanner/index.mjs +4 -4
  52. package/dist/strategy/index.mjs +3 -3
  53. package/dist/tui/standalone-client.mjs +90 -88
  54. package/package.json +1 -1
  55. package/public/eval-report.json +347 -13
  56. package/public/oracle-splash/docs/browser-and-web/index.html +2 -2
  57. package/public/oracle-splash/docs/connectors/index.html +2 -2
  58. package/public/oracle-splash/docs/getting-started/index.html +2 -2
  59. package/public/oracle-splash/docs/index.html +3 -3
  60. package/public/oracle-splash/docs/reference/index.html +2 -2
  61. package/public/oracle-splash/docs/security/index.html +2 -2
  62. package/public/oracle-splash/docs/using-oracle/index.html +2 -2
  63. package/server.json +2 -2
@@ -1,7 +1,7 @@
1
- import{createHash as Mt}from"node:crypto";import{types as F}from"node:util";import W from"node:net";import kt from"node:dns";var Ct=new Set(["localhost","metadata.google.internal","metadata.goog"]);function ue(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=s=>{if(!s)return[];let l=s.split(":"),d=l.at(-1);if(d?.includes(".")){let m=d.split(".").map(Number);if(m.length!==4||m.some(h=>!Number.isInteger(h)||h<0||h>255))return null;l.splice(l.length-1,1,(m[0]<<8|m[1]).toString(16),(m[2]<<8|m[3]).toString(16))}return l.some(m=>!/^[0-9a-f]{1,4}$/.test(m))?null:l.map(m=>Number.parseInt(m,16))},[n,o]=t.split("::"),a=r(n),i=r(o);if(!a||!i)return null;let c=t.includes("::"),u=8-a.length-i.length;if(!c&&u!==0||c&&u<1)return null;let f=[...a,...Array(Math.max(0,u)).fill(0),...i];return f.length!==8?null:Uint8Array.from(f.flatMap(s=>[s>>8,s&255]))}function ye(e,t,r){let n=Math.floor(r/8),o=r%8;for(let i=0;i<n;i+=1)if(e[i]!==t[i])return!1;if(!o)return!0;let a=255<<8-o;return(e[n]&a)===(t[n]&a)}function xe(e){if(W.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(W.isIPv6(e)){let t=ue(e);if(!t)return!1;let r=ue("::ffff:0:0");return ye(t,r,96)?xe([...t.slice(12)].join(".")):ye(t,ue("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,a])=>ye(t,ue(o),a)):!1}return!1}function $t(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Ct.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=W.isIP(r);return n!==0&&!xe(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function Ee(e,{lookupFn:t=kt.promises.lookup}={}){let r=$t(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:W.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(o=>!xe(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function Se({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let l=await t();r=l.Agent,n=l.fetch}catch(l){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${l?.message||l}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let o=l=>String(l).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),a=new Map,i=l=>(Array.isArray(l)?l:[l]).map(d=>typeof d=="string"?{address:d}:d).filter(d=>d&&d.address).map(d=>({address:d.address,family:d.family||(W.isIPv6(d.address)?6:4)})),c=(l,d,m)=>{a.set(o(l),i(typeof d=="string"?[{address:d,family:m}]:d))},u=l=>{let d=o(l);if(W.isIP(d))return[{address:d,family:W.isIPv6(d)?6:4}];let m=a.get(d);if(!m||!m.length)throw new Error(`refused: unpinned host ${l} during pinned fetch`);return m},f=new r({connect:{lookup(l,d,m){let h;try{h=u(l)}catch(p){return m(p)}return d?.all?m(null,h):m(null,h[0].address,h[0].family)}}}),s=Lt((l,d={})=>n(l,{...d,dispatcher:f}),c);return{dispatcher:f,fetch:s,pin:c,resolve:u,async close(){try{await f.destroy()}catch{}}}}var ve=Symbol.for("oracle.egressGuard.pinCapableFetch");function Lt(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[ve]=Object.freeze({pin:t}),e}function Ae(e){return typeof e=="function"&&typeof e[ve]?.pin=="function"}function De(e,t,r){if(!Ae(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[ve].pin(t,r)}var Ft=new Set([408,425,429,500,502,503,504]),He=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Bt=2,Ge=4e3,jt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Dt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Ht=AbortSignal.prototype.throwIfAborted,Gt=EventTarget.prototype.addEventListener,qe=EventTarget.prototype.removeEventListener,We=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,ae=e=>e?jt.call(e):!1,qt=e=>e?Dt.call(e):void 0,Wt=new Set([301,302,303,307,308]),fe=3,zn=64*1024,M=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function A(e){return D(`HTTP JSON body refused: ${e}`)}function Ut(e){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(t=>typeof F[t]=="function"&&F[t](e))}function Vt(e){let t=[],r=0,n=0,o=0,a=0,i=new WeakSet,c=s=>{if(r+=Buffer.byteLength(s,"utf8"),r>M.bytes)throw A("serialized byte limit exceeded");t.push(s)},u=s=>{if(Buffer.byteLength(s,"utf8")>M.bytes)throw A("serialized byte limit exceeded");return JSON.stringify(s)},f=(s,l)=>{if(n+=1,n>M.nodes)throw A("node limit exceeded");if(l>M.depth)throw A("depth limit exceeded");if(s===null){c("null");return}if(typeof s=="string"){c(u(s));return}if(typeof s=="boolean"){c(s?"true":"false");return}if(typeof s=="number"){if(!Number.isFinite(s))throw A("non-finite number");c(Object.is(s,-0)?"0":String(s));return}if(typeof s!="object")throw A("unsupported non-JSON value");if(F.isProxy(s))throw A("proxy value");if(Ut(s))throw A("unsupported exotic object");if(i.has(s))throw A("cyclic value");i.add(s);try{if(Object.getOwnPropertySymbols(s).length>0)throw A("symbol-keyed fields are unsupported");if(Array.isArray(s)){let h=Object.getPrototypeOf(s),p=0;for(;h!==null;){if(F.isProxy(h))throw A("proxy array prototype");if(p+=1,p>M.depth)throw A("array prototype depth limit exceeded");h=Object.getPrototypeOf(h)}if(s.length>M.arrayLength)throw A("array length limit exceeded");for(let b=0;b<s.length;b+=1){let T=Object.getOwnPropertyDescriptor(s,String(b));if(!T||!Object.hasOwn(T,"value")||T.enumerable!==!0)throw A("array entries must be dense enumerable own data")}let g=0;for(let b in s){if(a+=1,a>M.fields)throw A("enumeration limit exceeded");if(Object.hasOwn(s,b)&&(g+=1,g>s.length))throw A("named array fields are unsupported")}if(g!==s.length)throw A("array entries must be dense enumerable own data");c("[");for(let b=0;b<s.length;b+=1)b&&c(","),f(Object.getOwnPropertyDescriptor(s,String(b)).value,l+1);c("]");return}let d=Object.getPrototypeOf(s);if(d!==Object.prototype&&d!==null)throw A("non-plain object");let m=[];for(let h in s){if(a+=1,a>M.fields)throw A("enumeration limit exceeded");if(!Object.hasOwn(s,h))continue;if(o+=1,o>M.fields)throw A("field limit exceeded");let p=Object.getOwnPropertyDescriptor(s,h);if(!p||!Object.hasOwn(p,"value")||p.enumerable!==!0)throw A("object fields must be enumerable own data");m.push([h,p.value])}c("{");for(let h=0;h<m.length;h+=1)h&&c(","),c(u(m[h][0])),c(":"),f(m[h][1],l+1);c("}")}finally{i.delete(s)}};return f(e,0),t.join("")}function zt(e){let t=Object.create(null);if(e==null)return t;if(typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP headers must be an object");if(F.isProxy(e))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(e)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let o=n.toLowerCase();if(r.has(o))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(o);let a=Object.getOwnPropertyDescriptor(e,n);if(!a||!Object.hasOwn(a,"value"))throw new TypeError("HTTP headers must contain own data properties");let i=a.value;if(i==null||["object","function","symbol"].includes(typeof i))throw new TypeError("HTTP header values must be scalar");t[n]=String(i)}return t}function Jt(){return Object.assign(Object.create(null),{Accept:"application/json"})}function Kt(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let r=new URL(String(e),String(t));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${r.protocol}`);return r.toString()}function Yt(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var Te=new Map,Ue=new WeakMap,Ve=1;function le(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=Ue.get(e);return t||(t=Ve,Ve+=1,Ue.set(e,t)),`reference:${t}`}var Xt=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),Zt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function ze(e){if(!e||typeof e!="object"||Array.isArray(e)||!Object.hasOwn(e,"jsonrpc")||!Object.hasOwn(e,"method")||e.jsonrpc!=="2.0")return!1;let t=typeof e.method=="string"?e.method:"";return t?Xt.has(t)||/^get[A-Z0-9_]/u.test(t)||/^is[A-Z0-9_]/u.test(t)||/^eth_get[A-Z0-9_]/u.test(t):!1}function Je(e,t){if(e==="GET"&&t==null)return!0;if(e!=="POST"||t==null)return!1;let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{return!1}if(Array.isArray(r))return r.length>0&&r.every(ze);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return ze(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&Zt.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Qt(e,t,r,n={},o=null){let a=Mt("sha256"),i=(u,f)=>{let s=String(f);a.update(String(Buffer.byteLength(u,"utf8"))).update(":").update(u),a.update("=").update(String(Buffer.byteLength(s,"utf8"))).update(":").update(s).update(`
2
- `)};i("method",e),i("url",t),Object.keys(r||{}).map((u,f)=>({name:u.toLowerCase(),order:f,value:String(r[u])})).sort((u,f)=>u.name.localeCompare(f.name)||u.order-f.order).forEach((u,f)=>{i(`header-name-${f}`,u.name),i(`header-value-${f}`,u.value)}),i("body",o??"-");for(let u of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])i(`context-${u}`,n[u]??"-");return a.digest("hex")}function er(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Ge):Math.min(250*2**e,Ge)+Math.floor(Math.random()*100)}var tr=e=>new Promise(t=>setTimeout(t,e));function D(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Ie(e,t,r){return D(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function U(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function rr(e){return e?e.byteLength??e.length??0:0}async function nr(e,t,{url:r,truncate:n=!1,onOversize:o}={}){if(t==null)return await e.text();let a=Number(e.headers?.get?.("content-length"));if(Number.isFinite(a)&&a>t&&(U(e),!n))throw Ie(r,`content-length ${a}`,t);let i=e.body?.getReader?.();if(!i){let l=await e.text(),d=Buffer.byteLength(l,"utf8");if(d>t){if(!n)throw Ie(r,`body ${d} bytes`,t);return Buffer.from(l,"utf8").subarray(0,t).toString("utf8")}return l}let c=[],u=0,f=!1;try{for(;;){let{value:l,done:d}=await i.read();if(d)break;if(l&&(c.push(Buffer.from(l)),u+=rr(l),u>t)){f=!0;break}}}finally{if(f)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(f&&(typeof o=="function"&&o(),!n))throw Ie(r,`streamed ${u} bytes`,t);let s=Buffer.concat(c);return(f?s.subarray(0,t):s).toString("utf8")}function or(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function ar(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:a,lookupFn:i,realFetch:c,untrustedUrl:u=!1,maxResponseBytes:f=null,sameOriginRedirectsOnly:s=!1,importUndici:l,validateResponse:d,signal:m,redirectPolicy:h="follow",maxRedirects:p=fe}){let g=null,b=t,T=i?{lookupFn:i}:{};if(u&&!c&&!Ae(b))throw D(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let y=new AbortController,_=setTimeout(()=>y.abort(),a),C=m?We?We([m,y.signal]):m:y.signal,H=async(x,{status:O=null}={})=>{let R=await Ee(x,T);if(!R.ok)throw D(O==null?`HTTP refused ${x}: ${R.error}`:`HTTP redirect to ${x} ${R.error}`,O==null?{}:{status:O});let j=new URL(x).hostname;if(c){if(g&&(await g.close(),g=null),!g)try{g=await Se({requireUndici:!0,...l?{importUndici:l}:{}})}catch(w){throw D(O==null?`HTTP refused ${x}: ${w?.message||w}`:`HTTP redirect to ${x} refused: ${w?.message||w}`,O==null?{}:{status:O})}g.pin(j,R.addresses),b=g.fetch}else De(b,j,R.addresses);return R};try{let x=String(e),O=Object.assign(Object.create(null),n||{});u&&await H(x);for(let R=0;R<=p;R+=1){let j=Object.assign(Object.create(null),{method:r,headers:O,body:o,signal:C,redirect:"manual",dispatcher:void 0}),w=await b(x,j);if((h==="error"||p===0)&&w.status>=300&&w.status<400)throw U(w),D(`HTTP ${w.status} ${r} redirect refused`,{status:w.status,redirectRefused:!0});if(Wt.has(w.status)){let N=s===!0&&r==="POST"&&[307,308].includes(w.status)&&Je(r,o);if(r!=="GET"&&r!=="HEAD"&&!N){U(w);let I=new Error(`HTTP ${w.status} ${r} ${x} redirected non-idempotent request`);throw I.status=w.status,I}if(R===p)throw U(w),D(`HTTP ${w.status} ${r} redirect budget exhausted`,{status:w.status,redirectRefused:!0});let Fe=w.headers?.get?.("location"),$;try{$=Kt(Fe,x)}catch(I){throw U(w),I}let G=!Yt($,x);if(U(w),G&&r==="POST"){let I=new Error(`HTTP ${w.status} ${r} cross-origin redirect refused`);throw I.status=w.status,I}if(G&&s){let I=new Error(`HTTP ${w.status} ${r} cross-origin redirect refused`);throw I.status=w.status,I.retryable=!1,I}if(G&&(O=Jt(O)),u)await H($,{status:w.status});else if(G){let I=await Ee($,T);if(!I.ok){let S=new Error(`HTTP redirect from ${x} ${I.error}`);throw S.status=w.status,S.retryable=!1,S}c&&I.addresses?.length&&(g||(g=await Se(l?{importUndici:l}:{})),g&&(g.pin(new URL($).hostname,I.addresses),b=g.fetch))}x=$;continue}if(typeof d=="function")try{await d(w,{url:x})}catch(N){throw U(w),D(N?.message||String(N))}let P=await nr(w,f,{url:x,onOversize:()=>y.abort()}),re=or(P);if(!w.ok){let N=new Error(`HTTP ${w.status} ${r} ${x}`);throw N.status=w.status,N.retryAfter=w.headers?.get?.("retry-after")??null,N.body=re??P.slice(0,300),N}return re??P}throw new Error(`HTTP redirect loop for ${e}`)}catch(x){if(y.signal.aborted&&!ae(m)){let O=x&&(typeof x=="object"||typeof x=="function")&&!F.isProxy(x)?x:null,R=O?Object.getOwnPropertyDescriptor(O,"oversize"):null;if(!(R&&Object.hasOwn(R,"value")&&R.value===!0))try{if(!O)throw new TypeError("unsafe rejection");Object.defineProperties(O,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let w=new Error("HTTP request timed out");throw Object.defineProperties(w,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),w}}throw x}finally{clearTimeout(_),g&&await g.close()}}async function Ke(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&F.isProxy(t))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(t!=null){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP options contain unknown fields");for(let S of Object.getOwnPropertyNames(t)){let E=Object.getOwnPropertyDescriptor(t,S);if(!(S==="toJSON"&&E&&Object.hasOwn(E,"value")&&E.value===void 0)){if(!r.has(S))throw new TypeError("HTTP options contain unknown fields");if(!E||!E.enumerable||!Object.hasOwn(E,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=S=>{if(t==null||!Object.hasOwn(t,S))return;let E=Object.getOwnPropertyDescriptor(t,S);if(!E||!Object.hasOwn(E,"value"))throw new TypeError("HTTP options must contain own data properties");return E.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let o=n("method");if(o!==void 0&&(typeof o!="string"||!/^[A-Za-z]+$/u.test(o)))throw new TypeError("HTTP method must be a string token");let a=n("timeoutMs");if(a!==void 0&&(!Number.isInteger(a)||a<1||a>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let i=n("retries");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>10))throw new TypeError("HTTP retries must be a bounded integer");let c=n("redirectPolicy");if(c!==void 0&&c!=="follow"&&c!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let u=n("maxRedirects");if(u!==void 0&&(!Number.isInteger(u)||u<0||u>fe))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${fe}`);if(c==="error"&&u!==void 0&&u!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let f=c??"follow",s=f==="error"?0:u??fe;for(let S of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let E=n(S);if(E!==void 0&&typeof E!="boolean")throw new TypeError(`HTTP ${S} must be boolean`)}let l=n("maxResponseBytes");if(l!==void 0&&(!Number.isInteger(l)||l<1||l>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let d=n("signal");if(d!==void 0){if(F.isProxy(d)||!(d instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{ae(d)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let S of["importUndici","lookupFn","validateResponse"]){let E=n(S);if(E!==void 0&&typeof E!="function")throw new TypeError(`HTTP ${S} must be a function`)}let m=n("fetchImpl"),h=m||globalThis.fetch;if(typeof h!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let p=a??12e3,g=(o||"GET").toUpperCase(),b=n("headers"),T=zt(b),y=Object.assign(Object.create(null),T);Object.keys(y).some(S=>S.toLowerCase()==="accept")||(y.Accept="application/json");let _=n("body");_!=null&&typeof _!="string"&&(Object.keys(y).find(E=>E.toLowerCase()==="content-type")||(y["Content-Type"]="application/json"),_=Vt(_));let C=i??Bt,H=n("lookupFn"),x=!m,O=n("untrustedUrl")===!0,R=n("sameOriginRedirectsOnly")===!0,j=n("importUndici"),w=n("validateResponse"),P=d,re=l??null,N=async()=>{let S;for(let E=0;E<=C;E++){P&&Ht.call(P);try{return await ar(e,{fetchImpl:h,method:g,headers:y,body:_,timeoutMs:p,lookupFn:H,realFetch:x,untrustedUrl:O,maxResponseBytes:re,sameOriginRedirectsOnly:R,importUndici:j,validateResponse:w,signal:P,redirectPolicy:f,maxRedirects:s})}catch(q){S=q;let Y=be=>{if(!q||typeof q!="object"&&typeof q!="function"||F.isProxy(q))return;let ne=Object.getOwnPropertyDescriptor(q,be);return ne&&Object.hasOwn(ne,"value")?ne.value:void 0},we=Y("status"),Pt=Y("oracleTimeout")===!0||Y("name")==="AbortError"||Y("name")==="TimeoutError"||ae(P),_t=new Set([408,425,429]),Nt=Y("retryable")===!1?!1:we!=null?_t.has(we)||Ft.has(we)&&He.has(g):!Pt&&He.has(g);if(E===C||!Nt)throw q;let Be=er(E,Y("retryAfter"));P?await new Promise((be,ne)=>{let je,oe=()=>{clearTimeout(je),qe.call(P,"abort",oe),ne(qt(P)||new DOMException("Aborted","AbortError"))};if(ae(P)){oe();return}je=setTimeout(()=>{qe.call(P,"abort",oe),be()},Be),Gt.call(P,"abort",oe,{once:!0}),ae(P)&&oe()}):await tr(Be)}}throw S};if(!(n("dedupe")!==!1&&!P&&Je(g,_)))return N();let $=Qt(g,e,y,{untrustedUrl:O,maxResponseBytes:re,sameOriginRedirectsOnly:R,redirectPolicy:f,maxRedirects:s,timeoutMs:p,retries:C,fetchImpl:le(h),realFetch:x,lookupFn:le(H),importUndici:le(j),validateResponse:le(w)},_),G=Te.get($);if(G)return G;let I=N().finally(()=>Te.delete($));return Te.set($,I),I}var Ye={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}},ir=new Map(Object.values(Ye).map(e=>[e.chainId,e]));function Xe(e){return ir.get(Number(e))||null}function Ze(e,t=process.env){let r=Xe(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}import{Interface as sr,getAddress as eo}from"ethers";var to=new sr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var cr={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};function ur(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Ze(e,r);return n||cr[Number(e)]||null}var lr=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function fr(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!lr.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var ie=new Map,Qe=new Map;function dr(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function pr(e){if(e?.error)throw dr(e.error);return e?.result}function mr(e,t,r){return`${e}
1
+ import{createHash as Wt}from"node:crypto";import{types as B}from"node:util";import{AsyncLocalStorage as Mt}from"node:async_hooks";var Ft=new Mt,Bt=["http","retry","shared"],jt=512;function le(e){let t=Ft.getStore();if(!t||t.closed||!Bt.includes(e))return null;if(t.spans.length>=jt)return t.droppedSpans++,null;let r={stage:e,startMs:t.now()-t.start,durationMs:null,outcome:"pending",status:null};return t.spans.push(r),(n,o=null)=>{t.closed||r.durationMs!==null||(r.durationMs=Math.max(0,t.now()-t.start-r.startMs),r.outcome=n==="succeeded"?"succeeded":"failed",r.status=Number.isInteger(o)&&o>=100&&o<=599?o:null)}}import W from"node:net";import Dt from"node:dns";var Gt=new Set(["localhost","metadata.google.internal","metadata.goog"]);function fe(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=s=>{if(!s)return[];let l=s.split(":"),d=l.at(-1);if(d?.includes(".")){let m=d.split(".").map(Number);if(m.length!==4||m.some(h=>!Number.isInteger(h)||h<0||h>255))return null;l.splice(l.length-1,1,(m[0]<<8|m[1]).toString(16),(m[2]<<8|m[3]).toString(16))}return l.some(m=>!/^[0-9a-f]{1,4}$/.test(m))?null:l.map(m=>Number.parseInt(m,16))},[n,o]=t.split("::"),a=r(n),i=r(o);if(!a||!i)return null;let c=t.includes("::"),u=8-a.length-i.length;if(!c&&u!==0||c&&u<1)return null;let f=[...a,...Array(Math.max(0,u)).fill(0),...i];return f.length!==8?null:Uint8Array.from(f.flatMap(s=>[s>>8,s&255]))}function xe(e,t,r){let n=Math.floor(r/8),o=r%8;for(let i=0;i<n;i+=1)if(e[i]!==t[i])return!1;if(!o)return!0;let a=255<<8-o;return(e[n]&a)===(t[n]&a)}function Ee(e){if(W.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(W.isIPv6(e)){let t=fe(e);if(!t)return!1;let r=fe("::ffff:0:0");return xe(t,r,96)?Ee([...t.slice(12)].join(".")):xe(t,fe("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,a])=>xe(t,fe(o),a)):!1}return!1}function Ht(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Gt.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=W.isIP(r);return n!==0&&!Ee(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function Se(e,{lookupFn:t=Dt.promises.lookup}={}){let r=Ht(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:W.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(o=>!Ee(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function ve({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let l=await t();r=l.Agent,n=l.fetch}catch(l){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${l?.message||l}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let o=l=>String(l).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),a=new Map,i=l=>(Array.isArray(l)?l:[l]).map(d=>typeof d=="string"?{address:d}:d).filter(d=>d&&d.address).map(d=>({address:d.address,family:d.family||(W.isIPv6(d.address)?6:4)})),c=(l,d,m)=>{a.set(o(l),i(typeof d=="string"?[{address:d,family:m}]:d))},u=l=>{let d=o(l);if(W.isIP(d))return[{address:d,family:W.isIPv6(d)?6:4}];let m=a.get(d);if(!m||!m.length)throw new Error(`refused: unpinned host ${l} during pinned fetch`);return m},f=new r({connect:{lookup(l,d,m){let h;try{h=u(l)}catch(p){return m(p)}return d?.all?m(null,h):m(null,h[0].address,h[0].family)}}}),s=qt((l,d={})=>n(l,{...d,dispatcher:f}),c);return{dispatcher:f,fetch:s,pin:c,resolve:u,async close(){try{await f.destroy()}catch{}}}}var Ae=Symbol.for("oracle.egressGuard.pinCapableFetch");function qt(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[Ae]=Object.freeze({pin:t}),e}function Te(e){return typeof e=="function"&&typeof e[Ae]?.pin=="function"}function qe(e,t,r){if(!Te(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[Ae].pin(t,r)}var Ut=new Set([408,425,429,500,502,503,504]),We=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Vt=2,Ue=4e3,zt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Jt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Kt=AbortSignal.prototype.throwIfAborted,Yt=EventTarget.prototype.addEventListener,Ve=EventTarget.prototype.removeEventListener,ze=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,ae=e=>e?zt.call(e):!1,Xt=e=>e?Jt.call(e):void 0,Zt=new Set([301,302,303,307,308]),pe=3,oo=64*1024,F=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function A(e){return G(`HTTP JSON body refused: ${e}`)}function Qt(e){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(t=>typeof B[t]=="function"&&B[t](e))}function er(e){let t=[],r=0,n=0,o=0,a=0,i=new WeakSet,c=s=>{if(r+=Buffer.byteLength(s,"utf8"),r>F.bytes)throw A("serialized byte limit exceeded");t.push(s)},u=s=>{if(Buffer.byteLength(s,"utf8")>F.bytes)throw A("serialized byte limit exceeded");return JSON.stringify(s)},f=(s,l)=>{if(n+=1,n>F.nodes)throw A("node limit exceeded");if(l>F.depth)throw A("depth limit exceeded");if(s===null){c("null");return}if(typeof s=="string"){c(u(s));return}if(typeof s=="boolean"){c(s?"true":"false");return}if(typeof s=="number"){if(!Number.isFinite(s))throw A("non-finite number");c(Object.is(s,-0)?"0":String(s));return}if(typeof s!="object")throw A("unsupported non-JSON value");if(B.isProxy(s))throw A("proxy value");if(Qt(s))throw A("unsupported exotic object");if(i.has(s))throw A("cyclic value");i.add(s);try{if(Object.getOwnPropertySymbols(s).length>0)throw A("symbol-keyed fields are unsupported");if(Array.isArray(s)){let h=Object.getPrototypeOf(s),p=0;for(;h!==null;){if(B.isProxy(h))throw A("proxy array prototype");if(p+=1,p>F.depth)throw A("array prototype depth limit exceeded");h=Object.getPrototypeOf(h)}if(s.length>F.arrayLength)throw A("array length limit exceeded");for(let b=0;b<s.length;b+=1){let T=Object.getOwnPropertyDescriptor(s,String(b));if(!T||!Object.hasOwn(T,"value")||T.enumerable!==!0)throw A("array entries must be dense enumerable own data")}let g=0;for(let b in s){if(a+=1,a>F.fields)throw A("enumeration limit exceeded");if(Object.hasOwn(s,b)&&(g+=1,g>s.length))throw A("named array fields are unsupported")}if(g!==s.length)throw A("array entries must be dense enumerable own data");c("[");for(let b=0;b<s.length;b+=1)b&&c(","),f(Object.getOwnPropertyDescriptor(s,String(b)).value,l+1);c("]");return}let d=Object.getPrototypeOf(s);if(d!==Object.prototype&&d!==null)throw A("non-plain object");let m=[];for(let h in s){if(a+=1,a>F.fields)throw A("enumeration limit exceeded");if(!Object.hasOwn(s,h))continue;if(o+=1,o>F.fields)throw A("field limit exceeded");let p=Object.getOwnPropertyDescriptor(s,h);if(!p||!Object.hasOwn(p,"value")||p.enumerable!==!0)throw A("object fields must be enumerable own data");m.push([h,p.value])}c("{");for(let h=0;h<m.length;h+=1)h&&c(","),c(u(m[h][0])),c(":"),f(m[h][1],l+1);c("}")}finally{i.delete(s)}};return f(e,0),t.join("")}function tr(e){let t=Object.create(null);if(e==null)return t;if(typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP headers must be an object");if(B.isProxy(e))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(e)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let o=n.toLowerCase();if(r.has(o))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(o);let a=Object.getOwnPropertyDescriptor(e,n);if(!a||!Object.hasOwn(a,"value"))throw new TypeError("HTTP headers must contain own data properties");let i=a.value;if(i==null||["object","function","symbol"].includes(typeof i))throw new TypeError("HTTP header values must be scalar");t[n]=String(i)}return t}function rr(){return Object.assign(Object.create(null),{Accept:"application/json"})}function nr(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let r=new URL(String(e),String(t));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${r.protocol}`);return r.toString()}function or(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var Ie=new Map,Je=new WeakMap,Ke=1;function de(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=Je.get(e);return t||(t=Ke,Ke+=1,Je.set(e,t)),`reference:${t}`}var ar=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),ir=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function Ye(e){if(!e||typeof e!="object"||Array.isArray(e)||!Object.hasOwn(e,"jsonrpc")||!Object.hasOwn(e,"method")||e.jsonrpc!=="2.0")return!1;let t=typeof e.method=="string"?e.method:"";return t?ar.has(t)||/^get[A-Z0-9_]/u.test(t)||/^is[A-Z0-9_]/u.test(t)||/^eth_get[A-Z0-9_]/u.test(t):!1}function Xe(e,t){if(e==="GET"&&t==null)return!0;if(e!=="POST"||t==null)return!1;let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{return!1}if(Array.isArray(r))return r.length>0&&r.every(Ye);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Ye(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&ir.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function sr(e,t,r,n={},o=null){let a=Wt("sha256"),i=(u,f)=>{let s=String(f);a.update(String(Buffer.byteLength(u,"utf8"))).update(":").update(u),a.update("=").update(String(Buffer.byteLength(s,"utf8"))).update(":").update(s).update(`
2
+ `)};i("method",e),i("url",t),Object.keys(r||{}).map((u,f)=>({name:u.toLowerCase(),order:f,value:String(r[u])})).sort((u,f)=>u.name.localeCompare(f.name)||u.order-f.order).forEach((u,f)=>{i(`header-name-${f}`,u.name),i(`header-value-${f}`,u.value)}),i("body",o??"-");for(let u of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])i(`context-${u}`,n[u]??"-");return a.digest("hex")}function cr(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Ue):Math.min(250*2**e,Ue)+Math.floor(Math.random()*100)}var ur=e=>new Promise(t=>setTimeout(t,e));function G(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Oe(e,t,r){return G(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function U(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function lr(e){return e?e.byteLength??e.length??0:0}async function fr(e,t,{url:r,truncate:n=!1,onOversize:o}={}){if(t==null)return await e.text();let a=Number(e.headers?.get?.("content-length"));if(Number.isFinite(a)&&a>t&&(U(e),!n))throw Oe(r,`content-length ${a}`,t);let i=e.body?.getReader?.();if(!i){let l=await e.text(),d=Buffer.byteLength(l,"utf8");if(d>t){if(!n)throw Oe(r,`body ${d} bytes`,t);return Buffer.from(l,"utf8").subarray(0,t).toString("utf8")}return l}let c=[],u=0,f=!1;try{for(;;){let{value:l,done:d}=await i.read();if(d)break;if(l&&(c.push(Buffer.from(l)),u+=lr(l),u>t)){f=!0;break}}}finally{if(f)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(f&&(typeof o=="function"&&o(),!n))throw Oe(r,`streamed ${u} bytes`,t);let s=Buffer.concat(c);return(f?s.subarray(0,t):s).toString("utf8")}function dr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function pr(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:a,lookupFn:i,realFetch:c,untrustedUrl:u=!1,maxResponseBytes:f=null,sameOriginRedirectsOnly:s=!1,importUndici:l,validateResponse:d,signal:m,redirectPolicy:h="follow",maxRedirects:p=pe}){let g=null,b=t,T=i?{lookupFn:i}:{};if(u&&!c&&!Te(b))throw G(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let y=new AbortController,_=setTimeout(()=>y.abort(),a),C=m?ze?ze([m,y.signal]):m:y.signal,H=async(x,{status:O=null}={})=>{let R=await Se(x,T);if(!R.ok)throw G(O==null?`HTTP refused ${x}: ${R.error}`:`HTTP redirect to ${x} ${R.error}`,O==null?{}:{status:O});let D=new URL(x).hostname;if(c){if(g&&(await g.close(),g=null),!g)try{g=await ve({requireUndici:!0,...l?{importUndici:l}:{}})}catch(w){throw G(O==null?`HTTP refused ${x}: ${w?.message||w}`:`HTTP redirect to ${x} refused: ${w?.message||w}`,O==null?{}:{status:O})}g.pin(D,R.addresses),b=g.fetch}else qe(b,D,R.addresses);return R};try{let x=String(e),O=Object.assign(Object.create(null),n||{});u&&await H(x);for(let R=0;R<=p;R+=1){let D=Object.assign(Object.create(null),{method:r,headers:O,body:o,signal:C,redirect:"manual",dispatcher:void 0}),w=await b(x,D);if((h==="error"||p===0)&&w.status>=300&&w.status<400)throw U(w),G(`HTTP ${w.status} ${r} redirect refused`,{status:w.status,redirectRefused:!0});if(Zt.has(w.status)){let N=s===!0&&r==="POST"&&[307,308].includes(w.status)&&Xe(r,o);if(r!=="GET"&&r!=="HEAD"&&!N){U(w);let I=new Error(`HTTP ${w.status} ${r} ${x} redirected non-idempotent request`);throw I.status=w.status,I}if(R===p)throw U(w),G(`HTTP ${w.status} ${r} redirect budget exhausted`,{status:w.status,redirectRefused:!0});let Be=w.headers?.get?.("location"),$;try{$=nr(Be,x)}catch(I){throw U(w),I}let q=!or($,x);if(U(w),q&&r==="POST"){let I=new Error(`HTTP ${w.status} ${r} cross-origin redirect refused`);throw I.status=w.status,I}if(q&&s){let I=new Error(`HTTP ${w.status} ${r} cross-origin redirect refused`);throw I.status=w.status,I.retryable=!1,I}if(q&&(O=rr(O)),u)await H($,{status:w.status});else if(q){let I=await Se($,T);if(!I.ok){let S=new Error(`HTTP redirect from ${x} ${I.error}`);throw S.status=w.status,S.retryable=!1,S}c&&I.addresses?.length&&(g||(g=await ve(l?{importUndici:l}:{})),g&&(g.pin(new URL($).hostname,I.addresses),b=g.fetch))}x=$;continue}if(typeof d=="function")try{await d(w,{url:x})}catch(N){throw U(w),G(N?.message||String(N))}let P=await fr(w,f,{url:x,onOversize:()=>y.abort()}),re=dr(P);if(!w.ok){let N=new Error(`HTTP ${w.status} ${r} ${x}`);throw N.status=w.status,N.retryAfter=w.headers?.get?.("retry-after")??null,N.body=re??P.slice(0,300),N}return re??P}throw new Error(`HTTP redirect loop for ${e}`)}catch(x){if(y.signal.aborted&&!ae(m)){let O=x&&(typeof x=="object"||typeof x=="function")&&!B.isProxy(x)?x:null,R=O?Object.getOwnPropertyDescriptor(O,"oversize"):null;if(!(R&&Object.hasOwn(R,"value")&&R.value===!0))try{if(!O)throw new TypeError("unsafe rejection");Object.defineProperties(O,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let w=new Error("HTTP request timed out");throw Object.defineProperties(w,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),w}}throw x}finally{clearTimeout(_),g&&await g.close()}}async function Ze(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&B.isProxy(t))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(t!=null){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP options contain unknown fields");for(let S of Object.getOwnPropertyNames(t)){let E=Object.getOwnPropertyDescriptor(t,S);if(!(S==="toJSON"&&E&&Object.hasOwn(E,"value")&&E.value===void 0)){if(!r.has(S))throw new TypeError("HTTP options contain unknown fields");if(!E||!E.enumerable||!Object.hasOwn(E,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=S=>{if(t==null||!Object.hasOwn(t,S))return;let E=Object.getOwnPropertyDescriptor(t,S);if(!E||!Object.hasOwn(E,"value"))throw new TypeError("HTTP options must contain own data properties");return E.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let o=n("method");if(o!==void 0&&(typeof o!="string"||!/^[A-Za-z]+$/u.test(o)))throw new TypeError("HTTP method must be a string token");let a=n("timeoutMs");if(a!==void 0&&(!Number.isInteger(a)||a<1||a>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let i=n("retries");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>10))throw new TypeError("HTTP retries must be a bounded integer");let c=n("redirectPolicy");if(c!==void 0&&c!=="follow"&&c!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let u=n("maxRedirects");if(u!==void 0&&(!Number.isInteger(u)||u<0||u>pe))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${pe}`);if(c==="error"&&u!==void 0&&u!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let f=c??"follow",s=f==="error"?0:u??pe;for(let S of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let E=n(S);if(E!==void 0&&typeof E!="boolean")throw new TypeError(`HTTP ${S} must be boolean`)}let l=n("maxResponseBytes");if(l!==void 0&&(!Number.isInteger(l)||l<1||l>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let d=n("signal");if(d!==void 0){if(B.isProxy(d)||!(d instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{ae(d)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let S of["importUndici","lookupFn","validateResponse"]){let E=n(S);if(E!==void 0&&typeof E!="function")throw new TypeError(`HTTP ${S} must be a function`)}let m=n("fetchImpl"),h=m||globalThis.fetch;if(typeof h!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let p=a??12e3,g=(o||"GET").toUpperCase(),b=n("headers"),T=tr(b),y=Object.assign(Object.create(null),T);Object.keys(y).some(S=>S.toLowerCase()==="accept")||(y.Accept="application/json");let _=n("body");_!=null&&typeof _!="string"&&(Object.keys(y).find(E=>E.toLowerCase()==="content-type")||(y["Content-Type"]="application/json"),_=er(_));let C=i??Vt,H=n("lookupFn"),x=!m,O=n("untrustedUrl")===!0,R=n("sameOriginRedirectsOnly")===!0,D=n("importUndici"),w=n("validateResponse"),P=d,re=l??null,N=async()=>{let S;for(let E=0;E<=C;E++){P&&Kt.call(P);let je=le("http");try{let M=await pr(e,{fetchImpl:h,method:g,headers:y,body:_,timeoutMs:p,lookupFn:H,realFetch:x,untrustedUrl:O,maxResponseBytes:re,sameOriginRedirectsOnly:R,importUndici:D,validateResponse:w,signal:P,redirectPolicy:f,maxRedirects:s});return je?.("succeeded"),M}catch(M){S=M;let Y=ye=>{if(!M||typeof M!="object"&&typeof M!="function"||B.isProxy(M))return;let ne=Object.getOwnPropertyDescriptor(M,ye);return ne&&Object.hasOwn(ne,"value")?ne.value:void 0},ue=Y("status");je?.("failed",ue);let kt=Y("oracleTimeout")===!0||Y("name")==="AbortError"||Y("name")==="TimeoutError"||ae(P),Ct=new Set([408,425,429]),$t=Y("retryable")===!1?!1:ue!=null?Ct.has(ue)||Ut.has(ue)&&We.has(g):!kt&&We.has(g);if(E===C||!$t)throw M;let De=cr(E,Y("retryAfter")),Lt=le("retry"),Ge=!1;try{P?await new Promise((ye,ne)=>{let He,oe=()=>{clearTimeout(He),Ve.call(P,"abort",oe),ne(Xt(P)||new DOMException("Aborted","AbortError"))};if(ae(P)){oe();return}He=setTimeout(()=>{Ve.call(P,"abort",oe),ye()},De),Yt.call(P,"abort",oe,{once:!0}),ae(P)&&oe()}):await ur(De),Ge=!0}finally{Lt?.(Ge?"succeeded":"failed")}}}throw S};if(!(n("dedupe")!==!1&&!P&&Xe(g,_)))return N();let $=sr(g,e,y,{untrustedUrl:O,maxResponseBytes:re,sameOriginRedirectsOnly:R,redirectPolicy:f,maxRedirects:s,timeoutMs:p,retries:C,fetchImpl:de(h),realFetch:x,lookupFn:de(H),importUndici:de(D),validateResponse:de(w)},_),q=Ie.get($);if(q){let S=le("shared");try{let E=await q;return S?.("succeeded"),E}catch(E){throw S?.("failed"),E}}let I=N().finally(()=>Ie.delete($));return Ie.set($,I),I}var Qe={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}},mr=new Map(Object.values(Qe).map(e=>[e.chainId,e]));function et(e){return mr.get(Number(e))||null}function tt(e,t=process.env){let r=et(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}import{Interface as hr,getAddress as fo}from"ethers";var po=new hr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var gr={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};function wr(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=tt(e,r);return n||gr[Number(e)]||null}var br=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function yr(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!br.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var ie=new Map,rt=new Map;function xr(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function Er(e){if(e?.error)throw xr(e.error);return e?.result}function Sr(e,t,r){return`${e}
3
3
  ${t}
4
- ${JSON.stringify(r??[])}`}async function hr(e,t,r){return Ke(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function k(e,t,r=[],n={}){let o=String(t||""),a=fr(o),i=ur(e,n);if(!i)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);if(a==="eth_chainid"&&n.cacheChainId!==!1){let s=Qe.get(i);if(s!=null)return s}let u=n.dedupe!==!1&&!n.signal?mr(i,o,r):null;if(u&&ie.has(u))return ie.get(u);let f=(async()=>{let s=await hr(i,{jsonrpc:"2.0",id:1,method:t,params:r},n),l=pr(s);return a==="eth_chainid"&&typeof l=="string"&&Qe.set(i,l),l})();return u&&(ie.set(u,f),f.finally(()=>{ie.get(u)===f&&ie.delete(u)}).catch(()=>{})),f}var gr=/^(0|[1-9][0-9]*)$/;function V(e,t,{required:r=!0,allowZero:n=!1}={}){if(e==null||e===""){if(r)throw new Error(`${t} required`);return null}let o;if(typeof e=="bigint")o=e;else if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error(`${t} must be a safe integer`);o=BigInt(e)}else if(typeof e=="string"){let a=e.trim();if(a.startsWith("0x")||a.startsWith("0X"))o=BigInt(a);else{if(!gr.test(a))throw new Error(`${t} must be an integer wei string`);o=BigInt(a)}}else throw new Error(`${t} must be bigint, number, or integer string`);if(o<0n||!n&&o===0n)throw new Error(`${t} must be ${n?"non-negative":"positive"}`);return o}function wr(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new Error("chainId must be a positive integer");return t}function br(e={}){return e.maxFeePerGas!=null?V(e.maxFeePerGas,"maxFeePerGas"):e.gasPrice!=null?V(e.gasPrice,"gasPrice"):null}function et(e={}){try{let t=wr(e.chainId??e.tx?.chainId),r=e.tx||e,n=e.policy||e,o=n.grant?.maxGasWei??e.grant?.maxGasWei,a=V(n.maxTotalGasWei??n.maxGasWei??o,"maxTotalGasWei"),i=V(r.gasLimit??r.gas,"gasLimit"),c=br(r);if(c==null)throw new Error("maxFeePerGas or gasPrice required");let u=V(n.maxFeePerGasWei,"maxFeePerGasWei",{required:!1}),f=V(n.maxPriorityFeePerGasWei,"maxPriorityFeePerGasWei",{required:!1}),s=r.maxPriorityFeePerGas==null?null:V(r.maxPriorityFeePerGas,"maxPriorityFeePerGas"),l=i*c;return l>a?{ok:!1,status:"BLOCK",reason:`total gas ${l} exceeds cap ${a}`,chainId:t,totalGasWei:l.toString(),maxTotalGasWei:a.toString()}:u!=null&&c>u?{ok:!1,status:"BLOCK",reason:`unit fee ${c} exceeds cap ${u}`,chainId:t,unitFeeWei:c.toString(),maxFeePerGasWei:u.toString(),totalGasWei:l.toString(),maxTotalGasWei:a.toString()}:s!=null&&f!=null&&s>f?{ok:!1,status:"BLOCK",reason:`priority fee ${s} exceeds cap ${f}`,chainId:t,priorityFeeWei:s.toString(),maxPriorityFeePerGasWei:f.toString(),totalGasWei:l.toString(),maxTotalGasWei:a.toString()}:{ok:!0,status:"PASS",reason:"gas envelope within NFT mint gas-war caps",chainId:t,totalGasWei:l.toString(),maxTotalGasWei:a.toString(),unitFeeWei:c.toString(),maxFeePerGasWei:u?.toString()??null,priorityFeeWei:s?.toString()??null,maxPriorityFeePerGasWei:f?.toString()??null}}catch(t){return{ok:!1,status:"BLOCK",reason:String(t?.message||t)}}}var yr=5,Oe=[50,75,90],tt=Object.freeze({normal:{percentile:0,baseFeeMultiplier:2n,label:"normal"},fast:{percentile:1,baseFeeMultiplier:3n,label:"fast"},war:{percentile:2,baseFeeMultiplier:4n,label:"war"}});function z(e,t){if(e==null)return null;try{if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isFinite(e)||e<0)throw new Error("bad number");return BigInt(Math.floor(e))}let r=String(e).trim();return r.startsWith("0x"),BigInt(r)}catch{throw new Error(`${t} must be a non-negative integer (wei)`)}}function xr(e){let t=e.filter(r=>r!=null).sort((r,n)=>r<n?-1:r>n?1:0);return t.length?t[Math.floor(t.length/2)]:null}async function rt(e={},t={}){let r=t.rpcCall||k,n=Number(e.chainId);if(!Number.isInteger(n))return{status:"error",error:"chainId is required",viable:!1};let o=tt[e.urgency||"fast"];if(!o)return{status:"error",viable:!1,error:`urgency must be one of: ${Object.keys(tt).join(", ")}`};let a,i,c,u;try{a=z(e.maxFeePerGasWei,"maxFeePerGasWei"),i=z(e.maxPriorityFeePerGasWei,"maxPriorityFeePerGasWei"),c=z(e.gasLimit,"gasLimit"),u=z(e.maxTotalGasWei,"maxTotalGasWei")}catch(x){return{status:"error",viable:!1,error:x.message}}let f,s;try{[f,s]=await Promise.all([r(n,"eth_feeHistory",[`0x${yr.toString(16)}`,"pending",Oe],t),r(n,"eth_getBlockByNumber",["pending",!1],t)])}catch(x){return{status:"unavailable",viable:!1,error:x?.message||"fee history unavailable",notes:["could not read live fee data; refusing to guess a competitive bid"]}}let l=z(s?.baseFeePerGas,"baseFeePerGas")??z(f?.baseFeePerGas?.[f.baseFeePerGas.length-1],"baseFeePerGas");if(l==null)return{status:"unavailable",viable:!1,error:"chain did not report a baseFeePerGas (pre-EIP-1559?)",notes:["this pricer is EIP-1559 only"]};let m=(Array.isArray(f?.reward)?f.reward:[]).map(x=>{try{return z(x?.[o.percentile],"reward")}catch{return null}}).filter(x=>x!=null&&x>0n),h=xr(m),p=[];h==null&&p.push("no non-zero tips observed in recent blocks; using a 1 gwei floor");let g=h??1000000000n,b=l*o.baseFeeMultiplier+g,T=[];i!=null&&g>i&&(T.push({field:"maxPriorityFeePerGas",wanted:g.toString(),capped:i.toString()}),g=i,b=l*o.baseFeeMultiplier+g),a!=null&&b>a&&(T.push({field:"maxFeePerGas",wanted:b.toString(),capped:a.toString()}),b=a,g>b&&(g=b));let y=c!=null?c*b:null;u!=null&&y!=null&&y>u&&T.push({field:"totalGas",wanted:y.toString(),capped:u.toString()});let _=h==null||g>=h,C=u==null||y==null||y<=u,H=_&&C;return _||p.push(`tip cap ${g} is below the observed ${Oe[o.percentile]}th-percentile tip ${h}; this bid is unlikely to land`),C||p.push(`worst-case gas ${y} exceeds the ${u} total cap`),p.push("maxFeePerGas is a ceiling \u2014 unused headroom above basefee+tip is refunded, not spent"),{status:"ok",viable:H,chainId:n,urgency:o.label,baseFeePerGas:l.toString(),observedTip:h==null?null:h.toString(),percentile:Oe[o.percentile],maxFeePerGas:b.toString(),maxPriorityFeePerGas:g.toString(),worstCaseGasWei:y==null?null:y.toString(),clamps:T,notes:p}}var Er=Object.freeze({"8da5cb5b":{name:"owner()",weight:"low",note:"contract has an owner"},f2fde38b:{name:"transferOwnership(address)",weight:"low",note:"ownership transferable"},"40c10f19":{name:"mint(address,uint256)",weight:"high",note:"owner can mint new supply"},a0712d68:{name:"mint(uint256)",weight:"high",note:"owner can mint new supply"},f9f92be4:{name:"blacklist(address)",weight:"high",note:"addresses can be blocked from selling"},e4997dc5:{name:"removeBlackList(address)",weight:"high",note:"blacklist machinery present"},"8456cb59":{name:"pause()",weight:"high",note:"transfers can be frozen"},"3f4ba83a":{name:"unpause()",weight:"high",note:"pausable transfers"},c0246668:{name:"setFee/excludeFromFee",weight:"high",note:"transfer fees can be changed"},"3659cfe6":{name:"upgradeTo(address)",weight:"high",note:"logic can be replaced entirely"},"4f1ef286":{name:"upgradeToAndCall(address,bytes)",weight:"high",note:"logic can be replaced entirely"}}),Sr=Object.freeze([{label:"eip1967",slot:"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"},{label:"zeppelinos",slot:"0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3"},{label:"eip1822",slot:"0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"}]),vr=`0x${"0".repeat(64)}`;function Ar(e){return!e||e==="0x"||e===vr}async function nt(e={},t={}){let r=t.rpcCall||k,n=String(e.address||"").trim().toLowerCase(),o=Number(e.chainId);if(!/^0x[a-f0-9]{40}$/.test(n))return{status:"error",error:"address must be a 0x-prefixed EVM address",risk:"unknown-risk",findings:[],notes:[]};if(!Number.isInteger(o))return{status:"error",error:"chainId is required",risk:"unknown-risk",findings:[],notes:[]};let a;try{a=await r(o,"eth_getCode",[n,"latest"],t)}catch(p){return{address:n,chainId:o,status:"unavailable",error:p?.message||"eth_getCode failed",risk:"unknown-risk",findings:[],isProxy:!1,codeSize:0,notes:["could not read contract code; treat as unverified"]}}if(!a||a==="0x")return{address:n,chainId:o,status:"ok",risk:"high",findings:[{selector:"-",name:"no-code",weight:"high",note:"no contract deployed at this address"}],isProxy:!1,codeSize:0,notes:["nothing is deployed here \u2014 an approval or transfer to this address is unrecoverable"]};let i=[],c=[],u=a.slice(2).toLowerCase();for(let[p,g]of Object.entries(Er))u.includes(p)&&c.push({selector:`0x${p}`,...g});let f=!1,s=null,l=null,d=await Promise.all(Sr.map(async({label:p,slot:g})=>{try{let b=await r(o,"eth_getStorageAt",[n,g,"latest"],t);return{label:p,word:b,error:null}}catch{return{label:p,word:null,error:`proxy slot (${p}) unreadable; proxy status uncertain`}}}));for(let p of d)p.error&&i.push(p.error),!f&&p.word&&!Ar(p.word)&&(f=!0,s=p.label,l=`0x${String(p.word).slice(-40)}`);f&&(c.push({selector:s,name:"proxy",weight:"high",note:"implementation is upgradeable \u2014 current behaviour is not a guarantee"}),i.push(`bytecode scan covers the proxy (${s}), not the implementation ${l} it delegates to`));let h=c.filter(p=>p.weight==="high").length>0?"high":c.length>0?"elevated":"unknown-risk";return h==="unknown-risk"&&i.push("no owner-power selectors found; this is weak evidence, not a safety guarantee"),{address:n,chainId:o,status:"ok",risk:h,findings:c,isProxy:f,proxyStandard:s,implementation:l,codeSize:Math.floor(u.length/2),notes:i}}var Tr="08c379a0",Ir="4e487b71",Or=Object.freeze({1:"assertion failed",17:"arithmetic overflow or underflow",18:"division or modulo by zero",33:"invalid enum value",34:"invalid storage byte array encoding",49:"pop() on an empty array",50:"array index out of bounds",65:"out of memory",81:"call to an uninitialized function pointer"});function Rr(e){if(!e||e==="0x")return{kind:"empty",reason:"reverted without a reason (often a require with no message, or out of gas)"};let t=String(e).slice(2),r=t.slice(0,8);if(r===Tr)try{let n=parseInt(t.slice(72,136),16),o=t.slice(136,136+n*2);return{kind:"revert",reason:Buffer.from(o,"hex").toString("utf8"),selector:`0x${r}`}}catch{return{kind:"revert",reason:"Error(string) payload could not be decoded",selector:`0x${r}`}}if(r===Ir){let n=parseInt(t.slice(8,72),16);return{kind:"panic",code:n,reason:Or[n]||`panic code 0x${n.toString(16)}`,selector:`0x${r}`}}return{kind:"custom",reason:`custom error ${`0x${r}`} (decoding needs the contract ABI)`,selector:`0x${r}`}}function Pr(e){let t=[e?.data,e?.error?.data,e?.data?.data,e?.cause?.data,e?.body?.error?.data];for(let o of t){if(typeof o=="string"&&o.startsWith("0x")&&o.length>2)return o;if(typeof o?.data=="string"&&o.data.startsWith("0x")&&o.data.length>2)return o.data}let n=String(e?.message||"").match(/0x[0-9a-fA-F]{72,}/);return n?n[0]:null}function _r(e,t){if(t)return!0;let r=String(e?.message||"").toLowerCase();return!!/execution reverted|revert|invalid opcode|out of gas|stack underflow|insufficient funds for/.test(r)}function Nr(e={}){let t={};return e.from&&(t.from=String(e.from).toLowerCase()),e.to&&(t.to=String(e.to).toLowerCase()),e.data&&e.data!=="0x"&&(t.data=e.data),e.value!=null&&String(e.value)!=="0"&&(t.value=`0x${BigInt(e.value).toString(16)}`),t}async function ot(e={},t={}){let r=t.rpcCall||k,n=Number(e.chainId),o=e.tx||{};if(!Number.isInteger(n))return{status:"error",willRevert:null,error:"chainId is required"};if(!o.to||!/^0x[a-fA-F0-9]{40}$/.test(String(o.to)))return{status:"error",willRevert:null,error:"tx.to must be a valid address"};if(o.from&&!/^0x[a-fA-F0-9]{40}$/.test(String(o.from)))return{status:"error",willRevert:null,error:"tx.from must be a valid address"};let a=Nr(o),i=[],c=null,u=!1,f=null;try{c=await r(n,"eth_call",[a,"pending"],t)}catch(h){let p=Pr(h);if(!_r(h,!!p))return{status:"unavailable",willRevert:null,chainId:n,error:h?.message||"simulation unavailable",notes:["could not reach the node; this is NOT evidence the transaction would fail"]};u=!0,f=Rr(p),p||(f.reason="execution reverted (node did not return a reason payload)",f.kind="revert-no-data")}if(u)return{status:"ok",willRevert:!0,chainId:n,revert:f,summary:`would REVERT: ${f.reason}`,notes:["simulated against current chain state; signing this now would burn gas and fail"]};let s=null,l=null;if(e.estimateGas!==!1)try{let h=await r(n,"eth_estimateGas",[a,"pending"],t);s=BigInt(h);let p=BigInt(Math.max(0,Math.floor(e.gasBufferPercent??20)));l=s+s*p/100n,i.push(`gasLimit includes a ${p}% buffer over the ${s} estimate`)}catch(h){i.push(`gas estimation failed: ${h?.message||"unknown"}`)}i.push("a pass reflects CURRENT chain state \u2014 it is not a guarantee the transaction lands, and in a contested mint the state changes between blocks");let d=`0x${"0".repeat(64)}`,m=c===d;return m&&i.push("call did not revert but returned boolean false \u2014 some ERC-20s (e.g. USDC) signal failure this way instead of reverting"),{status:"ok",willRevert:!1,returnsFalse:m,chainId:n,returnData:c,gasEstimate:s==null?null:s.toString(),gasLimit:l==null?null:l.toString(),summary:m?"executes but returns FALSE \u2014 the contract is rejecting this operation":s?`would succeed, ~${s} gas`:"would succeed",notes:i}}var kr=Object.freeze([{selector:"a0712d68",signature:"mint(uint256)",args:["quantity"]},{selector:"40c10f19",signature:"mint(address,uint256)",args:["to","quantity"]},{selector:"1249c58b",signature:"mint()",args:[]},{selector:"2db11544",signature:"publicMint(uint256)",args:["quantity"]},{selector:"efef39a1",signature:"purchase(uint256)",args:["quantity"]},{selector:"a6f2ae3a",signature:"buy()",args:[]}]);function Cr(e){let t=BigInt(e).toString(16);if(t.length>64)throw new Error("value too large for a 32-byte word");return t.padStart(64,"0")}function $r(e){let t=String(e).toLowerCase().replace(/^0x/,"");if(!/^[a-f0-9]{40}$/.test(t))throw new Error(`invalid address: ${e}`);return t.padStart(64,"0")}function at(e,{minter:t,quantity:r}){let n=`0x${e.selector}`;for(let o of e.args)if(o==="to")n+=$r(t);else if(o==="quantity")n+=Cr(r);else throw new Error(`unsupported mint argument: ${o}`);return n}function Lr({address:e,chainId:t,minter:r,quantity:n,tx:o,nowMs:a,ttlMs:i=3e4}){if(!o?.gasLimit||!o?.maxFeePerGas)throw new Error("local-signer envelope requires gasLimit and maxFeePerGas");let c=Number(a??Date.now()),u=String(o.value??"0");return{version:1,surface:"evm-nft",action:"mint",provider:"nft-mint",owner:r,destination:e,contract:e,quantity:String(n),totalWei:u,slippageBps:0,expiresAtMs:c+Math.min(Math.max(Number(i)||3e4,1e3),6e4),fee:{oracleFeeBps:0},artifact:{chainId:t,owner:r,contract:e,quantity:String(n),totalWei:u,transactions:[{chainId:t,from:r,to:e,data:o.data,value:u,gasLimit:String(o.gasLimit),maxFeePerGas:String(o.maxFeePerGas),...o.maxPriorityFeePerGas!=null?{maxPriorityFeePerGas:String(o.maxPriorityFeePerGas),type:2}:{}}]}}}async function Mr(e={},t={}){let r=t.rpcCall||k,n=String(e.address||"").trim().toLowerCase(),o=Number(e.chainId);if(!/^0x[a-f0-9]{40}$/.test(n))return{status:"error",error:"address must be a 0x-prefixed EVM address",found:[]};if(!Number.isInteger(o))return{status:"error",error:"chainId is required",found:[]};let a;try{a=await r(o,"eth_getCode",[n,"latest"],t)}catch(u){return{status:"unavailable",error:u?.message||"eth_getCode failed",found:[]}}if(!a||a==="0x")return{status:"ok",found:[],notes:["no contract deployed at this address"]};let i=a.slice(2).toLowerCase(),c=kr.filter(u=>i.includes(u.selector));return{status:"ok",address:n,chainId:o,found:c,notes:c.length?[]:["no known public mint selector found; this contract may use a custom or allowlist-only entrypoint"]}}async function de(e={},t={}){let r=String(e.contract||e.address||"").trim().toLowerCase(),n=Number(e.chainId),o=String(e.minter||e.from||"").trim().toLowerCase(),a=e.quantity==null?1:Number(e.quantity);if(!/^0x[a-f0-9]{40}$/.test(r))return{status:"error",error:"contract must be a 0x-prefixed EVM address"};if(!/^0x[a-f0-9]{40}$/.test(o))return{status:"error",error:"minter address is required"};if(!Number.isInteger(a)||a<1)return{status:"error",error:"quantity must be a positive integer"};if(!Number.isInteger(n))return{status:"error",error:"chainId is required"};let i=await Mr({address:r,chainId:n},t);if(i.status!=="ok")return{status:i.status,error:i.error};if(!i.found.length)return{status:"unsupported",error:"no known public mint function found in this contract's bytecode",notes:i.notes};let c=e.signature?i.found.find(y=>y.signature===e.signature):i.found[0];if(!c)return{status:"error",error:`requested signature ${e.signature} not present in this contract`,available:i.found.map(y=>y.signature)};let u=i.found.length>1&&!e.signature,f=await nt({address:r,chainId:n},t),s=null;if(e.simulate!==!1&&(s=await ot({chainId:n,tx:{from:o,to:r,data:at(c,{minter:o,quantity:a}),value:e.valueWei},gasBufferPercent:e.gasBufferPercent},t),s.willRevert===!0&&e.ignoreRevert!==!0))return{status:"would-revert",error:`mint would revert: ${s.revert.reason}`,simulation:s,mintFunction:c.signature,notes:["signing this now would burn gas and fail; pass ignoreRevert to prepare anyway (e.g. a mint that has not opened yet)"]};let l=e.gasLimit??(s?.gasLimit?Number(s.gasLimit):null),d=await rt({chainId:n,urgency:e.urgency||"war",gasLimit:l,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei,maxTotalGasWei:e.maxTotalGasWei},t);if(d.status!=="ok")return{status:"unavailable",error:d.error,notes:d.notes};let m;try{m=at(c,{minter:o,quantity:a})}catch(y){return{status:"error",error:y.message}}let h={chainId:n,from:o,to:r,data:m,value:e.valueWei==null?"0":String(e.valueWei),gasLimit:l==null?null:String(l),maxFeePerGas:d.maxFeePerGas,maxPriorityFeePerGas:d.maxPriorityFeePerGas},p={ok:!0,skipped:!0,reason:"no gasLimit or cap supplied"};if(l!=null&&(e.maxTotalGasWei!=null||e.grant!=null)&&(p=et({chainId:n,tx:{gasLimit:l,maxFeePerGas:d.maxFeePerGas,maxPriorityFeePerGas:d.maxPriorityFeePerGas},policy:{maxTotalGasWei:e.maxTotalGasWei,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei,grant:e.grant}}),!p.ok))return{status:"refused",error:`gas-war cap exceeded: ${p.reason||p.error}`,gas:d,capCheck:p};let g=[];u&&g.push(`contract exposes ${i.found.length} mint entrypoints (${i.found.map(y=>y.signature).join(", ")}); defaulted to ${c.signature} \u2014 pass signature to choose`),f.risk==="high"&&g.push(`contract risk HIGH: ${f.findings.map(y=>y.name).join(", ")}`),d.viable||g.push(d.notes[0]),p.skipped&&g.push("gas-war caps NOT enforced: supply gasLimit plus maxTotalGasWei or a grant");let b=null,T=null;try{b=Lr({address:r,chainId:n,minter:o,quantity:a,tx:h,nowMs:t.nowMs,ttlMs:e.ttlMs??e.expiresInMs})}catch(y){T=String(y?.message||y).slice(0,200)}return{status:"ok",execution:b?"armed-local":"prepare-only",signed:b?"pending-local-signer":!1,broadcast:b?"pending-local-signer":!1,tx:h,localSignerEnvelope:b,localSignerBlockedReason:T,mintFunction:c.signature,alternatives:i.found.map(y=>y.signature),quantity:a,gas:d,simulation:s,contractRisk:{risk:f.risk,findings:f.findings,isProxy:f.isProxy},capCheck:p,warnings:g}}var wo=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});function it(e=process.env){return String(e.ORACLE_AUTONOMOUS_TRADING??"").trim()==="1"}function Fr(e={},{nowMs:t=Date.now()}={}){let r=[];if(!e||typeof e!="object")return{ok:!1,problems:["grant is required for execute mode"]};let n=String(e.contract||"").toLowerCase();if(/^0x[a-f0-9]{40}$/.test(n)||r.push("grant.contract must be an exact address"),Number.isInteger(Number(e.chainId))||r.push("grant.chainId is required"),e.maxTotalGasWei==null&&r.push("grant.maxTotalGasWei is required"),e.maxValueWei==null&&r.push("grant.maxValueWei is required (mint price ceiling)"),e.expiresAt!=null){let o=Number(e.expiresAt);Number.isFinite(o)?o<=t&&r.push("grant has expired"):r.push("grant.expiresAt must be a timestamp when supplied")}return{ok:r.length===0,problems:r,contract:n,chainId:Number(e.chainId)}}function st(e={},t={}){let n=e.actionMode==="execute"?"execute":e.actionMode||"alert_only",o=String(e.contract||"").trim().toLowerCase(),a=Number(e.chainId),i=[];if(!/^0x[a-f0-9]{40}$/.test(o))return{status:"error",error:"contract must be a 0x-prefixed EVM address"};if(!Number.isInteger(a))return{status:"error",error:"chainId is required"};if(n!=="alert_only"&&n!=="execute")return{status:"ok",actionMode:"alert_only",requestedMode:n,downgraded:!0,contract:o,chainId:a,quantity:e.quantity==null?1:Number(e.quantity),urgency:e.urgency||"war",grant:null,notes:[`unrecognized actionMode ${JSON.stringify(n)} \u2014 defaulted to alert_only; only the exact string "execute" arms a trigger`]};let c=n;if(n==="execute")if(!it(t.env||process.env))c="alert_only",i.push("DOWNGRADED to alert_only: autonomous trading is off \u2014 set ORACLE_AUTONOMOUS_TRADING=1 to let a trigger fire unattended");else{let u=Fr(e.grant,{nowMs:t.nowMs});u.ok?(u.contract!==o||u.chainId!==a)&&(c="alert_only",i.push("DOWNGRADED to alert_only: grant does not match this contract/chain \u2014 a grant authorizes one exact target")):(c="alert_only",i.push(`DOWNGRADED to alert_only: ${u.problems.join("; ")}`))}return c==="alert_only"?i.push("alert_only: Oracle will notify and prepare an artifact; you sign it"):i.push("ARMED until mint opens: this trigger will submit one prepared, capped mint automatically when the mint opens"),{status:"ok",actionMode:c,requestedMode:n,downgraded:c!==n,contract:o,chainId:a,quantity:e.quantity==null?1:Number(e.quantity),urgency:e.urgency||"war",grant:c==="execute"?e.grant:null,armedUntil:c==="execute"?"mint-opens":null,notes:i}}async function Re(e={},t={}){let r=t.rpcCall||k,n=String(e.contract||"").trim().toLowerCase(),o=Number(e.chainId);if(!/^0x[a-f0-9]{40}$/.test(n)||!Number.isInteger(o))return{status:"error",open:!1,error:"contract and chainId are required"};let a=[{selector:"0xeb8d2444",name:"saleIsActive()",openWhen:!0},{selector:"0x25fd90f3",name:"mintActive()",openWhen:!0},{selector:"0x68428a1b",name:"saleActive()",openWhen:!0},{selector:"0x22f3e2d4",name:"isActive()",openWhen:!0},{selector:"0x5c975abb",name:"paused()",openWhen:!1}];for(let i of a)try{let c=await r(o,"eth_call",[{to:n,data:i.selector},"latest"],t);if(c&&c!=="0x"){let u=BigInt(c)===1n;return{status:"ok",open:i.openWhen?u:!u,evidence:i.name,raw:c}}}catch{}return{status:"unknown",open:!1,notes:["no readable sale-state flag; cannot confirm the mint is open \u2014 will not fire on a guess"]}}async function ct(e={},t={}){if(e.status!=="ok")return{status:"error",error:"invalid trigger"};let r=await Re({contract:e.contract,chainId:e.chainId},t);if(!r.open)return{status:"waiting",open:!1,reason:r.notes?.[0]||`sale flag ${r.evidence||"unknown"} reports closed`};let n=await de({contract:e.contract,chainId:e.chainId,minter:e.minter||t.minter,quantity:e.quantity,urgency:e.urgency,gasLimit:e.gasLimit??t.gasLimit,maxTotalGasWei:e.grant?.maxTotalGasWei??e.maxTotalGasWei??t.maxTotalGasWei,maxFeePerGasWei:e.maxFeePerGasWei??t.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei??t.maxPriorityFeePerGasWei,valueWei:e.valueWei??t.valueWei,grant:e.grant},t);if(n.status!=="ok")return{status:"blocked",open:!0,reason:n.error,prepared:n};if(e.actionMode==="execute"&&e.grant?.maxValueWei!=null){let o=BigInt(n.tx.value||"0");if(o>BigInt(e.grant.maxValueWei))return{status:"refused",open:!0,reason:`mint price ${o} exceeds granted maxValueWei ${e.grant.maxValueWei}`,prepared:n}}return{status:e.actionMode==="execute"?"fire":"alert",open:!0,actionMode:e.actionMode,prepared:n,signed:!1}}var Ao=Object.freeze([{selector:"0xeb8d2444",name:"saleIsActive()",openWhen:!0},{selector:"0x25fd90f3",name:"mintActive()",openWhen:!0},{selector:"0x68428a1b",name:"saleActive()",openWhen:!0},{selector:"0x22f3e2d4",name:"isActive()",openWhen:!0},{selector:"0x5c975abb",name:"paused()",openWhen:!1}]),v=Object.freeze({BUILDER_AUCTION:"builder-auction",OP_STACK_SEQUENCER:"op-stack-sequencer",NITRO_FCFS:"nitro-fcfs",HYPERBFT:"hyperbft",SOLANA_LEADER:"solana-leader",BITCOIN_FEE_RATE:"bitcoin-fee-rate"}),Br=Object.freeze({1:{chain:"Ethereum",regime:v.BUILDER_AUCTION},137:{chain:"Polygon",regime:v.BUILDER_AUCTION},56:{chain:"BNB Chain",regime:v.BUILDER_AUCTION},43114:{chain:"Avalanche C-Chain",regime:v.BUILDER_AUCTION},988:{chain:"Stable Mainnet",regime:v.BUILDER_AUCTION},8453:{chain:"Base",regime:v.OP_STACK_SEQUENCER},10:{chain:"OP Mainnet",regime:v.OP_STACK_SEQUENCER},7777777:{chain:"Zora",regime:v.OP_STACK_SEQUENCER},81457:{chain:"Blast",regime:v.OP_STACK_SEQUENCER},42161:{chain:"Arbitrum One",regime:v.NITRO_FCFS},4663:{chain:"Robinhood Chain",regime:v.NITRO_FCFS},2741:{chain:"Abstract",regime:v.NITRO_FCFS},999:{chain:"HyperEVM",regime:v.HYPERBFT}}),jr=Object.freeze({solana:{chain:"Solana",regime:v.SOLANA_LEADER},bitcoin:{chain:"Bitcoin",regime:v.BITCOIN_FEE_RATE},ordinals:{chain:"Bitcoin Ordinals",regime:v.BITCOIN_FEE_RATE}}),Dr=Object.freeze({[v.BUILDER_AUCTION]:{ordering:"builder-auction",lever:"priority-fee",priorityFeeHelps:!0,latencyDecides:!1,privateRelayAvailable:!0,subSecondRace:!0,notes:["inclusion is bought through the block builder auction","priority fee is the lever that actually moves position","a private relay hides the transaction from the public mempool and avoids being front-run"]},[v.OP_STACK_SEQUENCER]:{ordering:"sequencer",lever:"priority-fee+latency",priorityFeeHelps:!0,latencyDecides:!0,privateRelayAvailable:!1,subSecondRace:!0,notes:["the sequencer mempool orders by effective gas price, so paying more does move you forward","arrival time still matters within a fee tier, so latency and fee are both live levers","there is no public builder auction to bid into and no private relay to hide in"]},[v.NITRO_FCFS]:{ordering:"sequencer",lever:"latency",priorityFeeHelps:!1,latencyDecides:!0,privateRelayAvailable:!1,subSecondRace:!0,notes:["Nitro timestamps by arrival order; fees do not reorder the sequencer queue","raw round-trip time is the only lever that changes position","co-locate near the sequencer endpoint rather than raising gas"]},[v.HYPERBFT]:{ordering:"consensus",lever:"latency",priorityFeeHelps:!1,latencyDecides:!0,privateRelayAvailable:!1,subSecondRace:!0,notes:["HyperBFT consensus orders transactions; there is no public builder auction to bid into","reaching a validator early is the lever, not paying more","block times are sub-second, so a slow RPC path costs whole blocks"]},[v.SOLANA_LEADER]:{ordering:"leader",lever:"priority-fee+latency",priorityFeeHelps:!0,latencyDecides:!0,privateRelayAvailable:!0,subSecondRace:!0,notes:["there is no mempool: transactions are sent to the current and next slot leaders","compute-unit price is the fee lever; Jito bundles are the private-inclusion path","landing depends on reaching the leader in time, so both levers are live"]},[v.BITCOIN_FEE_RATE]:{ordering:"fee-rate",lever:"fee-rate",priorityFeeHelps:!0,latencyDecides:!1,privateRelayAvailable:!1,subSecondRace:!1,notes:["inclusion is fee-rate against roughly ten-minute blocks, not a sub-second race","being milliseconds earlier does not change inclusion; sat/vB estimation does","a co-located executor buys nothing here \u2014 this is a fee-estimation problem"]}});function ut(e){let t=e&&typeof e=="object"?e.chainId??e.family??e.chain:e,r=String(t??"").trim().toLowerCase(),n=jr[r]||Br[Number(t)];if(!n)return{chainId:Number.isInteger(Number(t))?Number(t):null,chain:null,regime:null,ordering:"unknown",lever:"unknown",priorityFeeHelps:null,latencyDecides:null,privateRelayAvailable:!1,subSecondRace:null,notes:["chain ordering not classified; treat inclusion strategy as unverified"]};let o=Dr[n.regime];return{chainId:Number.isInteger(Number(t))?Number(t):null,chain:n.chain,regime:n.regime,...o,notes:[...o.notes]}}var Oo=Object.freeze({"0x02c88989":"setSaleIsActive(bool)","0x34918dfd":"flipSaleState()","0x5a67de07":"setSaleState(uint8)","0x3f4ba83a":"unpause()","0x16c38b3c":"setPaused(bool)","0xb66a0e5d":"startSale()","0xee1cc944":"setMintActive(bool)"});function Hr(e){let t=ut(e);return t.regime==="nitro-fcfs"?{visible:!1,reason:"Arbitrum orders at a private sequencer; there is no public pending pool to watch"}:t.regime==="op-stack-sequencer"?{visible:!1,reason:"the OP-stack sequencer holds pending transactions privately; public mempool watching will not see the opening transaction"}:t.regime==="solana-leader"?{visible:!1,reason:"Solana has no mempool; transactions go straight to the slot leader"}:t.regime==="hyperbft"?{visible:!1,reason:"HyperBFT orders through validator consensus; there is no public pending pool to watch"}:t.regime==="bitcoin-fee-rate"?{visible:!1,reason:"Bitcoin inclusion is fee-rate over ten-minute blocks, so there is no sub-second opening to detect"}:t.regime==="builder-auction"?{visible:!0,reason:"public mempool is observable, though private-relay transactions will not appear in it"}:{visible:!1,reason:"chain ordering not classified; mempool visibility unverified"}}function lt(e){let t=Hr(e);return{chainId:Number(e),mempoolVisible:t.visible,reason:t.reason,fallback:t.visible?null:"poll sale state with probeMintOpenFast"}}import{existsSync as Sn,readFileSync as vn}from"node:fs";import{request as An}from"node:http";import Tn from"node:path";import pe from"node:fs";import Gr from"node:os";import Z from"node:path";import{fileURLToPath as qr}from"node:url";var Wr=Z.dirname(qr(import.meta.url)),Co=Z.resolve(Wr,"../..");function ft(){return process.env.ORACLE_FAKE_HOME||Gr.homedir()}function Ur(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function me(){return Ur()?process.env.ORACLE_CONFIG_DIR||Z.join(ft(),".config","oracle"):Z.join(ft(),".config","oracle")}function Vr(){return Z.join(me(),"desk.json")}function zr(){return Z.join(me(),"env")}function X({force:e=!1}={}){if(X._done&&!e)return X._result||null;X._done=!0;let t={},r=(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,t[o]=i))};try{let o=zr();if(pe.existsSync(o))for(let a of pe.readFileSync(o,"utf8").split(/\r?\n/)){let i=a.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let c=i[2];(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),r(i[1],c)}}catch{}try{let o=Vr();if(pe.existsSync(o)){let a=JSON.parse(pe.readFileSync(o,"utf8"));a&&typeof a=="object"&&(r("ORACLE_DESK_URL",a.deskUrl||a.dataUrl||a.url),r("ORACLE_DATA_URL",a.dataUrl||a.deskUrl||a.url),r("ORACLE_API_URL",a.apiUrl||a.dataUrl||a.deskUrl),r("ORACLE_PUBLIC_URL",a.publicUrl||a.deskUrl||a.dataUrl),r("ORACLE_EXEC_URL",a.execUrl),r("MAD_DESK_URL",a.deskUrl||a.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),X._result=Object.keys(t).length?t:null,X._result}try{X()}catch{}import{createHash as ln}from"node:crypto";var Jr=/^0x[0-9a-f]{40}$/,Kr=/^0x(?:[0-9a-f]{2})*$/,Yr=/^(?:0x)?[0-9a-f]{64}$/,Xr=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Zr=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,Qr=new Set([12,15,18,21,24]),he=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function Pe(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Zr.test(e)||Qr.has(o.length)&&o.every(a=>/^[a-z]+$/i.test(a)))throw new he(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,a)=>Pe(o,`${t}[${a}]`,r));J(e,t);let n={};for(let o of Object.keys(e).sort()){let a=o.replace(/[^a-z0-9]/gi,"");if(Xr.test(a))throw new he(`${t}.${o}`);e[o]!==void 0&&(n[o]=Pe(e[o],`${t}.${o}`,o))}return n}function J(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function se(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Q(e,t){let r=String(se(e,t)).toLowerCase();if(!Jr.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function B(e,t,{positive:r=!1}={}){try{let n=BigInt(se(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function _e(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function dt(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))dt(t);Object.freeze(e)}return e}function en(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};J(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:_e(String(n),`${t}.reason`)}}function tn(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>en(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function rn(e){if(e==null)return null;if(J(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:_e(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=B(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=B(e.gasLimit,"simulation.gasLimit")),t}function nn(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{J(t,`assetDeltas[${r}]`);let n=B(t.before,`assetDeltas[${r}].before`),o=B(t.after,`assetDeltas[${r}].after`),a=(BigInt(o)-BigInt(n)).toString(),i;try{i=t.delta==null?a:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(i!==a)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:_e(String(se(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:i}})}function on(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{J(t,`approvalDeltas[${r}]`);let n=B(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Q(t.token,`approvalDeltas[${r}].token`),spender:Q(t.spender,`approvalDeltas[${r}].spender`),owner:Q(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function pt(e={}){J(e,"input");let t=Pe(e),r=t.tx==null?t:J(t.tx,"tx"),n=B(t.chainId??r.chainId,"chainId",{positive:!0}),o=Q(t.account??t.from??r.from,"account/from"),a=Q(t.destination??t.to??r.to,"destination/to"),i=String(se(t.prepareHash,"prepareHash")).toLowerCase();if(!Yr.test(i))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let c=t.route??t.venue;if(c==null)throw new TypeError("sign-time review: route/venue required");let u=t.decodedCalldata??t.decodedAction;if(u==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let f=String(se(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Kr.test(f))throw new TypeError("sign-time review: calldata/data must be even-length hex");let s=t.policyChecks!==void 0&&t.policyChecks!==null,l=tn(s?t.policyChecks:[]),d=rn(t.simulation),m=nn(t.assetDeltas),h=on(t.approvalDeltas),p=t.allowlistHits??[];if(!Array.isArray(p))throw new TypeError("sign-time review: allowlistHits must be an array");let g=d?.willRevert===!0||["failed","error"].includes(d?.status),b=d!=null&&d.willRevert===!1&&["ok","success"].includes(d.status),T=g||l.failed>0?"BLOCKED":b&&s&&l.checks.length>0&&m!=null?"READY":"UNKNOWN",y=typeof u=="string"?u:u.method??u.action??u.type??"transaction",_=`${T}: review ${y} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${m?.length??0} asset delta${m?.length===1?"":"s"}; local signature required`,C={reviewVersion:1,status:T,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:c,venue:t.venue??(typeof c=="string"?c:c.venue??c.provider??null),destination:a,to:a,...t.spender==null?{}:{spender:Q(t.spender,"spender")},prepareHash:i,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:f,data:f,selector:f.length>=10?f.slice(0,10):null,value:B(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:B(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:B(t.gasLimit??r.gasLimit,"gasLimit")},simulation:d,policyChecks:l,allowlistHits:p,assetDeltas:m,approvalDeltas:h,summary:_};return dt(C)}import{createHash as an,createHmac as sn,timingSafeEqual as Fo}from"node:crypto";var Bo=300*1e3,jo=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function Ne(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ne).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Ne(e[r])}`).join(",")}}`}function mt(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function cn(e=process.env){return mt(process.env)||mt(e)}function un(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function ht(e){let t=un(e);return an("sha256").update(Ne(t)).digest("hex")}function gt(e,t=cn()){return t?sn("sha256",t).update(String(e)).digest("hex"):""}var wt=1,bt="prepare-verification";var ke=Object.freeze({NONE:"none",PREPARE_CHECKSUM:"prepare-checksum",PREPARE_HMAC:"prepare-hmac"}),fn=/^(?:0x)?[0-9a-f]{64}$/i,dn=Object.freeze(["signature","signedTx","signedTransaction","rawTransaction","signedPayload","signedRaw"]),pn=Object.freeze(["txid","txHash","transactionHash","broadcastHash"]),mn=Object.freeze(["tee-attestation","remote-attestation","hardware-enclave","trusted-execution-environment","execution-authorization","signature","broadcast"]);function K(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))K(t);Object.freeze(e)}return e}function ee(e,t){if(e==null||typeof e!="object"||Array.isArray(e))throw new TypeError(`prepare verification: ${t} must be an object`);return e}function Ce(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ce).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${Ce(e[r])}`).join(",")}}`}function yt(e){return ln("sha256").update(Ce(e),"utf8").digest("hex")}function hn(e,t,r=500){let o=(e==null?t:String(e)).trim();return o?o.slice(0,r):t}function gn(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function ce(e){let t=String(e||"").trim().toLowerCase().replace(/^0x/,"");return fn.test(t)?t:""}function xt(e){if(e?.transaction&&typeof e.transaction=="object")return e.transaction;if(e?.tx&&typeof e.tx=="object")return e.tx;let t=e?.localSignerEnvelope||e?.envelope;return t?.artifact&&typeof t.artifact=="object"?t.artifact:e}function Et(e,t="prepare verification"){if(ee(e,"prepared"),e.signed===!0)throw new Error(`${t}: prepared fact is signed`);if(e.broadcast===!0)throw new Error(`${t}: prepared fact claims broadcast`);for(let r of dn)if(e[r])throw new Error(`${t}: prepared fact carries ${r}`);for(let r of pn)if(e[r])throw new Error(`${t}: prepared fact claims executed ${r}`);return!0}function wn(e){if(e==null)return K({status:"unavailable",willRevert:null,summary:"no simulation supplied",source:"unavailable"});ee(e,"simulation");let t=String(e.status||(e.willRevert===!0?"failed":e.ok===!1?"error":"unknown")),r=["ok","success","failed","error","unavailable","unknown"].includes(t)?t:"unknown",n=e.willRevert===!0||e.willRevert===!1?e.willRevert:null;return K({status:r,willRevert:n,summary:hn(e.summary||e.reason||e.error,"simulation result recorded"),source:e.source==="dry-run"||e.source==="supplied"||e.source==="unavailable"?e.source:"supplied",...e.gasEstimate!=null?{gasEstimate:String(e.gasEstimate)}:{},...e.gasLimit!=null?{gasLimit:String(e.gasLimit)}:{}})}function bn(e={},t={}){let r=xt(e),n=e.localSignerEnvelope||e.envelope||{},o=t.provider||e.provider||e.source||n.provider||t.venue||e.venue||"unknown",a=t.kind||e.kind||e.artifactKind||n.action||e.action||"prepare",i=t.destination||e.destination||e.to||r?.to||n.destination||null,c=t.chainId??e.chainId??r?.chainId??n.chainId??null,u=t.account||e.account||e.from||r?.from||n.owner||null,f=[`Unsigned ${a} via ${o}`];return i&&f.push(`to ${i}`),c!=null&&c!==""&&f.push(`on chain ${c}`),t.note&&f.push(String(t.note)),f.push("for owner review only \u2014 not signed, not armed, not executed"),K({summary:f.join(" "),provider:String(o),kind:String(a),destination:i==null?null:String(i),chainId:c==null||c===""?null:String(c),account:u==null?null:String(u)})}function yn({prepared:e={},env:t}={}){ee(e,"prepared");let r=ce(e.prepareHash),n=typeof e.prepareMac=="string"&&e.prepareMac.length>=32,o=!1;if(r)try{o=ht(e)===String(e.prepareHash)}catch{o=!1}let a=!1,i=gn(t);if(n&&i&&r)try{let s=gt(r,i);a=s.length>0&&s===String(e.prepareMac)}catch{a=!1}let c=n?ke.PREPARE_HMAC:r?ke.PREPARE_CHECKSUM:ke.NONE,u=[];r&&u.push(o?"prepare-body-sha256-bound":"prepare-hash-present-unverified"),n&&u.push(a?"keyed-prepare-mac-verified":"keyed-prepare-mac-present-unverified");let f=a?"Keyed prepare MAC verified. This is integrity provenance, not TEE attestation or execution authority.":o?"Public prepare checksum only. Not provenance. Not TEE attested. Not an execution grant.":"No verified prepare integrity stamp. Simulation and intent are operator-visible facts only.";return K({kind:c,teeAttested:!1,cryptographicallyAttested:a,checksumBound:o,claims:u,notClaimed:[...mn],custody:"none",execution:"prepare-only",note:f})}function xn(e,t,r){let n=xt(e),o=e.localSignerEnvelope||e.envelope||{};try{let a=pt({chainId:e.chainId??n?.chainId??o.chainId,account:e.account||e.from||n?.from||o.owner,destination:e.destination||e.to||n?.to||o.destination,calldata:e.calldata||e.data||n?.data||"0x",value:e.value??n?.value??0,prepareHash:t,route:e.provider||e.venue||o.provider||o.surface||"prepare",decodedAction:e.kind||e.action||o.action||"transaction",simulation:r,...e.policyChecks?{policyChecks:e.policyChecks}:{}});return K({status:a.status,summary:a.summary,requiresLocalSignature:!0,custody:a.custody,execution:a.execution})}catch{return null}}function En({prepared:e,simulation:t,intent:r,env:n,nowMs:o=Date.now()}={}){ee(e,"prepared"),Et(e);let a=Number(o);if(!Number.isSafeInteger(a)||a<=0)throw new TypeError("prepare verification: bounded createdAt required");let i=wn(t??e.simulation??e.sim),c=bn(e,r&&typeof r=="object"?r:{}),u=yn({prepared:e,env:n}),f=ce(e.prepareHash)||null,s=f?xn(e,f,i):null,l={version:wt,kind:bt,prepareHash:f,simulation:i,intent:c,intentSummary:c.summary,attestation:u,review:s,custody:"none",execution:"prepare-only",signingReady:!1,broadcastReady:!1,executionReady:!1,createdAt:a};return K({...l,artifactHash:yt(l)})}function St(e,t={}){let r=t.label||"prepare verification";if(ee(e,"artifact"),Number(e.version)!==wt)throw new Error(`${r}: unsupported verification artifact version`);if(e.kind!==bt)throw new Error(`${r}: verification artifact kind required`);if(e.custody!=="none")throw new Error(`${r}: verification artifact custody must be none`);if(e.execution!=="prepare-only")throw new Error(`${r}: verification artifact must stay prepare-only`);if(e.signingReady===!0||e.broadcastReady===!0||e.executionReady===!0)throw new Error(`${r}: verification artifact must not claim a ready execution flag`);if(e.attestation?.teeAttested===!0)throw new Error(`${r}: TEE attestation is not claimed or accepted`);if(!["ok","success","failed","error","unavailable","unknown"].includes(String(e.simulation?.status||"")))throw new Error(`${r}: simulation status required`);if(typeof e.intentSummary!="string"||!e.intentSummary.trim())throw new Error(`${r}: human-readable intent summary required`);if(!e.attestation||typeof e.attestation!="object")throw new Error(`${r}: attestation record required`);if(!Array.isArray(e.attestation.notClaimed)||!e.attestation.notClaimed.includes("tee-attestation"))throw new Error(`${r}: attestation must honestly exclude TEE claims`);let{artifactHash:n,...o}=e;if(ce(n)!==yt(o))throw new Error(`${r}: artifactHash mismatch \u2014 verification artifact was altered`);if(t.prepareHash){let a=ce(t.prepareHash),i=ce(e.prepareHash);if(!a||a!==i)throw new Error(`${r}: verification artifact does not bind this prepare`)}return e}function vt(e,t={}){ee(e,"prepared");let r=t.artifact&&typeof t.artifact=="object"?t.artifact:En({prepared:e,simulation:t.simulation,intent:t.intent,env:t.env,nowMs:t.nowMs});return St(r,{label:t.label||"prepare verification"}),{...e,prepareVerification:r}}function At(e,t={}){let r=t.label||"armPreparedAction";if(!e||typeof e!="object")throw new Error(`${r}: prepared object required`);let n=e.prepareVerification||e.verificationArtifact||e.deskCheckpoint?.prepareVerification||t.checkpoint?.prepareVerification;if(!n)throw new Error(`${r}: prepare verification artifact required before arm`);return St(n,{label:r,...e.prepareHash?{prepareHash:e.prepareHash}:{}}),Et(e,r),n}var In="http://127.0.0.1:9462";function On(e=process.env){let t=String(e.ORACLE_SIGNER_URL||In).replace(/\/$/,""),r;try{r=new URL(t)}catch{return null}return r.hostname!=="127.0.0.1"&&r.hostname!=="localhost"&&r.hostname!=="::1"?null:r.origin}function Rn(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=Tn.join(me(),"signer","signer-token");return Sn(t)?vn(t,"utf8").trim():null}function Pn(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let a=On(n),i=Rn(n);return!a||!i?Promise.resolve({ok:!1,error:"local signer is not running"}):new Promise(c=>{let u=new URL(e,a),f=r?Buffer.from(JSON.stringify(r)):null,s=An({hostname:u.hostname,port:u.port||80,path:u.pathname,method:t,timeout:o,headers:{authorization:`Bearer ${i}`,origin:a,...f?{"content-type":"application/json","content-length":f.length}:{}}},l=>{let d=[];l.on("data",m=>d.push(m)),l.on("end",()=>{let m=Buffer.concat(d).toString("utf8"),h={};try{h=m?JSON.parse(m):{}}catch{h={error:"signer refused"}}c({httpStatus:l.statusCode,...h})})});s.on("timeout",()=>{s.destroy(),c({ok:!1,error:"local signer timed out"})}),s.on("error",()=>c({ok:!1,error:"local signer is not running"})),f&&s.write(f),s.end()})}async function _n(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return Pn("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function Tt(e,t=process.env){let r=e?.localSignerEnvelope||e?.envelope;if(!r||r.version!==1||!r.surface)throw new Error("armPreparedAction: prepared.localSignerEnvelope v1 required");return At(e,{env:t,label:"armPreparedAction"}),_n(r,t)}import{Interface as $n,MaxUint256 as Na,isAddress as ka,keccak256 as Ca,toUtf8Bytes as $a}from"ethers";import{Interface as kn,isAddress as fa}from"ethers";import{isAddress as aa}from"ethers";var ha=new kn(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Cn,isAddress as ba}from"ethers";var Sa=new Cn(["function approve(address spender,uint256 amount) returns (bool)"]),va=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var Da=new $n(["function approve(address spender,uint256 amount) returns (bool)"]);var Ln=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function It(e){try{return Ln.has(BigInt(e))}catch{return!1}}var Rt=`oracle mint <watch|check|prepare> <contract> --chain <id> [options]
4
+ ${JSON.stringify(r??[])}`}async function vr(e,t,r){return Ze(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function k(e,t,r=[],n={}){let o=String(t||""),a=yr(o),i=wr(e,n);if(!i)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);if(a==="eth_chainid"&&n.cacheChainId!==!1){let s=rt.get(i);if(s!=null)return s}let u=n.dedupe!==!1&&!n.signal?Sr(i,o,r):null;if(u&&ie.has(u))return ie.get(u);let f=(async()=>{let s=await vr(i,{jsonrpc:"2.0",id:1,method:t,params:r},n),l=Er(s);return a==="eth_chainid"&&typeof l=="string"&&rt.set(i,l),l})();return u&&(ie.set(u,f),f.finally(()=>{ie.get(u)===f&&ie.delete(u)}).catch(()=>{})),f}var Ar=/^(0|[1-9][0-9]*)$/;function V(e,t,{required:r=!0,allowZero:n=!1}={}){if(e==null||e===""){if(r)throw new Error(`${t} required`);return null}let o;if(typeof e=="bigint")o=e;else if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error(`${t} must be a safe integer`);o=BigInt(e)}else if(typeof e=="string"){let a=e.trim();if(a.startsWith("0x")||a.startsWith("0X"))o=BigInt(a);else{if(!Ar.test(a))throw new Error(`${t} must be an integer wei string`);o=BigInt(a)}}else throw new Error(`${t} must be bigint, number, or integer string`);if(o<0n||!n&&o===0n)throw new Error(`${t} must be ${n?"non-negative":"positive"}`);return o}function Tr(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new Error("chainId must be a positive integer");return t}function Ir(e={}){return e.maxFeePerGas!=null?V(e.maxFeePerGas,"maxFeePerGas"):e.gasPrice!=null?V(e.gasPrice,"gasPrice"):null}function nt(e={}){try{let t=Tr(e.chainId??e.tx?.chainId),r=e.tx||e,n=e.policy||e,o=n.grant?.maxGasWei??e.grant?.maxGasWei,a=V(n.maxTotalGasWei??n.maxGasWei??o,"maxTotalGasWei"),i=V(r.gasLimit??r.gas,"gasLimit"),c=Ir(r);if(c==null)throw new Error("maxFeePerGas or gasPrice required");let u=V(n.maxFeePerGasWei,"maxFeePerGasWei",{required:!1}),f=V(n.maxPriorityFeePerGasWei,"maxPriorityFeePerGasWei",{required:!1}),s=r.maxPriorityFeePerGas==null?null:V(r.maxPriorityFeePerGas,"maxPriorityFeePerGas"),l=i*c;return l>a?{ok:!1,status:"BLOCK",reason:`total gas ${l} exceeds cap ${a}`,chainId:t,totalGasWei:l.toString(),maxTotalGasWei:a.toString()}:u!=null&&c>u?{ok:!1,status:"BLOCK",reason:`unit fee ${c} exceeds cap ${u}`,chainId:t,unitFeeWei:c.toString(),maxFeePerGasWei:u.toString(),totalGasWei:l.toString(),maxTotalGasWei:a.toString()}:s!=null&&f!=null&&s>f?{ok:!1,status:"BLOCK",reason:`priority fee ${s} exceeds cap ${f}`,chainId:t,priorityFeeWei:s.toString(),maxPriorityFeePerGasWei:f.toString(),totalGasWei:l.toString(),maxTotalGasWei:a.toString()}:{ok:!0,status:"PASS",reason:"gas envelope within NFT mint gas-war caps",chainId:t,totalGasWei:l.toString(),maxTotalGasWei:a.toString(),unitFeeWei:c.toString(),maxFeePerGasWei:u?.toString()??null,priorityFeeWei:s?.toString()??null,maxPriorityFeePerGasWei:f?.toString()??null}}catch(t){return{ok:!1,status:"BLOCK",reason:String(t?.message||t)}}}var Or=5,Re=[50,75,90],ot=Object.freeze({normal:{percentile:0,baseFeeMultiplier:2n,label:"normal"},fast:{percentile:1,baseFeeMultiplier:3n,label:"fast"},war:{percentile:2,baseFeeMultiplier:4n,label:"war"}});function z(e,t){if(e==null)return null;try{if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isFinite(e)||e<0)throw new Error("bad number");return BigInt(Math.floor(e))}let r=String(e).trim();return r.startsWith("0x"),BigInt(r)}catch{throw new Error(`${t} must be a non-negative integer (wei)`)}}function Rr(e){let t=e.filter(r=>r!=null).sort((r,n)=>r<n?-1:r>n?1:0);return t.length?t[Math.floor(t.length/2)]:null}async function at(e={},t={}){let r=t.rpcCall||k,n=Number(e.chainId);if(!Number.isInteger(n))return{status:"error",error:"chainId is required",viable:!1};let o=ot[e.urgency||"fast"];if(!o)return{status:"error",viable:!1,error:`urgency must be one of: ${Object.keys(ot).join(", ")}`};let a,i,c,u;try{a=z(e.maxFeePerGasWei,"maxFeePerGasWei"),i=z(e.maxPriorityFeePerGasWei,"maxPriorityFeePerGasWei"),c=z(e.gasLimit,"gasLimit"),u=z(e.maxTotalGasWei,"maxTotalGasWei")}catch(x){return{status:"error",viable:!1,error:x.message}}let f,s;try{[f,s]=await Promise.all([r(n,"eth_feeHistory",[`0x${Or.toString(16)}`,"pending",Re],t),r(n,"eth_getBlockByNumber",["pending",!1],t)])}catch(x){return{status:"unavailable",viable:!1,error:x?.message||"fee history unavailable",notes:["could not read live fee data; refusing to guess a competitive bid"]}}let l=z(s?.baseFeePerGas,"baseFeePerGas")??z(f?.baseFeePerGas?.[f.baseFeePerGas.length-1],"baseFeePerGas");if(l==null)return{status:"unavailable",viable:!1,error:"chain did not report a baseFeePerGas (pre-EIP-1559?)",notes:["this pricer is EIP-1559 only"]};let m=(Array.isArray(f?.reward)?f.reward:[]).map(x=>{try{return z(x?.[o.percentile],"reward")}catch{return null}}).filter(x=>x!=null&&x>0n),h=Rr(m),p=[];h==null&&p.push("no non-zero tips observed in recent blocks; using a 1 gwei floor");let g=h??1000000000n,b=l*o.baseFeeMultiplier+g,T=[];i!=null&&g>i&&(T.push({field:"maxPriorityFeePerGas",wanted:g.toString(),capped:i.toString()}),g=i,b=l*o.baseFeeMultiplier+g),a!=null&&b>a&&(T.push({field:"maxFeePerGas",wanted:b.toString(),capped:a.toString()}),b=a,g>b&&(g=b));let y=c!=null?c*b:null;u!=null&&y!=null&&y>u&&T.push({field:"totalGas",wanted:y.toString(),capped:u.toString()});let _=h==null||g>=h,C=u==null||y==null||y<=u,H=_&&C;return _||p.push(`tip cap ${g} is below the observed ${Re[o.percentile]}th-percentile tip ${h}; this bid is unlikely to land`),C||p.push(`worst-case gas ${y} exceeds the ${u} total cap`),p.push("maxFeePerGas is a ceiling \u2014 unused headroom above basefee+tip is refunded, not spent"),{status:"ok",viable:H,chainId:n,urgency:o.label,baseFeePerGas:l.toString(),observedTip:h==null?null:h.toString(),percentile:Re[o.percentile],maxFeePerGas:b.toString(),maxPriorityFeePerGas:g.toString(),worstCaseGasWei:y==null?null:y.toString(),clamps:T,notes:p}}var Pr=Object.freeze({"8da5cb5b":{name:"owner()",weight:"low",note:"contract has an owner"},f2fde38b:{name:"transferOwnership(address)",weight:"low",note:"ownership transferable"},"40c10f19":{name:"mint(address,uint256)",weight:"high",note:"owner can mint new supply"},a0712d68:{name:"mint(uint256)",weight:"high",note:"owner can mint new supply"},f9f92be4:{name:"blacklist(address)",weight:"high",note:"addresses can be blocked from selling"},e4997dc5:{name:"removeBlackList(address)",weight:"high",note:"blacklist machinery present"},"8456cb59":{name:"pause()",weight:"high",note:"transfers can be frozen"},"3f4ba83a":{name:"unpause()",weight:"high",note:"pausable transfers"},c0246668:{name:"setFee/excludeFromFee",weight:"high",note:"transfer fees can be changed"},"3659cfe6":{name:"upgradeTo(address)",weight:"high",note:"logic can be replaced entirely"},"4f1ef286":{name:"upgradeToAndCall(address,bytes)",weight:"high",note:"logic can be replaced entirely"}}),_r=Object.freeze([{label:"eip1967",slot:"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"},{label:"zeppelinos",slot:"0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3"},{label:"eip1822",slot:"0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"}]),Nr=`0x${"0".repeat(64)}`;function kr(e){return!e||e==="0x"||e===Nr}async function it(e={},t={}){let r=t.rpcCall||k,n=String(e.address||"").trim().toLowerCase(),o=Number(e.chainId);if(!/^0x[a-f0-9]{40}$/.test(n))return{status:"error",error:"address must be a 0x-prefixed EVM address",risk:"unknown-risk",findings:[],notes:[]};if(!Number.isInteger(o))return{status:"error",error:"chainId is required",risk:"unknown-risk",findings:[],notes:[]};let a;try{a=await r(o,"eth_getCode",[n,"latest"],t)}catch(p){return{address:n,chainId:o,status:"unavailable",error:p?.message||"eth_getCode failed",risk:"unknown-risk",findings:[],isProxy:!1,codeSize:0,notes:["could not read contract code; treat as unverified"]}}if(!a||a==="0x")return{address:n,chainId:o,status:"ok",risk:"high",findings:[{selector:"-",name:"no-code",weight:"high",note:"no contract deployed at this address"}],isProxy:!1,codeSize:0,notes:["nothing is deployed here \u2014 an approval or transfer to this address is unrecoverable"]};let i=[],c=[],u=a.slice(2).toLowerCase();for(let[p,g]of Object.entries(Pr))u.includes(p)&&c.push({selector:`0x${p}`,...g});let f=!1,s=null,l=null,d=await Promise.all(_r.map(async({label:p,slot:g})=>{try{let b=await r(o,"eth_getStorageAt",[n,g,"latest"],t);return{label:p,word:b,error:null}}catch{return{label:p,word:null,error:`proxy slot (${p}) unreadable; proxy status uncertain`}}}));for(let p of d)p.error&&i.push(p.error),!f&&p.word&&!kr(p.word)&&(f=!0,s=p.label,l=`0x${String(p.word).slice(-40)}`);f&&(c.push({selector:s,name:"proxy",weight:"high",note:"implementation is upgradeable \u2014 current behaviour is not a guarantee"}),i.push(`bytecode scan covers the proxy (${s}), not the implementation ${l} it delegates to`));let h=c.filter(p=>p.weight==="high").length>0?"high":c.length>0?"elevated":"unknown-risk";return h==="unknown-risk"&&i.push("no owner-power selectors found; this is weak evidence, not a safety guarantee"),{address:n,chainId:o,status:"ok",risk:h,findings:c,isProxy:f,proxyStandard:s,implementation:l,codeSize:Math.floor(u.length/2),notes:i}}var Cr="08c379a0",$r="4e487b71",Lr=Object.freeze({1:"assertion failed",17:"arithmetic overflow or underflow",18:"division or modulo by zero",33:"invalid enum value",34:"invalid storage byte array encoding",49:"pop() on an empty array",50:"array index out of bounds",65:"out of memory",81:"call to an uninitialized function pointer"});function Mr(e){if(!e||e==="0x")return{kind:"empty",reason:"reverted without a reason (often a require with no message, or out of gas)"};let t=String(e).slice(2),r=t.slice(0,8);if(r===Cr)try{let n=parseInt(t.slice(72,136),16),o=t.slice(136,136+n*2);return{kind:"revert",reason:Buffer.from(o,"hex").toString("utf8"),selector:`0x${r}`}}catch{return{kind:"revert",reason:"Error(string) payload could not be decoded",selector:`0x${r}`}}if(r===$r){let n=parseInt(t.slice(8,72),16);return{kind:"panic",code:n,reason:Lr[n]||`panic code 0x${n.toString(16)}`,selector:`0x${r}`}}return{kind:"custom",reason:`custom error ${`0x${r}`} (decoding needs the contract ABI)`,selector:`0x${r}`}}function Fr(e){let t=[e?.data,e?.error?.data,e?.data?.data,e?.cause?.data,e?.body?.error?.data];for(let o of t){if(typeof o=="string"&&o.startsWith("0x")&&o.length>2)return o;if(typeof o?.data=="string"&&o.data.startsWith("0x")&&o.data.length>2)return o.data}let n=String(e?.message||"").match(/0x[0-9a-fA-F]{72,}/);return n?n[0]:null}function Br(e,t){if(t)return!0;let r=String(e?.message||"").toLowerCase();return!!/execution reverted|revert|invalid opcode|out of gas|stack underflow|insufficient funds for/.test(r)}function jr(e={}){let t={};return e.from&&(t.from=String(e.from).toLowerCase()),e.to&&(t.to=String(e.to).toLowerCase()),e.data&&e.data!=="0x"&&(t.data=e.data),e.value!=null&&String(e.value)!=="0"&&(t.value=`0x${BigInt(e.value).toString(16)}`),t}async function st(e={},t={}){let r=t.rpcCall||k,n=Number(e.chainId),o=e.tx||{};if(!Number.isInteger(n))return{status:"error",willRevert:null,error:"chainId is required"};if(!o.to||!/^0x[a-fA-F0-9]{40}$/.test(String(o.to)))return{status:"error",willRevert:null,error:"tx.to must be a valid address"};if(o.from&&!/^0x[a-fA-F0-9]{40}$/.test(String(o.from)))return{status:"error",willRevert:null,error:"tx.from must be a valid address"};let a=jr(o),i=[],c=null,u=!1,f=null;try{c=await r(n,"eth_call",[a,"pending"],t)}catch(h){let p=Fr(h);if(!Br(h,!!p))return{status:"unavailable",willRevert:null,chainId:n,error:h?.message||"simulation unavailable",notes:["could not reach the node; this is NOT evidence the transaction would fail"]};u=!0,f=Mr(p),p||(f.reason="execution reverted (node did not return a reason payload)",f.kind="revert-no-data")}if(u)return{status:"ok",willRevert:!0,chainId:n,revert:f,summary:`would REVERT: ${f.reason}`,notes:["simulated against current chain state; signing this now would burn gas and fail"]};let s=null,l=null;if(e.estimateGas!==!1)try{let h=await r(n,"eth_estimateGas",[a,"pending"],t);s=BigInt(h);let p=BigInt(Math.max(0,Math.floor(e.gasBufferPercent??20)));l=s+s*p/100n,i.push(`gasLimit includes a ${p}% buffer over the ${s} estimate`)}catch(h){i.push(`gas estimation failed: ${h?.message||"unknown"}`)}i.push("a pass reflects CURRENT chain state \u2014 it is not a guarantee the transaction lands, and in a contested mint the state changes between blocks");let d=`0x${"0".repeat(64)}`,m=c===d;return m&&i.push("call did not revert but returned boolean false \u2014 some ERC-20s (e.g. USDC) signal failure this way instead of reverting"),{status:"ok",willRevert:!1,returnsFalse:m,chainId:n,returnData:c,gasEstimate:s==null?null:s.toString(),gasLimit:l==null?null:l.toString(),summary:m?"executes but returns FALSE \u2014 the contract is rejecting this operation":s?`would succeed, ~${s} gas`:"would succeed",notes:i}}var Dr=Object.freeze([{selector:"a0712d68",signature:"mint(uint256)",args:["quantity"]},{selector:"40c10f19",signature:"mint(address,uint256)",args:["to","quantity"]},{selector:"1249c58b",signature:"mint()",args:[]},{selector:"2db11544",signature:"publicMint(uint256)",args:["quantity"]},{selector:"efef39a1",signature:"purchase(uint256)",args:["quantity"]},{selector:"a6f2ae3a",signature:"buy()",args:[]}]);function Gr(e){let t=BigInt(e).toString(16);if(t.length>64)throw new Error("value too large for a 32-byte word");return t.padStart(64,"0")}function Hr(e){let t=String(e).toLowerCase().replace(/^0x/,"");if(!/^[a-f0-9]{40}$/.test(t))throw new Error(`invalid address: ${e}`);return t.padStart(64,"0")}function ct(e,{minter:t,quantity:r}){let n=`0x${e.selector}`;for(let o of e.args)if(o==="to")n+=Hr(t);else if(o==="quantity")n+=Gr(r);else throw new Error(`unsupported mint argument: ${o}`);return n}function qr({address:e,chainId:t,minter:r,quantity:n,tx:o,nowMs:a,ttlMs:i=3e4}){if(!o?.gasLimit||!o?.maxFeePerGas)throw new Error("local-signer envelope requires gasLimit and maxFeePerGas");let c=Number(a??Date.now()),u=String(o.value??"0");return{version:1,surface:"evm-nft",action:"mint",provider:"nft-mint",owner:r,destination:e,contract:e,quantity:String(n),totalWei:u,slippageBps:0,expiresAtMs:c+Math.min(Math.max(Number(i)||3e4,1e3),6e4),fee:{oracleFeeBps:0},artifact:{chainId:t,owner:r,contract:e,quantity:String(n),totalWei:u,transactions:[{chainId:t,from:r,to:e,data:o.data,value:u,gasLimit:String(o.gasLimit),maxFeePerGas:String(o.maxFeePerGas),...o.maxPriorityFeePerGas!=null?{maxPriorityFeePerGas:String(o.maxPriorityFeePerGas),type:2}:{}}]}}}async function Wr(e={},t={}){let r=t.rpcCall||k,n=String(e.address||"").trim().toLowerCase(),o=Number(e.chainId);if(!/^0x[a-f0-9]{40}$/.test(n))return{status:"error",error:"address must be a 0x-prefixed EVM address",found:[]};if(!Number.isInteger(o))return{status:"error",error:"chainId is required",found:[]};let a;try{a=await r(o,"eth_getCode",[n,"latest"],t)}catch(u){return{status:"unavailable",error:u?.message||"eth_getCode failed",found:[]}}if(!a||a==="0x")return{status:"ok",found:[],notes:["no contract deployed at this address"]};let i=a.slice(2).toLowerCase(),c=Dr.filter(u=>i.includes(u.selector));return{status:"ok",address:n,chainId:o,found:c,notes:c.length?[]:["no known public mint selector found; this contract may use a custom or allowlist-only entrypoint"]}}async function me(e={},t={}){let r=String(e.contract||e.address||"").trim().toLowerCase(),n=Number(e.chainId),o=String(e.minter||e.from||"").trim().toLowerCase(),a=e.quantity==null?1:Number(e.quantity);if(!/^0x[a-f0-9]{40}$/.test(r))return{status:"error",error:"contract must be a 0x-prefixed EVM address"};if(!/^0x[a-f0-9]{40}$/.test(o))return{status:"error",error:"minter address is required"};if(!Number.isInteger(a)||a<1)return{status:"error",error:"quantity must be a positive integer"};if(!Number.isInteger(n))return{status:"error",error:"chainId is required"};let i=await Wr({address:r,chainId:n},t);if(i.status!=="ok")return{status:i.status,error:i.error};if(!i.found.length)return{status:"unsupported",error:"no known public mint function found in this contract's bytecode",notes:i.notes};let c=e.signature?i.found.find(y=>y.signature===e.signature):i.found[0];if(!c)return{status:"error",error:`requested signature ${e.signature} not present in this contract`,available:i.found.map(y=>y.signature)};let u=i.found.length>1&&!e.signature,f=await it({address:r,chainId:n},t),s=null;if(e.simulate!==!1&&(s=await st({chainId:n,tx:{from:o,to:r,data:ct(c,{minter:o,quantity:a}),value:e.valueWei},gasBufferPercent:e.gasBufferPercent},t),s.willRevert===!0&&e.ignoreRevert!==!0))return{status:"would-revert",error:`mint would revert: ${s.revert.reason}`,simulation:s,mintFunction:c.signature,notes:["signing this now would burn gas and fail; pass ignoreRevert to prepare anyway (e.g. a mint that has not opened yet)"]};let l=e.gasLimit??(s?.gasLimit?Number(s.gasLimit):null),d=await at({chainId:n,urgency:e.urgency||"war",gasLimit:l,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei,maxTotalGasWei:e.maxTotalGasWei},t);if(d.status!=="ok")return{status:"unavailable",error:d.error,notes:d.notes};let m;try{m=ct(c,{minter:o,quantity:a})}catch(y){return{status:"error",error:y.message}}let h={chainId:n,from:o,to:r,data:m,value:e.valueWei==null?"0":String(e.valueWei),gasLimit:l==null?null:String(l),maxFeePerGas:d.maxFeePerGas,maxPriorityFeePerGas:d.maxPriorityFeePerGas},p={ok:!0,skipped:!0,reason:"no gasLimit or cap supplied"};if(l!=null&&(e.maxTotalGasWei!=null||e.grant!=null)&&(p=nt({chainId:n,tx:{gasLimit:l,maxFeePerGas:d.maxFeePerGas,maxPriorityFeePerGas:d.maxPriorityFeePerGas},policy:{maxTotalGasWei:e.maxTotalGasWei,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei,grant:e.grant}}),!p.ok))return{status:"refused",error:`gas-war cap exceeded: ${p.reason||p.error}`,gas:d,capCheck:p};let g=[];u&&g.push(`contract exposes ${i.found.length} mint entrypoints (${i.found.map(y=>y.signature).join(", ")}); defaulted to ${c.signature} \u2014 pass signature to choose`),f.risk==="high"&&g.push(`contract risk HIGH: ${f.findings.map(y=>y.name).join(", ")}`),d.viable||g.push(d.notes[0]),p.skipped&&g.push("gas-war caps NOT enforced: supply gasLimit plus maxTotalGasWei or a grant");let b=null,T=null;try{b=qr({address:r,chainId:n,minter:o,quantity:a,tx:h,nowMs:t.nowMs,ttlMs:e.ttlMs??e.expiresInMs})}catch(y){T=String(y?.message||y).slice(0,200)}return{status:"ok",execution:b?"armed-local":"prepare-only",signed:b?"pending-local-signer":!1,broadcast:b?"pending-local-signer":!1,tx:h,localSignerEnvelope:b,localSignerBlockedReason:T,mintFunction:c.signature,alternatives:i.found.map(y=>y.signature),quantity:a,gas:d,simulation:s,contractRisk:{risk:f.risk,findings:f.findings,isProxy:f.isProxy},capCheck:p,warnings:g}}var Ro=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});function ut(e=process.env){return String(e.ORACLE_AUTONOMOUS_TRADING??"").trim()==="1"}function Ur(e={},{nowMs:t=Date.now()}={}){let r=[];if(!e||typeof e!="object")return{ok:!1,problems:["grant is required for execute mode"]};let n=String(e.contract||"").toLowerCase();if(/^0x[a-f0-9]{40}$/.test(n)||r.push("grant.contract must be an exact address"),Number.isInteger(Number(e.chainId))||r.push("grant.chainId is required"),e.maxTotalGasWei==null&&r.push("grant.maxTotalGasWei is required"),e.maxValueWei==null&&r.push("grant.maxValueWei is required (mint price ceiling)"),e.expiresAt!=null){let o=Number(e.expiresAt);Number.isFinite(o)?o<=t&&r.push("grant has expired"):r.push("grant.expiresAt must be a timestamp when supplied")}return{ok:r.length===0,problems:r,contract:n,chainId:Number(e.chainId)}}function lt(e={},t={}){let n=e.actionMode==="execute"?"execute":e.actionMode||"alert_only",o=String(e.contract||"").trim().toLowerCase(),a=Number(e.chainId),i=[];if(!/^0x[a-f0-9]{40}$/.test(o))return{status:"error",error:"contract must be a 0x-prefixed EVM address"};if(!Number.isInteger(a))return{status:"error",error:"chainId is required"};if(n!=="alert_only"&&n!=="execute")return{status:"ok",actionMode:"alert_only",requestedMode:n,downgraded:!0,contract:o,chainId:a,quantity:e.quantity==null?1:Number(e.quantity),urgency:e.urgency||"war",grant:null,notes:[`unrecognized actionMode ${JSON.stringify(n)} \u2014 defaulted to alert_only; only the exact string "execute" arms a trigger`]};let c=n;if(n==="execute")if(!ut(t.env||process.env))c="alert_only",i.push("DOWNGRADED to alert_only: autonomous trading is off \u2014 set ORACLE_AUTONOMOUS_TRADING=1 to let a trigger fire unattended");else{let u=Ur(e.grant,{nowMs:t.nowMs});u.ok?(u.contract!==o||u.chainId!==a)&&(c="alert_only",i.push("DOWNGRADED to alert_only: grant does not match this contract/chain \u2014 a grant authorizes one exact target")):(c="alert_only",i.push(`DOWNGRADED to alert_only: ${u.problems.join("; ")}`))}return c==="alert_only"?i.push("alert_only: Oracle will notify and prepare an artifact; you sign it"):i.push("ARMED until mint opens: this trigger will submit one prepared, capped mint automatically when the mint opens"),{status:"ok",actionMode:c,requestedMode:n,downgraded:c!==n,contract:o,chainId:a,quantity:e.quantity==null?1:Number(e.quantity),urgency:e.urgency||"war",grant:c==="execute"?e.grant:null,armedUntil:c==="execute"?"mint-opens":null,notes:i}}async function Pe(e={},t={}){let r=t.rpcCall||k,n=String(e.contract||"").trim().toLowerCase(),o=Number(e.chainId);if(!/^0x[a-f0-9]{40}$/.test(n)||!Number.isInteger(o))return{status:"error",open:!1,error:"contract and chainId are required"};let a=[{selector:"0xeb8d2444",name:"saleIsActive()",openWhen:!0},{selector:"0x25fd90f3",name:"mintActive()",openWhen:!0},{selector:"0x68428a1b",name:"saleActive()",openWhen:!0},{selector:"0x22f3e2d4",name:"isActive()",openWhen:!0},{selector:"0x5c975abb",name:"paused()",openWhen:!1}];for(let i of a)try{let c=await r(o,"eth_call",[{to:n,data:i.selector},"latest"],t);if(c&&c!=="0x"){let u=BigInt(c)===1n;return{status:"ok",open:i.openWhen?u:!u,evidence:i.name,raw:c}}}catch{}return{status:"unknown",open:!1,notes:["no readable sale-state flag; cannot confirm the mint is open \u2014 will not fire on a guess"]}}async function ft(e={},t={}){if(e.status!=="ok")return{status:"error",error:"invalid trigger"};let r=await Pe({contract:e.contract,chainId:e.chainId},t);if(!r.open)return{status:"waiting",open:!1,reason:r.notes?.[0]||`sale flag ${r.evidence||"unknown"} reports closed`};let n=await me({contract:e.contract,chainId:e.chainId,minter:e.minter||t.minter,quantity:e.quantity,urgency:e.urgency,gasLimit:e.gasLimit??t.gasLimit,maxTotalGasWei:e.grant?.maxTotalGasWei??e.maxTotalGasWei??t.maxTotalGasWei,maxFeePerGasWei:e.maxFeePerGasWei??t.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei??t.maxPriorityFeePerGasWei,valueWei:e.valueWei??t.valueWei,grant:e.grant},t);if(n.status!=="ok")return{status:"blocked",open:!0,reason:n.error,prepared:n};if(e.actionMode==="execute"&&e.grant?.maxValueWei!=null){let o=BigInt(n.tx.value||"0");if(o>BigInt(e.grant.maxValueWei))return{status:"refused",open:!0,reason:`mint price ${o} exceeds granted maxValueWei ${e.grant.maxValueWei}`,prepared:n}}return{status:e.actionMode==="execute"?"fire":"alert",open:!0,actionMode:e.actionMode,prepared:n,signed:!1}}var Lo=Object.freeze([{selector:"0xeb8d2444",name:"saleIsActive()",openWhen:!0},{selector:"0x25fd90f3",name:"mintActive()",openWhen:!0},{selector:"0x68428a1b",name:"saleActive()",openWhen:!0},{selector:"0x22f3e2d4",name:"isActive()",openWhen:!0},{selector:"0x5c975abb",name:"paused()",openWhen:!1}]),v=Object.freeze({BUILDER_AUCTION:"builder-auction",OP_STACK_SEQUENCER:"op-stack-sequencer",NITRO_FCFS:"nitro-fcfs",HYPERBFT:"hyperbft",SOLANA_LEADER:"solana-leader",BITCOIN_FEE_RATE:"bitcoin-fee-rate"}),Vr=Object.freeze({1:{chain:"Ethereum",regime:v.BUILDER_AUCTION},137:{chain:"Polygon",regime:v.BUILDER_AUCTION},56:{chain:"BNB Chain",regime:v.BUILDER_AUCTION},43114:{chain:"Avalanche C-Chain",regime:v.BUILDER_AUCTION},988:{chain:"Stable Mainnet",regime:v.BUILDER_AUCTION},8453:{chain:"Base",regime:v.OP_STACK_SEQUENCER},10:{chain:"OP Mainnet",regime:v.OP_STACK_SEQUENCER},7777777:{chain:"Zora",regime:v.OP_STACK_SEQUENCER},81457:{chain:"Blast",regime:v.OP_STACK_SEQUENCER},42161:{chain:"Arbitrum One",regime:v.NITRO_FCFS},4663:{chain:"Robinhood Chain",regime:v.NITRO_FCFS},2741:{chain:"Abstract",regime:v.NITRO_FCFS},999:{chain:"HyperEVM",regime:v.HYPERBFT}}),zr=Object.freeze({solana:{chain:"Solana",regime:v.SOLANA_LEADER},bitcoin:{chain:"Bitcoin",regime:v.BITCOIN_FEE_RATE},ordinals:{chain:"Bitcoin Ordinals",regime:v.BITCOIN_FEE_RATE}}),Jr=Object.freeze({[v.BUILDER_AUCTION]:{ordering:"builder-auction",lever:"priority-fee",priorityFeeHelps:!0,latencyDecides:!1,privateRelayAvailable:!0,subSecondRace:!0,notes:["inclusion is bought through the block builder auction","priority fee is the lever that actually moves position","a private relay hides the transaction from the public mempool and avoids being front-run"]},[v.OP_STACK_SEQUENCER]:{ordering:"sequencer",lever:"priority-fee+latency",priorityFeeHelps:!0,latencyDecides:!0,privateRelayAvailable:!1,subSecondRace:!0,notes:["the sequencer mempool orders by effective gas price, so paying more does move you forward","arrival time still matters within a fee tier, so latency and fee are both live levers","there is no public builder auction to bid into and no private relay to hide in"]},[v.NITRO_FCFS]:{ordering:"sequencer",lever:"latency",priorityFeeHelps:!1,latencyDecides:!0,privateRelayAvailable:!1,subSecondRace:!0,notes:["Nitro timestamps by arrival order; fees do not reorder the sequencer queue","raw round-trip time is the only lever that changes position","co-locate near the sequencer endpoint rather than raising gas"]},[v.HYPERBFT]:{ordering:"consensus",lever:"latency",priorityFeeHelps:!1,latencyDecides:!0,privateRelayAvailable:!1,subSecondRace:!0,notes:["HyperBFT consensus orders transactions; there is no public builder auction to bid into","reaching a validator early is the lever, not paying more","block times are sub-second, so a slow RPC path costs whole blocks"]},[v.SOLANA_LEADER]:{ordering:"leader",lever:"priority-fee+latency",priorityFeeHelps:!0,latencyDecides:!0,privateRelayAvailable:!0,subSecondRace:!0,notes:["there is no mempool: transactions are sent to the current and next slot leaders","compute-unit price is the fee lever; Jito bundles are the private-inclusion path","landing depends on reaching the leader in time, so both levers are live"]},[v.BITCOIN_FEE_RATE]:{ordering:"fee-rate",lever:"fee-rate",priorityFeeHelps:!0,latencyDecides:!1,privateRelayAvailable:!1,subSecondRace:!1,notes:["inclusion is fee-rate against roughly ten-minute blocks, not a sub-second race","being milliseconds earlier does not change inclusion; sat/vB estimation does","a co-located executor buys nothing here \u2014 this is a fee-estimation problem"]}});function dt(e){let t=e&&typeof e=="object"?e.chainId??e.family??e.chain:e,r=String(t??"").trim().toLowerCase(),n=zr[r]||Vr[Number(t)];if(!n)return{chainId:Number.isInteger(Number(t))?Number(t):null,chain:null,regime:null,ordering:"unknown",lever:"unknown",priorityFeeHelps:null,latencyDecides:null,privateRelayAvailable:!1,subSecondRace:null,notes:["chain ordering not classified; treat inclusion strategy as unverified"]};let o=Jr[n.regime];return{chainId:Number.isInteger(Number(t))?Number(t):null,chain:n.chain,regime:n.regime,...o,notes:[...o.notes]}}var Bo=Object.freeze({"0x02c88989":"setSaleIsActive(bool)","0x34918dfd":"flipSaleState()","0x5a67de07":"setSaleState(uint8)","0x3f4ba83a":"unpause()","0x16c38b3c":"setPaused(bool)","0xb66a0e5d":"startSale()","0xee1cc944":"setMintActive(bool)"});function Kr(e){let t=dt(e);return t.regime==="nitro-fcfs"?{visible:!1,reason:"Arbitrum orders at a private sequencer; there is no public pending pool to watch"}:t.regime==="op-stack-sequencer"?{visible:!1,reason:"the OP-stack sequencer holds pending transactions privately; public mempool watching will not see the opening transaction"}:t.regime==="solana-leader"?{visible:!1,reason:"Solana has no mempool; transactions go straight to the slot leader"}:t.regime==="hyperbft"?{visible:!1,reason:"HyperBFT orders through validator consensus; there is no public pending pool to watch"}:t.regime==="bitcoin-fee-rate"?{visible:!1,reason:"Bitcoin inclusion is fee-rate over ten-minute blocks, so there is no sub-second opening to detect"}:t.regime==="builder-auction"?{visible:!0,reason:"public mempool is observable, though private-relay transactions will not appear in it"}:{visible:!1,reason:"chain ordering not classified; mempool visibility unverified"}}function pt(e){let t=Kr(e);return{chainId:Number(e),mempoolVisible:t.visible,reason:t.reason,fallback:t.visible?null:"poll sale state with probeMintOpenFast"}}import{existsSync as _n,readFileSync as Nn}from"node:fs";import{request as kn}from"node:http";import Cn from"node:path";import he from"node:fs";import Yr from"node:os";import Z from"node:path";import{fileURLToPath as Xr}from"node:url";var Zr=Z.dirname(Xr(import.meta.url)),Wo=Z.resolve(Zr,"../..");function mt(){return process.env.ORACLE_FAKE_HOME||Yr.homedir()}function Qr(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function ge(){return Qr()?process.env.ORACLE_CONFIG_DIR||Z.join(mt(),".config","oracle"):Z.join(mt(),".config","oracle")}function en(){return Z.join(ge(),"desk.json")}function tn(){return Z.join(ge(),"env")}function X({force:e=!1}={}){if(X._done&&!e)return X._result||null;X._done=!0;let t={},r=(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,t[o]=i))};try{let o=tn();if(he.existsSync(o))for(let a of he.readFileSync(o,"utf8").split(/\r?\n/)){let i=a.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let c=i[2];(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),r(i[1],c)}}catch{}try{let o=en();if(he.existsSync(o)){let a=JSON.parse(he.readFileSync(o,"utf8"));a&&typeof a=="object"&&(r("ORACLE_DESK_URL",a.deskUrl||a.dataUrl||a.url),r("ORACLE_DATA_URL",a.dataUrl||a.deskUrl||a.url),r("ORACLE_API_URL",a.apiUrl||a.dataUrl||a.deskUrl),r("ORACLE_PUBLIC_URL",a.publicUrl||a.deskUrl||a.dataUrl),r("ORACLE_EXEC_URL",a.execUrl),r("MAD_DESK_URL",a.deskUrl||a.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),X._result=Object.keys(t).length?t:null,X._result}try{X()}catch{}import{createHash as bn}from"node:crypto";var rn=/^0x[0-9a-f]{40}$/,nn=/^0x(?:[0-9a-f]{2})*$/,on=/^(?:0x)?[0-9a-f]{64}$/,an=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,sn=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,cn=new Set([12,15,18,21,24]),we=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}};function _e(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(sn.test(e)||cn.has(o.length)&&o.every(a=>/^[a-z]+$/i.test(a)))throw new we(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,a)=>_e(o,`${t}[${a}]`,r));J(e,t);let n={};for(let o of Object.keys(e).sort()){let a=o.replace(/[^a-z0-9]/gi,"");if(an.test(a))throw new we(`${t}.${o}`);e[o]!==void 0&&(n[o]=_e(e[o],`${t}.${o}`,o))}return n}function J(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function se(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function Q(e,t){let r=String(se(e,t)).toLowerCase();if(!rn.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function j(e,t,{positive:r=!1}={}){try{let n=BigInt(se(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function Ne(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function ht(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))ht(t);Object.freeze(e)}return e}function un(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};J(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:Ne(String(n),`${t}.reason`)}}function ln(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>un(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function fn(e){if(e==null)return null;if(J(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:Ne(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=j(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=j(e.gasLimit,"simulation.gasLimit")),t}function dn(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{J(t,`assetDeltas[${r}]`);let n=j(t.before,`assetDeltas[${r}].before`),o=j(t.after,`assetDeltas[${r}].after`),a=(BigInt(o)-BigInt(n)).toString(),i;try{i=t.delta==null?a:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(i!==a)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:Ne(String(se(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:i}})}function pn(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{J(t,`approvalDeltas[${r}]`);let n=j(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:Q(t.token,`approvalDeltas[${r}].token`),spender:Q(t.spender,`approvalDeltas[${r}].spender`),owner:Q(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function gt(e={}){J(e,"input");let t=_e(e),r=t.tx==null?t:J(t.tx,"tx"),n=j(t.chainId??r.chainId,"chainId",{positive:!0}),o=Q(t.account??t.from??r.from,"account/from"),a=Q(t.destination??t.to??r.to,"destination/to"),i=String(se(t.prepareHash,"prepareHash")).toLowerCase();if(!on.test(i))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let c=t.route??t.venue;if(c==null)throw new TypeError("sign-time review: route/venue required");let u=t.decodedCalldata??t.decodedAction;if(u==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let f=String(se(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!nn.test(f))throw new TypeError("sign-time review: calldata/data must be even-length hex");let s=t.policyChecks!==void 0&&t.policyChecks!==null,l=ln(s?t.policyChecks:[]),d=fn(t.simulation),m=dn(t.assetDeltas),h=pn(t.approvalDeltas),p=t.allowlistHits??[];if(!Array.isArray(p))throw new TypeError("sign-time review: allowlistHits must be an array");let g=d?.willRevert===!0||["failed","error"].includes(d?.status),b=d!=null&&d.willRevert===!1&&["ok","success"].includes(d.status),T=g||l.failed>0?"BLOCKED":b&&s&&l.checks.length>0&&m!=null?"READY":"UNKNOWN",y=typeof u=="string"?u:u.method??u.action??u.type??"transaction",_=`${T}: review ${y} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${m?.length??0} asset delta${m?.length===1?"":"s"}; local signature required`,C={reviewVersion:1,status:T,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:c,venue:t.venue??(typeof c=="string"?c:c.venue??c.provider??null),destination:a,to:a,...t.spender==null?{}:{spender:Q(t.spender,"spender")},prepareHash:i,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:f,data:f,selector:f.length>=10?f.slice(0,10):null,value:j(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:j(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:j(t.gasLimit??r.gasLimit,"gasLimit")},simulation:d,policyChecks:l,allowlistHits:p,assetDeltas:m,approvalDeltas:h,summary:_};return ht(C)}import{createHash as mn,createHmac as hn,timingSafeEqual as Jo}from"node:crypto";var Ko=300*1e3,Yo=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function ke(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(ke).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${ke(e[r])}`).join(",")}}`}function wt(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function gn(e=process.env){return wt(process.env)||wt(e)}function wn(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function bt(e){let t=wn(e);return mn("sha256").update(ke(t)).digest("hex")}function yt(e,t=gn()){return t?hn("sha256",t).update(String(e)).digest("hex"):""}var xt=1,Et="prepare-verification";var Ce=Object.freeze({NONE:"none",PREPARE_CHECKSUM:"prepare-checksum",PREPARE_HMAC:"prepare-hmac"}),yn=/^(?:0x)?[0-9a-f]{64}$/i,xn=Object.freeze(["signature","signedTx","signedTransaction","rawTransaction","signedPayload","signedRaw"]),En=Object.freeze(["txid","txHash","transactionHash","broadcastHash"]),Sn=Object.freeze(["tee-attestation","remote-attestation","hardware-enclave","trusted-execution-environment","execution-authorization","signature","broadcast"]);function K(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))K(t);Object.freeze(e)}return e}function ee(e,t){if(e==null||typeof e!="object"||Array.isArray(e))throw new TypeError(`prepare verification: ${t} must be an object`);return e}function $e(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map($e).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${$e(e[r])}`).join(",")}}`}function St(e){return bn("sha256").update($e(e),"utf8").digest("hex")}function vn(e,t,r=500){let o=(e==null?t:String(e)).trim();return o?o.slice(0,r):t}function An(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function ce(e){let t=String(e||"").trim().toLowerCase().replace(/^0x/,"");return yn.test(t)?t:""}function vt(e){if(e?.transaction&&typeof e.transaction=="object")return e.transaction;if(e?.tx&&typeof e.tx=="object")return e.tx;let t=e?.localSignerEnvelope||e?.envelope;return t?.artifact&&typeof t.artifact=="object"?t.artifact:e}function At(e,t="prepare verification"){if(ee(e,"prepared"),e.signed===!0)throw new Error(`${t}: prepared fact is signed`);if(e.broadcast===!0)throw new Error(`${t}: prepared fact claims broadcast`);for(let r of xn)if(e[r])throw new Error(`${t}: prepared fact carries ${r}`);for(let r of En)if(e[r])throw new Error(`${t}: prepared fact claims executed ${r}`);return!0}function Tn(e){if(e==null)return K({status:"unavailable",willRevert:null,summary:"no simulation supplied",source:"unavailable"});ee(e,"simulation");let t=String(e.status||(e.willRevert===!0?"failed":e.ok===!1?"error":"unknown")),r=["ok","success","failed","error","unavailable","unknown"].includes(t)?t:"unknown",n=e.willRevert===!0||e.willRevert===!1?e.willRevert:null;return K({status:r,willRevert:n,summary:vn(e.summary||e.reason||e.error,"simulation result recorded"),source:e.source==="dry-run"||e.source==="supplied"||e.source==="unavailable"?e.source:"supplied",...e.gasEstimate!=null?{gasEstimate:String(e.gasEstimate)}:{},...e.gasLimit!=null?{gasLimit:String(e.gasLimit)}:{}})}function In(e={},t={}){let r=vt(e),n=e.localSignerEnvelope||e.envelope||{},o=t.provider||e.provider||e.source||n.provider||t.venue||e.venue||"unknown",a=t.kind||e.kind||e.artifactKind||n.action||e.action||"prepare",i=t.destination||e.destination||e.to||r?.to||n.destination||null,c=t.chainId??e.chainId??r?.chainId??n.chainId??null,u=t.account||e.account||e.from||r?.from||n.owner||null,f=[`Unsigned ${a} via ${o}`];return i&&f.push(`to ${i}`),c!=null&&c!==""&&f.push(`on chain ${c}`),t.note&&f.push(String(t.note)),f.push("for owner review only \u2014 not signed, not armed, not executed"),K({summary:f.join(" "),provider:String(o),kind:String(a),destination:i==null?null:String(i),chainId:c==null||c===""?null:String(c),account:u==null?null:String(u)})}function On({prepared:e={},env:t}={}){ee(e,"prepared");let r=ce(e.prepareHash),n=typeof e.prepareMac=="string"&&e.prepareMac.length>=32,o=!1;if(r)try{o=bt(e)===String(e.prepareHash)}catch{o=!1}let a=!1,i=An(t);if(n&&i&&r)try{let s=yt(r,i);a=s.length>0&&s===String(e.prepareMac)}catch{a=!1}let c=n?Ce.PREPARE_HMAC:r?Ce.PREPARE_CHECKSUM:Ce.NONE,u=[];r&&u.push(o?"prepare-body-sha256-bound":"prepare-hash-present-unverified"),n&&u.push(a?"keyed-prepare-mac-verified":"keyed-prepare-mac-present-unverified");let f=a?"Keyed prepare MAC verified. This is integrity provenance, not TEE attestation or execution authority.":o?"Public prepare checksum only. Not provenance. Not TEE attested. Not an execution grant.":"No verified prepare integrity stamp. Simulation and intent are operator-visible facts only.";return K({kind:c,teeAttested:!1,cryptographicallyAttested:a,checksumBound:o,claims:u,notClaimed:[...Sn],custody:"none",execution:"prepare-only",note:f})}function Rn(e,t,r){let n=vt(e),o=e.localSignerEnvelope||e.envelope||{};try{let a=gt({chainId:e.chainId??n?.chainId??o.chainId,account:e.account||e.from||n?.from||o.owner,destination:e.destination||e.to||n?.to||o.destination,calldata:e.calldata||e.data||n?.data||"0x",value:e.value??n?.value??0,prepareHash:t,route:e.provider||e.venue||o.provider||o.surface||"prepare",decodedAction:e.kind||e.action||o.action||"transaction",simulation:r,...e.policyChecks?{policyChecks:e.policyChecks}:{}});return K({status:a.status,summary:a.summary,requiresLocalSignature:!0,custody:a.custody,execution:a.execution})}catch{return null}}function Pn({prepared:e,simulation:t,intent:r,env:n,nowMs:o=Date.now()}={}){ee(e,"prepared"),At(e);let a=Number(o);if(!Number.isSafeInteger(a)||a<=0)throw new TypeError("prepare verification: bounded createdAt required");let i=Tn(t??e.simulation??e.sim),c=In(e,r&&typeof r=="object"?r:{}),u=On({prepared:e,env:n}),f=ce(e.prepareHash)||null,s=f?Rn(e,f,i):null,l={version:xt,kind:Et,prepareHash:f,simulation:i,intent:c,intentSummary:c.summary,attestation:u,review:s,custody:"none",execution:"prepare-only",signingReady:!1,broadcastReady:!1,executionReady:!1,createdAt:a};return K({...l,artifactHash:St(l)})}function Tt(e,t={}){let r=t.label||"prepare verification";if(ee(e,"artifact"),Number(e.version)!==xt)throw new Error(`${r}: unsupported verification artifact version`);if(e.kind!==Et)throw new Error(`${r}: verification artifact kind required`);if(e.custody!=="none")throw new Error(`${r}: verification artifact custody must be none`);if(e.execution!=="prepare-only")throw new Error(`${r}: verification artifact must stay prepare-only`);if(e.signingReady===!0||e.broadcastReady===!0||e.executionReady===!0)throw new Error(`${r}: verification artifact must not claim a ready execution flag`);if(e.attestation?.teeAttested===!0)throw new Error(`${r}: TEE attestation is not claimed or accepted`);if(!["ok","success","failed","error","unavailable","unknown"].includes(String(e.simulation?.status||"")))throw new Error(`${r}: simulation status required`);if(typeof e.intentSummary!="string"||!e.intentSummary.trim())throw new Error(`${r}: human-readable intent summary required`);if(!e.attestation||typeof e.attestation!="object")throw new Error(`${r}: attestation record required`);if(!Array.isArray(e.attestation.notClaimed)||!e.attestation.notClaimed.includes("tee-attestation"))throw new Error(`${r}: attestation must honestly exclude TEE claims`);let{artifactHash:n,...o}=e;if(ce(n)!==St(o))throw new Error(`${r}: artifactHash mismatch \u2014 verification artifact was altered`);if(t.prepareHash){let a=ce(t.prepareHash),i=ce(e.prepareHash);if(!a||a!==i)throw new Error(`${r}: verification artifact does not bind this prepare`)}return e}function It(e,t={}){ee(e,"prepared");let r=t.artifact&&typeof t.artifact=="object"?t.artifact:Pn({prepared:e,simulation:t.simulation,intent:t.intent,env:t.env,nowMs:t.nowMs});return Tt(r,{label:t.label||"prepare verification"}),{...e,prepareVerification:r}}function Ot(e,t={}){let r=t.label||"armPreparedAction";if(!e||typeof e!="object")throw new Error(`${r}: prepared object required`);let n=e.prepareVerification||e.verificationArtifact||e.deskCheckpoint?.prepareVerification||t.checkpoint?.prepareVerification;if(!n)throw new Error(`${r}: prepare verification artifact required before arm`);return Tt(n,{label:r,...e.prepareHash?{prepareHash:e.prepareHash}:{}}),At(e,r),n}var $n="http://127.0.0.1:9462";function Ln(e=process.env){let t=String(e.ORACLE_SIGNER_URL||$n).replace(/\/$/,""),r;try{r=new URL(t)}catch{return null}return r.hostname!=="127.0.0.1"&&r.hostname!=="localhost"&&r.hostname!=="::1"?null:r.origin}function Mn(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=Cn.join(ge(),"signer","signer-token");return _n(t)?Nn(t,"utf8").trim():null}function Fn(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let a=Ln(n),i=Mn(n);return!a||!i?Promise.resolve({ok:!1,error:"local signer is not running"}):new Promise(c=>{let u=new URL(e,a),f=r?Buffer.from(JSON.stringify(r)):null,s=kn({hostname:u.hostname,port:u.port||80,path:u.pathname,method:t,timeout:o,headers:{authorization:`Bearer ${i}`,origin:a,...f?{"content-type":"application/json","content-length":f.length}:{}}},l=>{let d=[];l.on("data",m=>d.push(m)),l.on("end",()=>{let m=Buffer.concat(d).toString("utf8"),h={};try{h=m?JSON.parse(m):{}}catch{h={error:"signer refused"}}c({httpStatus:l.statusCode,...h})})});s.on("timeout",()=>{s.destroy(),c({ok:!1,error:"local signer timed out"})}),s.on("error",()=>c({ok:!1,error:"local signer is not running"})),f&&s.write(f),s.end()})}async function Bn(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return Fn("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function Rt(e,t=process.env){let r=e?.localSignerEnvelope||e?.envelope;if(!r||r.version!==1||!r.surface)throw new Error("armPreparedAction: prepared.localSignerEnvelope v1 required");return Ot(e,{env:t,label:"armPreparedAction"}),Bn(r,t)}import{Interface as Hn,MaxUint256 as Ha,isAddress as qa,keccak256 as Wa,toUtf8Bytes as Ua}from"ethers";import{Interface as Dn,isAddress as Sa}from"ethers";import{isAddress as ga}from"ethers";var Ia=new Dn(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Gn,isAddress as Pa}from"ethers";var Ca=new Gn(["function approve(address spender,uint256 amount) returns (bool)"]),$a=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var Xa=new Hn(["function approve(address spender,uint256 amount) returns (bool)"]);var qn=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function Pt(e){try{return qn.has(BigInt(e))}catch{return!1}}var Nt=`oracle mint <watch|check|prepare> <contract> --chain <id> [options]
5
5
 
6
6
  oracle mint check <contract> --chain <id> [--rpc-url <url>] [--json]
7
7
  oracle mint prepare <contract> --chain <id> --minter <address> --max-total-gas-wei <wei> [--rpc-url <url>] [--queue] [--json]
@@ -12,11 +12,11 @@ Safe posture:
12
12
  --queue sends one prepared envelope to the loopback local signer for owner approval
13
13
  this command never signs or broadcasts
14
14
  --execute, --arm, and --fire are refused because autonomous trigger attestation minting is not shipped
15
- `,Ot=/^0x[0-9a-fA-F]{40}$/,Mn=["--execute","--arm","--fire"];function L(e,t){let r=e.indexOf(t);return r>=0?e[r+1]:void 0}function Fn(e){let t=e.reduce((o,a,i)=>a==="--rpc-url"?[...o,i]:o,[]);if(t.length===0)return;if(t.length!==1)throw new Error("--rpc-url must be specified exactly once");let r=String(e[t[0]+1]||"");if(r!==r.trim())throw new Error("--rpc-url must not contain surrounding whitespace");let n;try{n=new URL(r)}catch{throw new Error("--rpc-url must be an HTTP or HTTPS URL")}if(!["http:","https:"].includes(n.protocol))throw new Error("--rpc-url must be an HTTP or HTTPS URL");return r}function te(e,t,{optional:r=!1,min:n=0}={}){if(r&&e==null)return;let o=String(e??"");if(!/^(0|[1-9][0-9]*)$/.test(o)||BigInt(o)<BigInt(n))throw new Error(`${t} must be an integer >= ${n}`);return o}function Bn(e,{requireMinter:t=!1}={}){let r=String(e[1]||"").trim().toLowerCase(),n=Number(L(e,"--chain")),o=String(L(e,"--minter")||"").trim().toLowerCase();if(!Ot.test(r))throw new Error("contract must be a 0x-prefixed EVM address");if(!Number.isSafeInteger(n)||n<=0)throw new Error("--chain must be a positive integer");if(t&&!Ot.test(o))throw new Error("--minter must be a 0x-prefixed EVM address");return{contract:r,chainId:n,...t?{minter:o}:{},quantity:Number(te(L(e,"--quantity")??"1","quantity",{min:1})),urgency:L(e,"--urgency")||"war",signature:L(e,"--signature"),valueWei:te(L(e,"--value-wei"),"valueWei",{optional:!0}),gasLimit:te(L(e,"--gas-limit"),"gasLimit",{optional:!0,min:1}),maxTotalGasWei:te(L(e,"--max-total-gas-wei"),"maxTotalGasWei",{optional:!0,min:1}),maxFeePerGasWei:te(L(e,"--max-fee-per-gas-wei"),"maxFeePerGasWei",{optional:!0,min:1}),maxPriorityFeePerGasWei:te(L(e,"--max-priority-fee-per-gas-wei"),"maxPriorityFeePerGasWei",{optional:!0})}}function Le(e,t={}){return{...e,...t,broadcast:!1}}function Me(e,t,r){e.write(`${JSON.stringify(t,null,r?0:2)}
16
- `)}var jn={createTrigger:st,evaluateTrigger:ct,checkOpen:Re,prepare:de,queuePrepared:Tt,mempoolSupport:lt,isRollup:It};async function Dn(e=[],{out:t=process.stdout,err:r=process.stderr,env:n=process.env,deps:o={}}={}){let a=Mn.find(s=>e.includes(s));if(a)return r.write(`oracle mint: ${a} refused; autonomous trigger attestation minting is not shipped
17
- `),1;if(e.length===0||["--help","-h","help"].includes(e[0]))return t.write(Rt),0;let i={...jn,...o},c=e[0],u=e.includes("--json"),f=e.includes("--queue");try{if(!["watch","check","prepare"].includes(c))return r.write(`oracle mint: unknown verb '${c}'. Try: oracle mint --help
18
- `),1;let s=Bn(e,{requireMinter:c!=="check"}),l=Fn(e),d={env:n,...l?{rpcUrl:l}:{}};if(f&&s.maxTotalGasWei==null)return r.write(`oracle mint: --max-total-gas-wei is required before --queue
15
+ `,_t=/^0x[0-9a-fA-F]{40}$/,Wn=["--execute","--arm","--fire"];function L(e,t){let r=e.indexOf(t);return r>=0?e[r+1]:void 0}function Un(e){let t=e.reduce((o,a,i)=>a==="--rpc-url"?[...o,i]:o,[]);if(t.length===0)return;if(t.length!==1)throw new Error("--rpc-url must be specified exactly once");let r=String(e[t[0]+1]||"");if(r!==r.trim())throw new Error("--rpc-url must not contain surrounding whitespace");let n;try{n=new URL(r)}catch{throw new Error("--rpc-url must be an HTTP or HTTPS URL")}if(!["http:","https:"].includes(n.protocol))throw new Error("--rpc-url must be an HTTP or HTTPS URL");return r}function te(e,t,{optional:r=!1,min:n=0}={}){if(r&&e==null)return;let o=String(e??"");if(!/^(0|[1-9][0-9]*)$/.test(o)||BigInt(o)<BigInt(n))throw new Error(`${t} must be an integer >= ${n}`);return o}function Vn(e,{requireMinter:t=!1}={}){let r=String(e[1]||"").trim().toLowerCase(),n=Number(L(e,"--chain")),o=String(L(e,"--minter")||"").trim().toLowerCase();if(!_t.test(r))throw new Error("contract must be a 0x-prefixed EVM address");if(!Number.isSafeInteger(n)||n<=0)throw new Error("--chain must be a positive integer");if(t&&!_t.test(o))throw new Error("--minter must be a 0x-prefixed EVM address");return{contract:r,chainId:n,...t?{minter:o}:{},quantity:Number(te(L(e,"--quantity")??"1","quantity",{min:1})),urgency:L(e,"--urgency")||"war",signature:L(e,"--signature"),valueWei:te(L(e,"--value-wei"),"valueWei",{optional:!0}),gasLimit:te(L(e,"--gas-limit"),"gasLimit",{optional:!0,min:1}),maxTotalGasWei:te(L(e,"--max-total-gas-wei"),"maxTotalGasWei",{optional:!0,min:1}),maxFeePerGasWei:te(L(e,"--max-fee-per-gas-wei"),"maxFeePerGasWei",{optional:!0,min:1}),maxPriorityFeePerGasWei:te(L(e,"--max-priority-fee-per-gas-wei"),"maxPriorityFeePerGasWei",{optional:!0})}}function Me(e,t={}){return{...e,...t,broadcast:!1}}function Fe(e,t,r){e.write(`${JSON.stringify(t,null,r?0:2)}
16
+ `)}var zn={createTrigger:lt,evaluateTrigger:ft,checkOpen:Pe,prepare:me,queuePrepared:Rt,mempoolSupport:pt,isRollup:Pt};async function Jn(e=[],{out:t=process.stdout,err:r=process.stderr,env:n=process.env,deps:o={}}={}){let a=Wn.find(s=>e.includes(s));if(a)return r.write(`oracle mint: ${a} refused; autonomous trigger attestation minting is not shipped
17
+ `),1;if(e.length===0||["--help","-h","help"].includes(e[0]))return t.write(Nt),0;let i={...zn,...o},c=e[0],u=e.includes("--json"),f=e.includes("--queue");try{if(!["watch","check","prepare"].includes(c))return r.write(`oracle mint: unknown verb '${c}'. Try: oracle mint --help
18
+ `),1;let s=Vn(e,{requireMinter:c!=="check"}),l=Un(e),d={env:n,...l?{rpcUrl:l}:{}};if(f&&s.maxTotalGasWei==null)return r.write(`oracle mint: --max-total-gas-wei is required before --queue
19
19
  `),1;if(f&&i.isRollup(s.chainId))return r.write(`oracle mint: queue refused on rollups because the prepared envelope does not yet carry required l1FeeWei and operatorFeeWei attestations
20
- `),1;if(c==="check"){let g=await i.checkOpen({contract:s.contract,chainId:s.chainId},d);return Me(t,Le({status:g.status,sale:g,mempool:i.mempoolSupport(s.chainId),queued:!1}),u),0}let m;if(c==="prepare"){let g=await i.prepare(s,d);m={status:g?.status||(g?.localSignerEnvelope?"ok":"error"),prepared:g,signed:!1}}else{let g=i.createTrigger({...s,actionMode:"alert_only"},{env:n});m=await i.evaluateTrigger(g,{...d,minter:s.minter,...s})}if(!f||!["alert","fire","ok"].includes(m?.status))return Me(t,Le(m||{status:"error"},{queued:!1}),u),0;let h=m.prepared,p=await i.queuePrepared(vt(h,{simulation:h?.simulation,env:n}),n);return p?.ok!==!0?(r.write(`oracle mint: ${p?.error||"local signer refused the pending mint"}
21
- `),1):(Me(t,Le(m,{queued:!0,queue:p}),u),0)}catch(s){return r.write(`oracle mint: ${s?.message||s}
22
- `),1}}var Za={name:"mint",summary:"evaluate and queue one bounded mint for local owner approval; never signs or broadcasts",usage:Rt,run:e=>Dn(e.argv||[])};export{Za as default,Dn as runMintCommand};
20
+ `),1;if(c==="check"){let g=await i.checkOpen({contract:s.contract,chainId:s.chainId},d);return Fe(t,Me({status:g.status,sale:g,mempool:i.mempoolSupport(s.chainId),queued:!1}),u),0}let m;if(c==="prepare"){let g=await i.prepare(s,d);m={status:g?.status||(g?.localSignerEnvelope?"ok":"error"),prepared:g,signed:!1}}else{let g=i.createTrigger({...s,actionMode:"alert_only"},{env:n});m=await i.evaluateTrigger(g,{...d,minter:s.minter,...s})}if(!f||!["alert","fire","ok"].includes(m?.status))return Fe(t,Me(m||{status:"error"},{queued:!1}),u),0;let h=m.prepared,p=await i.queuePrepared(It(h,{simulation:h?.simulation,env:n}),n);return p?.ok!==!0?(r.write(`oracle mint: ${p?.error||"local signer refused the pending mint"}
21
+ `),1):(Fe(t,Me(m,{queued:!0,queue:p}),u),0)}catch(s){return r.write(`oracle mint: ${s?.message||s}
22
+ `),1}}var ui={name:"mint",summary:"evaluate and queue one bounded mint for local owner approval; never signs or broadcasts",usage:Nt,run:e=>Jn(e.argv||[])};export{ui as default,Jn as runMintCommand};