@oracle-agent/oracle 0.35.44 → 0.35.46

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 (80) hide show
  1. package/dist/agent-sessions.mjs +24 -24
  2. package/dist/artifacts/token-dashboard.mjs +1 -0
  3. package/dist/assets/graphics/oracle_card.py +60 -0
  4. package/dist/assets/graphics/pnl-samples.mjs +22 -0
  5. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  6. package/dist/assets/skills/web-research.md +6 -2
  7. package/dist/automation-plan.d.mts +63 -0
  8. package/dist/automation-plan.mjs +1 -0
  9. package/dist/bin/desk-server.mjs +30 -30
  10. package/dist/bin/oracle-data-mcp.mjs +20 -19
  11. package/dist/bin/oracle-gateway.mjs +48 -47
  12. package/dist/bin/oracle-investigate.mjs +4 -4
  13. package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
  14. package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
  15. package/dist/bin/oracle-mev-shadow.mjs +6 -6
  16. package/dist/bin/oracle-public-server.mjs +5 -5
  17. package/dist/bin/oracle-route.mjs +24 -24
  18. package/dist/bin/oracle-scan.mjs +7 -7
  19. package/dist/bin/oracle-telegram-mcp.mjs +13 -12
  20. package/dist/bin/oracle.mjs +1 -0
  21. package/dist/chains.mjs +1 -1
  22. package/dist/cli/commands/account.mjs +39 -0
  23. package/dist/cli/commands/agent-session.mjs +23 -23
  24. package/dist/cli/commands/airdrop.mjs +7 -7
  25. package/dist/cli/commands/chat.mjs +214 -212
  26. package/dist/cli/commands/data.mjs +34 -34
  27. package/dist/cli/commands/doctor.mjs +7 -7
  28. package/dist/cli/commands/eval.mjs +136 -135
  29. package/dist/cli/commands/farm.mjs +18 -18
  30. package/dist/cli/commands/follow.mjs +43 -32
  31. package/dist/cli/commands/mint.mjs +12 -11
  32. package/dist/cli/commands/model.mjs +218 -216
  33. package/dist/cli/commands/quickstart.mjs +6 -6
  34. package/dist/cli/commands/receipt.mjs +11 -11
  35. package/dist/cli/commands/resolve.mjs +9 -9
  36. package/dist/cli/commands/session-vault.mjs +5 -5
  37. package/dist/cli/commands/sign.mjs +12 -12
  38. package/dist/cli/commands/signer.mjs +25 -25
  39. package/dist/cli/commands/snipe.mjs +9 -9
  40. package/dist/cli/commands/strategy.mjs +5 -5
  41. package/dist/cli/commands/swap.mjs +15 -15
  42. package/dist/cli/commands/telegram.mjs +11 -10
  43. package/dist/cli/commands/venues.mjs +2 -2
  44. package/dist/data/chart-artifact.mjs +2 -0
  45. package/dist/data/desk-data.mjs +28 -28
  46. package/dist/data/holder-table.mjs +3 -0
  47. package/dist/data/market-tape.mjs +1 -0
  48. package/dist/data/names.mjs +3 -3
  49. package/dist/data/providers/farming.mjs +2 -2
  50. package/dist/data/providers/lp-destination-discovery.mjs +4 -4
  51. package/dist/index.mjs +46 -46
  52. package/dist/investigator/index.mjs +2 -2
  53. package/dist/launch-radar/index.mjs +5 -5
  54. package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
  55. package/dist/local-signer/index.mjs +7 -3
  56. package/dist/local-signer/runtime.mjs +22 -22
  57. package/dist/lp/index.mjs +5 -0
  58. package/dist/nft/universal-mint-router.mjs +4 -4
  59. package/dist/notifications/contract-watchman.mjs +4 -0
  60. package/dist/notifications/index.mjs +7 -7
  61. package/dist/router/index.mjs +3 -3
  62. package/dist/router/prepare-bridge.mjs +2 -2
  63. package/dist/router/prepare-route.mjs +3 -3
  64. package/dist/scanner/index.mjs +4 -4
  65. package/dist/strategy/index.mjs +5 -3
  66. package/dist/telegram/chart-card.mjs +5 -0
  67. package/dist/telegram/market-commands.mjs +2 -0
  68. package/dist/tui/standalone-client.mjs +86 -85
  69. package/package.json +10 -1
  70. package/public/oracle-splash/docs/browser-and-web/index.html +3 -3
  71. package/public/oracle-splash/docs/connectors/index.html +3 -3
  72. package/public/oracle-splash/docs/getting-started/index.html +2 -2
  73. package/public/oracle-splash/docs/index.html +3 -3
  74. package/public/oracle-splash/docs/reference/index.html +2 -2
  75. package/public/oracle-splash/docs/security/index.html +2 -2
  76. package/public/oracle-splash/docs/using-oracle/index.html +2 -2
  77. package/public/oracle-splash/download/index.html +3 -3
  78. package/public/oracle-splash/downloads/index.html +1 -1
  79. package/public/oracle-splash/index.html +6 -6
  80. package/server.json +2 -2
@@ -1,7 +1,8 @@
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}
1
+ var gn=Object.defineProperty;var q=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var We=(e,t)=>{for(var r in t)gn(e,r,{get:t[r],enumerable:!0})};import{AsyncLocalStorage as wn}from"node:async_hooks";function Te(e){let t=bn.getStore();if(!t||t.closed||!yn.includes(e))return null;if(t.spans.length>=En)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)}}var bn,yn,En,Rt=q(()=>{bn=new wn,yn=["http","retry","shared"],En=512});import re from"node:net";import xn from"node:dns";function Ie(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=u=>{if(!u)return[];let d=u.split(":"),m=d.at(-1);if(m?.includes(".")){let f=m.split(".").map(Number);if(f.length!==4||f.some(p=>!Number.isInteger(p)||p<0||p>255))return null;d.splice(d.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return d.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:d.map(f=>Number.parseInt(f,16))},[n,o]=t.split("::"),i=r(n),a=r(o);if(!i||!a)return null;let s=t.includes("::"),c=8-i.length-a.length;if(!s&&c!==0||s&&c<1)return null;let l=[...i,...Array(Math.max(0,c)).fill(0),...a];return l.length!==8?null:Uint8Array.from(l.flatMap(u=>[u>>8,u&255]))}function He(e,t,r){let n=Math.floor(r/8),o=r%8;for(let a=0;a<n;a+=1)if(e[a]!==t[a])return!1;if(!o)return!0;let i=255<<8-o;return(e[n]&i)===(t[n]&i)}function Ue(e){if(re.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(re.isIPv6(e)){let t=Ie(e);if(!t)return!1;let r=Ie("::ffff:0:0");return He(t,r,96)?Ue([...t.slice(12)].join(".")):He(t,Ie("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,i])=>He(t,Ie(o),i)):!1}return!1}function vn(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(Sn.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=re.isIP(r);return n!==0&&!Ue(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function ze(e,{lookupFn:t=xn.promises.lookup}={}){let r=vn(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:re.isIPv6(r.host)?6:4}]};let n;if(process.env.ORACLE_HOSTED_EGRESS_PROXY)return{ok:!0,url:r.url,addresses:[]};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=>!Ue(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}function An(e=process.env){let t=e.ORACLE_HOSTED_EGRESS_PROXY||"";if(!t)return null;let r;try{r=new URL(t)}catch{throw new Error("egress-guard: ORACLE_HOSTED_EGRESS_PROXY is not a URL")}if(r.protocol!=="http:"||!["127.0.0.1","::1","localhost","[::1]"].includes(r.hostname)||!r.port||r.username||r.password)throw new Error("egress-guard: egress proxy must be an exact loopback http origin");let n=e.ORACLE_HOSTED_EGRESS_TOKEN||"";if(!/^[A-Za-z0-9_-]{43}$/.test(n))throw new Error("egress-guard: egress proxy token is missing");return{uri:r.origin,token:n}}async function Ve({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n,o;try{o=await t(),r=o.Agent,n=o.fetch}catch(f){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${f?.message||f}`);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 i=f=>String(f).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),a=new Map,s=f=>(Array.isArray(f)?f:[f]).map(p=>typeof p=="string"?{address:p}:p).filter(p=>p&&p.address).map(p=>({address:p.address,family:p.family||(re.isIPv6(p.address)?6:4)})),c=(f,p,h)=>{a.set(i(f),s(typeof p=="string"?[{address:p,family:h}]:p))},l=f=>{let p=i(f);if(re.isIP(p))return[{address:p,family:re.isIPv6(p)?6:4}];let h=a.get(p);if(!h||!h.length)throw new Error(`refused: unpinned host ${f} during pinned fetch`);return h},u=An(),d=u&&typeof o.ProxyAgent=="function"?new o.ProxyAgent({uri:u.uri,token:`Bearer ${u.token}`,connectTimeout:1e4}):new r({connect:{lookup(f,p,h){let g;try{g=l(f)}catch(b){return h(b)}return p?.all?h(null,g):h(null,g[0].address,g[0].family)}}}),m=Tn((f,p={})=>n(f,{...p,dispatcher:d}),c);return{dispatcher:d,fetch:m,pin:c,resolve:l,async close(){try{await d.destroy()}catch{}}}}function Tn(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[Ke]=Object.freeze({pin:t}),e}function Je(e){return typeof e=="function"&&typeof e[Ke]?.pin=="function"}function Ct(e,t,r){if(!Je(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[Ke].pin(t,r)}var Sn,Ke,kt=q(()=>{Sn=new Set(["localhost","metadata.google.internal","metadata.goog"]);Ke=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as In}from"node:crypto";import{types as K}from"node:util";function k(e){return Q(`HTTP JSON body refused: ${e}`)}function Ln(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 K[t]=="function"&&K[t](e))}function Mn(e){let t=[],r=0,n=0,o=0,i=0,a=new WeakSet,s=u=>{if(r+=Buffer.byteLength(u,"utf8"),r>V.bytes)throw k("serialized byte limit exceeded");t.push(u)},c=u=>{if(Buffer.byteLength(u,"utf8")>V.bytes)throw k("serialized byte limit exceeded");return JSON.stringify(u)},l=(u,d)=>{if(n+=1,n>V.nodes)throw k("node limit exceeded");if(d>V.depth)throw k("depth limit exceeded");if(u===null){s("null");return}if(typeof u=="string"){s(c(u));return}if(typeof u=="boolean"){s(u?"true":"false");return}if(typeof u=="number"){if(!Number.isFinite(u))throw k("non-finite number");s(Object.is(u,-0)?"0":String(u));return}if(typeof u!="object")throw k("unsupported non-JSON value");if(K.isProxy(u))throw k("proxy value");if(Ln(u))throw k("unsupported exotic object");if(a.has(u))throw k("cyclic value");a.add(u);try{if(Object.getOwnPropertySymbols(u).length>0)throw k("symbol-keyed fields are unsupported");if(Array.isArray(u)){let p=Object.getPrototypeOf(u),h=0;for(;p!==null;){if(K.isProxy(p))throw k("proxy array prototype");if(h+=1,h>V.depth)throw k("array prototype depth limit exceeded");p=Object.getPrototypeOf(p)}if(u.length>V.arrayLength)throw k("array length limit exceeded");for(let b=0;b<u.length;b+=1){let I=Object.getOwnPropertyDescriptor(u,String(b));if(!I||!Object.hasOwn(I,"value")||I.enumerable!==!0)throw k("array entries must be dense enumerable own data")}let g=0;for(let b in u){if(i+=1,i>V.fields)throw k("enumeration limit exceeded");if(Object.hasOwn(u,b)&&(g+=1,g>u.length))throw k("named array fields are unsupported")}if(g!==u.length)throw k("array entries must be dense enumerable own data");s("[");for(let b=0;b<u.length;b+=1)b&&s(","),l(Object.getOwnPropertyDescriptor(u,String(b)).value,d+1);s("]");return}let m=Object.getPrototypeOf(u);if(m!==Object.prototype&&m!==null)throw k("non-plain object");let f=[];for(let p in u){if(i+=1,i>V.fields)throw k("enumeration limit exceeded");if(!Object.hasOwn(u,p))continue;if(o+=1,o>V.fields)throw k("field limit exceeded");let h=Object.getOwnPropertyDescriptor(u,p);if(!h||!Object.hasOwn(h,"value")||h.enumerable!==!0)throw k("object fields must be enumerable own data");f.push([p,h.value])}s("{");for(let p=0;p<f.length;p+=1)p&&s(","),s(c(f[p][0])),s(":"),l(f[p][1],d+1);s("}")}finally{a.delete(u)}};return l(e,0),t.join("")}function Fn(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(K.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 i=Object.getOwnPropertyDescriptor(e,n);if(!i||!Object.hasOwn(i,"value"))throw new TypeError("HTTP headers must contain own data properties");let a=i.value;if(a==null||["object","function","symbol"].includes(typeof a))throw new TypeError("HTTP header values must be scalar");t[n]=String(a)}return t}function Bn(){return Object.assign(Object.create(null),{Accept:"application/json"})}function qn(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 Dn(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function _e(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=Bt.get(e);return t||(t=qt,qt+=1,Bt.set(e,t)),`reference:${t}`}function Dt(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?jn.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 jt(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(Dt);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Dt(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&Gn.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Wn(e,t,r,n={},o=null){let i=In("sha256"),a=(c,l)=>{let u=String(l);i.update(String(Buffer.byteLength(c,"utf8"))).update(":").update(c),i.update("=").update(String(Buffer.byteLength(u,"utf8"))).update(":").update(u).update(`
2
+ `)};a("method",e),a("url",t),Object.keys(r||{}).map((c,l)=>({name:c.toLowerCase(),order:l,value:String(r[c])})).sort((c,l)=>c.name.localeCompare(l.name)||c.order-l.order).forEach((c,l)=>{a(`header-name-${l}`,c.name),a(`header-value-${l}`,c.value)}),a("body",o??"-");for(let c of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])a(`context-${c}`,n[c]??"-");return i.digest("hex")}function Hn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Lt):Math.min(250*2**e,Lt)+Math.floor(Math.random()*100)}function Q(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function Xe(e,t,r){return Q(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function ne(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function zn(e){return e?e.byteLength??e.length??0:0}async function Vn(e,t,{url:r,truncate:n=!1,onOversize:o}={}){if(t==null)return await e.text();let i=Number(e.headers?.get?.("content-length"));if(Number.isFinite(i)&&i>t&&(ne(e),!n))throw Xe(r,`content-length ${i}`,t);let a=e.body?.getReader?.();if(!a){let d=await e.text(),m=Buffer.byteLength(d,"utf8");if(m>t){if(!n)throw Xe(r,`body ${m} bytes`,t);return Buffer.from(d,"utf8").subarray(0,t).toString("utf8")}return d}let s=[],c=0,l=!1;try{for(;;){let{value:d,done:m}=await a.read();if(m)break;if(d&&(s.push(Buffer.from(d)),c+=zn(d),c>t)){l=!0;break}}}finally{if(l)try{await a.cancel()}catch{}try{a.releaseLock?.()}catch{}}if(l&&(typeof o=="function"&&o(),!n))throw Xe(r,`streamed ${c} bytes`,t);let u=Buffer.concat(s);return(l?u.subarray(0,t):u).toString("utf8")}function Kn(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function Jn(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:i,lookupFn:a,realFetch:s,untrustedUrl:c=!1,maxResponseBytes:l=null,sameOriginRedirectsOnly:u=!1,importUndici:d,validateResponse:m,signal:f,redirectPolicy:p="follow",maxRedirects:h=Pe}){let g=null,b=t,I=a?{lookupFn:a}:{};if(c&&!s&&!Je(b))throw Q(`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 w=new AbortController,E=setTimeout(()=>w.abort(),i),P=f?Ft?Ft([f,w.signal]):f:w.signal,L=async(x,{status:v=null}={})=>{let _=await ze(x,I);if(!_.ok)throw Q(v==null?`HTTP refused ${x}: ${_.error}`:`HTTP redirect to ${x} ${_.error}`,v==null?{}:{status:v});let F=new URL(x).hostname;if(s){if(g&&(await g.close(),g=null),!g)try{g=await Ve({requireUndici:!0,...d?{importUndici:d}:{}})}catch(y){throw Q(v==null?`HTTP refused ${x}: ${y?.message||y}`:`HTTP redirect to ${x} refused: ${y?.message||y}`,v==null?{}:{status:v})}g.pin(F,_.addresses),b=g.fetch}else Ct(b,F,_.addresses);return _};try{let x=String(e),v=Object.assign(Object.create(null),n||{});c&&await L(x);for(let _=0;_<=h;_+=1){let F=Object.assign(Object.create(null),{method:r,headers:v,body:o,signal:P,redirect:"manual",dispatcher:void 0}),y=await b(x,F);if((p==="error"||h===0)&&y.status>=300&&y.status<400)throw ne(y),Q(`HTTP ${y.status} ${r} redirect refused`,{status:y.status,redirectRefused:!0});if($n.has(y.status)){let B=u===!0&&r==="POST"&&[307,308].includes(y.status)&&jt(r,o);if(r!=="GET"&&r!=="HEAD"&&!B){ne(y);let N=new Error(`HTTP ${y.status} ${r} ${x} redirected non-idempotent request`);throw N.status=y.status,N}if(_===h)throw ne(y),Q(`HTTP ${y.status} ${r} redirect budget exhausted`,{status:y.status,redirectRefused:!0});let C=y.headers?.get?.("location"),M;try{M=qn(C,x)}catch(N){throw ne(y),N}let W=!Dn(M,x);if(ne(y),W&&r==="POST"){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N}if(W&&u){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N.retryable=!1,N}if(W&&(v=Bn(v)),c)await L(M,{status:y.status});else if(W){let N=await ze(M,I);if(!N.ok){let T=new Error(`HTTP redirect from ${x} ${N.error}`);throw T.status=y.status,T.retryable=!1,T}s&&N.addresses?.length&&(g||(g=await Ve(d?{importUndici:d}:{})),g&&(g.pin(new URL(M).hostname,N.addresses),b=g.fetch))}x=M;continue}if(typeof m=="function")try{await m(y,{url:x})}catch(B){throw ne(y),Q(B?.message||String(B))}let O=await Vn(y,l,{url:x,onOversize:()=>w.abort()}),te=Kn(O);if(!y.ok){let B=new Error(`HTTP ${y.status} ${r} ${x}`);throw B.status=y.status,B.retryAfter=y.headers?.get?.("retry-after")??null,B.body=te??O.slice(0,300),B}return te??O}throw new Error(`HTTP redirect loop for ${e}`)}catch(x){if(w.signal.aborted&&!be(f)){let v=x&&(typeof x=="object"||typeof x=="function")&&!K.isProxy(x)?x:null,_=v?Object.getOwnPropertyDescriptor(v,"oversize"):null;if(!(_&&Object.hasOwn(_,"value")&&_.value===!0))try{if(!v)throw new TypeError("unsafe rejection");Object.defineProperties(v,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let y=new Error("HTTP request timed out");throw Object.defineProperties(y,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),y}}throw x}finally{clearTimeout(E),g&&await g.close()}}async function G(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&K.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 T of Object.getOwnPropertyNames(t)){let A=Object.getOwnPropertyDescriptor(t,T);if(!(T==="toJSON"&&A&&Object.hasOwn(A,"value")&&A.value===void 0)){if(!r.has(T))throw new TypeError("HTTP options contain unknown fields");if(!A||!A.enumerable||!Object.hasOwn(A,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=T=>{if(t==null||!Object.hasOwn(t,T))return;let A=Object.getOwnPropertyDescriptor(t,T);if(!A||!Object.hasOwn(A,"value"))throw new TypeError("HTTP options must contain own data properties");return A.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 i=n("timeoutMs");if(i!==void 0&&(!Number.isInteger(i)||i<1||i>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let a=n("retries");if(a!==void 0&&(!Number.isInteger(a)||a<0||a>10))throw new TypeError("HTTP retries must be a bounded integer");let s=n("redirectPolicy");if(s!==void 0&&s!=="follow"&&s!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let c=n("maxRedirects");if(c!==void 0&&(!Number.isInteger(c)||c<0||c>Pe))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${Pe}`);if(s==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let l=s??"follow",u=l==="error"?0:c??Pe;for(let T of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let A=n(T);if(A!==void 0&&typeof A!="boolean")throw new TypeError(`HTTP ${T} must be boolean`)}let d=n("maxResponseBytes");if(d!==void 0&&(!Number.isInteger(d)||d<1||d>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let m=n("signal");if(m!==void 0){if(K.isProxy(m)||!(m instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{be(m)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let T of["importUndici","lookupFn","validateResponse"]){let A=n(T);if(A!==void 0&&typeof A!="function")throw new TypeError(`HTTP ${T} must be a function`)}let f=n("fetchImpl"),p=f||globalThis.fetch;if(typeof p!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let h=i??12e3,g=(o||"GET").toUpperCase(),b=n("headers"),I=Fn(b),w=Object.assign(Object.create(null),I);Object.keys(w).some(T=>T.toLowerCase()==="accept")||(w.Accept="application/json");let E=n("body");E!=null&&typeof E!="string"&&(Object.keys(w).find(A=>A.toLowerCase()==="content-type")||(w["Content-Type"]="application/json"),E=Mn(E));let P=a??Pn,L=n("lookupFn"),x=!f,v=n("untrustedUrl")===!0,_=n("sameOriginRedirectsOnly")===!0,F=n("importUndici"),y=n("validateResponse"),O=m,te=d??null,B=async()=>{let T;for(let A=0;A<=P;A++){O&&Rn.call(O);let _t=Te("http");try{let z=await Jn(e,{fetchImpl:p,method:g,headers:w,body:E,timeoutMs:h,lookupFn:L,realFetch:x,untrustedUrl:v,maxResponseBytes:te,sameOriginRedirectsOnly:_,importUndici:F,validateResponse:y,signal:O,redirectPolicy:l,maxRedirects:u});return _t?.("succeeded"),z}catch(z){T=z;let ce=Ge=>{if(!z||typeof z!="object"&&typeof z!="function"||K.isProxy(z))return;let ge=Object.getOwnPropertyDescriptor(z,Ge);return ge&&Object.hasOwn(ge,"value")?ge.value:void 0},Ae=ce("status");_t?.("failed",Ae);let fn=ce("oracleTimeout")===!0||ce("name")==="AbortError"||ce("name")==="TimeoutError"||be(O),pn=new Set([408,425,429]),mn=ce("retryable")===!1?!1:Ae!=null?pn.has(Ae)||_n.has(Ae)&&$t.has(g):!fn&&$t.has(g);if(A===P||!mn)throw z;let Pt=Hn(A,ce("retryAfter")),hn=Te("retry"),Ot=!1;try{O?await new Promise((Ge,ge)=>{let Nt,we=()=>{clearTimeout(Nt),Mt.call(O,"abort",we),ge(kn(O)||new DOMException("Aborted","AbortError"))};if(be(O)){we();return}Nt=setTimeout(()=>{Mt.call(O,"abort",we),Ge()},Pt),Cn.call(O,"abort",we,{once:!0}),be(O)&&we()}):await Un(Pt),Ot=!0}finally{hn?.(Ot?"succeeded":"failed")}}}throw T};if(!(n("dedupe")!==!1&&!O&&jt(g,E)))return B();let M=Wn(g,e,w,{untrustedUrl:v,maxResponseBytes:te,sameOriginRedirectsOnly:_,redirectPolicy:l,maxRedirects:u,timeoutMs:h,retries:P,fetchImpl:_e(p),realFetch:x,lookupFn:_e(L),importUndici:_e(F),validateResponse:_e(y)},E),W=Ye.get(M);if(W){let T=Te("shared");try{let A=await W;return T?.("succeeded"),A}catch(A){throw T?.("failed"),A}}let N=B().finally(()=>Ye.delete(M));return Ye.set(M,N),N}async function Gt(e,t,r){let n=Array.from(e),o=Math.max(1,Math.min(Number(t)||1,n.length||1)),i=new Array(n.length),a=0;return await Promise.all(Array.from({length:o},async()=>{for(;a<n.length;){let s=a++;i[s]=await r(n[s],s)}})),i}var _n,$t,Pn,Lt,On,Nn,Rn,Cn,Mt,Ft,be,kn,$n,Pe,Ma,V,Ye,Bt,qt,jn,Gn,Un,Ze=q(()=>{Rt();kt();_n=new Set([408,425,429,500,502,503,504]),$t=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Pn=2,Lt=4e3,On=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Nn=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Rn=AbortSignal.prototype.throwIfAborted,Cn=EventTarget.prototype.addEventListener,Mt=EventTarget.prototype.removeEventListener,Ft=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,be=e=>e?On.call(e):!1,kn=e=>e?Nn.call(e):void 0,$n=new Set([301,302,303,307,308]),Pe=3,Ma=64*1024,V=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});Ye=new Map,Bt=new WeakMap,qt=1;jn=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),Gn=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);Un=e=>new Promise(t=>setTimeout(t,e))});var Oe,Wt=q(()=>{Oe={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}}});function Qe(e){return Ht.get(Number(e))||null}function Ut(e,t=process.env){let r=Qe(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}function zt(e){return Ht.has(Number(e))}var Ht,Vt=q(()=>{Wt();Ht=new Map(Object.values(Oe).map(e=>[e.chainId,e]))});var rt={};We(rt,{PUBLIC_RPC_FALLBACKS:()=>tt,erc20Allowance:()=>ao,erc20BalanceOf:()=>so,resolveRpcUrl:()=>Re,rpcBatch:()=>Qt,rpcBlockNumber:()=>ro,rpcCall:()=>$,rpcChainId:()=>no,rpcGasPrice:()=>oo,rpcGetBalance:()=>io,rpcHealth:()=>er,rpcHealthAll:()=>uo,transactionReceipt:()=>co});import{Interface as Yn,getAddress as Xn}from"ethers";function ee(e,t){try{return Xn(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function Zn(e){let t=String(e||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw new Error("txHash must be a 32-byte hex transaction hash");return t.toLowerCase()}function et(e){return e==null?null:Number.parseInt(String(e),16)}function Re(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Ut(e,r);return n||tt[Number(e)]||null}function Yt(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Qn.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}function eo(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function Xt(e){if(e?.error)throw eo(e.error);return e?.result}function to(e,t,r){return`${e}
3
3
  ${t}
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]
4
+ ${JSON.stringify(r??[])}`}async function Zt(e,t,r){return G(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function Qt(e,t,r={}){if(!Array.isArray(t)||t.length===0)throw new Error("rpcBatch requires a non-empty calls array");if(t.length>Kt)throw new Error(`rpcBatch: at most ${Kt} calls`);for(let i of t)Yt(i?.method);let n=Re(e,r);if(!n)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let o=t.map((i,a)=>({jsonrpc:"2.0",id:a+1,method:i.method,params:i.params||[]}));try{let i=await Zt(n,o,r);if(Array.isArray(i)&&i.length===t.length){let a=new Map(i.map(s=>[Number(s?.id),s]));return t.map((s,c)=>Xt(a.get(c+1)??i[c]))}}catch{}return Promise.all(t.map(i=>$(e,i.method,i.params||[],r)))}async function $(e,t,r=[],n={}){let o=String(t||""),i=Yt(o),a=Re(e,n);if(!a)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);if(i==="eth_chainid"&&n.cacheChainId!==!1){let u=Jt.get(a);if(u!=null)return u}let c=n.dedupe!==!1&&!n.signal?to(a,o,r):null;if(c&&ye.has(c))return ye.get(c);let l=(async()=>{let u=await Zt(a,{jsonrpc:"2.0",id:1,method:t,params:r},n),d=Xt(u);return i==="eth_chainid"&&typeof d=="string"&&Jt.set(a,d),d})();return c&&(ye.set(c,l),l.finally(()=>{ye.get(c)===l&&ye.delete(c)}).catch(()=>{})),l}async function er(e,t={}){let[r,n]=await Qt(e,[{method:"eth_blockNumber",params:[]},{method:"eth_chainId",params:[]}],t),o=parseInt(r,16),i=parseInt(n,16);return{ok:Number.isFinite(o)&&i===Number(e),chainId:Number(e),reportedChainId:i,blockNumber:o,name:Qe(e)?.name||null}}async function ro(e,t={}){let r=await $(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function no(e,t={}){let r=await $(e,"eth_chainId",[],t);return parseInt(r,16)}async function oo(e,t={}){let r=await $(e,"eth_gasPrice",[],t);if(r==null)return null;try{return BigInt(r)}catch{return null}}async function io(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await $(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function ao(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=ee(e.token||e.tokenAddress,"token"),o=ee(e.owner,"owner"),i=ee(e.spender,"spender"),a=Ne.encodeFunctionData("allowance",[o,i]),s=await $(r,"eth_call",[{to:n,data:a},e.blockTag||"latest"],t),c=Ne.decodeFunctionResult("allowance",s),l=BigInt(c[0]);return{chainId:r,token:n,owner:o,spender:i,allowance:l.toString(),allowanceHex:`0x${l.toString(16)}`,blockTag:e.blockTag||"latest"}}async function so(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=ee(e.token||e.tokenAddress,"token"),o=ee(e.account||e.owner||e.address,"account"),i=Ne.encodeFunctionData("balanceOf",[o]),a=await $(r,"eth_call",[{to:n,data:i},e.blockTag||"latest"],t),s=Ne.decodeFunctionResult("balanceOf",a),c=BigInt(s[0]);return{chainId:r,token:n,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}async function co(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Zn(e.txHash||e.hash||e.transactionHash),o=await $(r,"eth_getTransactionReceipt",[n],t);if(!o)return{ok:!1,chainId:r,txHash:n,status:"pending",receipt:null,reason:"receipt pending"};let i=et(o.status),a=i===1,s=i===1?"success":i===0?"reverted":"unknown",c=a?null:s==="reverted"?"transaction reverted":"unknown receipt status",l=e.expectedTo?ee(e.expectedTo,"expectedTo"):null,u=o.to?ee(o.to,"receipt.to"):null;return l&&u!==l&&(a=!1,c=`to mismatch: expected ${l}, got ${u||"null"}`),{ok:a,chainId:r,txHash:n,status:s,reason:c,statusCode:i,to:u,from:o.from?ee(o.from,"receipt.from"):null,blockNumber:et(o.blockNumber),transactionIndex:et(o.transactionIndex),logs:Array.isArray(o.logs)?o.logs:[],receipt:o}}async function uo(e={}){let t=e.chainIds||Object.values(Oe).map(n=>n.chainId),r={};return await Promise.all(t.map(async n=>{if(!zt(n)&&!tt[n]&&!Re(n,e)){r[n]={ok:!1,error:"no rpc configured",chainId:n};return}try{r[n]=await er(n,e)}catch(o){r[n]={ok:!1,chainId:n,error:String(o.message||o)}}})),r}var Ne,tt,Qn,Kt,ye,Jt,J=q(()=>{Ze();Vt();Ne=new Yn(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);tt={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"};Qn=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;Kt=32,ye=new Map,Jt=new Map});function oe(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 i=e.trim();if(i.startsWith("0x")||i.startsWith("0X"))o=BigInt(i);else{if(!lo.test(i))throw new Error(`${t} must be an integer wei string`);o=BigInt(i)}}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 fo(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new Error("chainId must be a positive integer");return t}function po(e={}){return e.maxFeePerGas!=null?oe(e.maxFeePerGas,"maxFeePerGas"):e.gasPrice!=null?oe(e.gasPrice,"gasPrice"):null}function ot(e={}){try{let t=fo(e.chainId??e.tx?.chainId),r=e.tx||e,n=e.policy||e,o=n.grant?.maxGasWei??e.grant?.maxGasWei,i=oe(n.maxTotalGasWei??n.maxGasWei??o,"maxTotalGasWei"),a=oe(r.gasLimit??r.gas,"gasLimit"),s=po(r);if(s==null)throw new Error("maxFeePerGas or gasPrice required");let c=oe(n.maxFeePerGasWei,"maxFeePerGasWei",{required:!1}),l=oe(n.maxPriorityFeePerGasWei,"maxPriorityFeePerGasWei",{required:!1}),u=r.maxPriorityFeePerGas==null?null:oe(r.maxPriorityFeePerGas,"maxPriorityFeePerGas"),d=a*s;return d>i?{ok:!1,status:"BLOCK",reason:`total gas ${d} exceeds cap ${i}`,chainId:t,totalGasWei:d.toString(),maxTotalGasWei:i.toString()}:c!=null&&s>c?{ok:!1,status:"BLOCK",reason:`unit fee ${s} exceeds cap ${c}`,chainId:t,unitFeeWei:s.toString(),maxFeePerGasWei:c.toString(),totalGasWei:d.toString(),maxTotalGasWei:i.toString()}:u!=null&&l!=null&&u>l?{ok:!1,status:"BLOCK",reason:`priority fee ${u} exceeds cap ${l}`,chainId:t,priorityFeeWei:u.toString(),maxPriorityFeePerGasWei:l.toString(),totalGasWei:d.toString(),maxTotalGasWei:i.toString()}:{ok:!0,status:"PASS",reason:"gas envelope within NFT mint gas-war caps",chainId:t,totalGasWei:d.toString(),maxTotalGasWei:i.toString(),unitFeeWei:s.toString(),maxFeePerGasWei:c?.toString()??null,priorityFeeWei:u?.toString()??null,maxPriorityFeePerGasWei:l?.toString()??null}}catch(t){return{ok:!1,status:"BLOCK",reason:String(t?.message||t)}}}function tr(e={}){let t=ot(e);if(!t.ok)throw new nt(t);return t}var lo,nt,it=q(()=>{lo=/^(0|[1-9][0-9]*)$/,nt=class extends Error{constructor(t){super(`nft gas-war limit: ${t.reason}`),this.name="NftGasWarLimitError",this.verdict=t}}});function lr({provider:e,defaultUrl:t,hosts:r=[],url:n,strict:o=!1}){let a=(String(n??"").trim()||String(t)).replace(/\/$/,"");if(a===String(t).replace(/\/$/,""))return{baseUrl:a,trusted:!0,host:ur(t)};let s;try{s=new URL(a)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(s.protocol!=="http:"&&s.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=s.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([ur(t),...r]).has(c)){let u=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return s.protocol==="http:"&&!u?{baseUrl:a,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:a,trusted:!0,host:c}}if(String(process.env[cr]||"")==="1")return{baseUrl:a,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${cr}=1 to permit it)`);return{baseUrl:a,trusted:!1,host:c}}function ur(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function dr(e,t,r){let n={...e};if(!r)return n;for(let[o,i]of Object.entries(t||{}))i&&(n[o]=i);return n}var cr,fr=q(()=>{cr="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});import{createHash as Co,createHmac as ko,timingSafeEqual as ss}from"node:crypto";function st(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(st).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${st(e[r])}`).join(",")}}`}function pr(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function mr(e=process.env){return pr(process.env)||pr(e)}function Mo(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function ut(e){let t=Mo(e);return Co("sha256").update(st(t)).digest("hex")}function lt(e,t=mr()){return t?ko("sha256",t).update(String(e)).digest("hex"):""}function ke(e,{provider:t,kind:r,env:n=process.env,nowMs:o=Date.now(),expiresAtMs:i}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let a=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(a&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let s={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:a?e.oraclePrepared:!0};if(!s.provider)throw new Error("stampPrepared: provider required");if(!s.kind)throw new Error("stampPrepared: kind required");let c=Number(o),l=i==null?c+ct:Number(i),u=l-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(l)||u<=0||u>Lo)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let m={...s,preparedAt:c,expiresAt:l,prepareVersion:$o},f=ut(m),p=mr(n),h=p?lt(f,p):void 0,g={...m,prepareHash:f};return h&&(g.prepareMac=h),g}var $o,ct,Lo,dt=q(()=>{$o=2,ct=300*1e3,Lo=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});var Dr={};We(Dr,{OPENSEA_ACCOUNT_CHAINS:()=>Sr,OPENSEA_API:()=>Er,OPENSEA_EVM_CHAIN_IDS:()=>mt,OPENSEA_NATIVE_PAYMENT_TOKEN:()=>Wo,OPENSEA_ROBINHOOD_WETH:()=>Ho,SEAPORT_FULFILL_ADVANCED_ORDER:()=>xr,openseaAccountNfts:()=>Zo,openseaAccountPnl:()=>Qo,openseaBestListing:()=>fi,openseaBestListings:()=>$r,openseaBestOffer:()=>mi,openseaCollection:()=>Me,openseaCollectionStats:()=>_r,openseaContext:()=>Jo,openseaFloor:()=>Xo,openseaHealth:()=>Yo,openseaPrepareBuy:()=>bi,openseaPrepareCancel:()=>Ii,openseaPrepareList:()=>Ti,openseaPrepareMint:()=>xi,openseaPrepareSweep:()=>yi});import{readFileSync as Fo,existsSync as Bo}from"node:fs";import{getAddress as qo,Interface as Le,TypedDataEncoder as pt,parseUnits as Do}from"ethers";function Uo(){let e=process.env.OPENSEA_ENV_FILE||`${process.env.HOME||""}/.config/locals-only/opensea.env`;if(!Bo(e))return"";try{for(let t of Fo(e,"utf8").split(`
5
+ `)){let r=t.match(/^\s*OPENSEA_API_KEY\s*=\s*(.+)\s*$/);if(r)return r[1].replace(/^["']|["']$/g,"").trim()}}catch{}return""}function H(e={}){return e.apiKey?e.apiKey:e.allowAmbientCredentials===!1||e.allowDiskCredentials===!1?e.env?.OPENSEA_API_KEY||e.env?.OPEN_SEA_API_KEY||"":e.env?.OPENSEA_API_KEY||process.env.OPENSEA_API_KEY||process.env.OPEN_SEA_API_KEY||Uo()}function Ar(e={}){return lr({provider:"opensea",defaultUrl:Er,hosts:["api.opensea.io","testnets-api.opensea.io"],url:e.baseUrl||process.env.OPENSEA_API_URL})}function Y(e={}){return Ar(e).baseUrl}function X(e={}){return dr({accept:"application/json"},{"x-api-key":H(e)},Ar(e).trusted)}function Tr(e){let t=String(e||"ethereum").trim().toLowerCase();if(!Go.has(t))throw new Error(`opensea: unsupported account chain ${t}`);return t}function S(e,t="address"){try{return qo(String(e||"").trim().toLowerCase())}catch{throw new Error(`opensea: invalid ${t}`)}}function Ir(e,t=null){let r=String(e||"").trim();if(!r)throw new Error("opensea: account address required");if(t&&!vr.has(t)||!t&&/^0x[0-9a-fA-F]{40}$/.test(r))return S(r,"account address");if(!/^[1-9A-HJ-NP-Za-km-z]{32,64}$/.test(r))throw new Error("opensea: invalid account address");return r}function zo(e,t){let r=String(e??"").trim();if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(r)||Number(r)<=0)throw new Error(`opensea: ${t} must be a positive plain decimal`);return r}function Vo(e,t){let r=Number(e);if(!Number.isSafeInteger(r)||r<=0)throw new Error(`opensea: ${t} must be a positive integer`);return r}function hr(e,t){let r=String(e||"").trim(),n=Date.parse(r);if(!r||!Number.isFinite(n))throw new Error(`opensea: ${t} must be an ISO 8601 timestamp`);return{text:new Date(n).toISOString(),ms:n}}function Ko(e={},t,r){return{chain:t,owner:r,contract:e.contract||null,tokenId:e.identifier==null?null:String(e.identifier),tokenStandard:e.token_standard||null,quantity:e.quantity==null&&e.balance==null?null:String(e.quantity??e.balance),collection:e.collection||null,name:e.name||null,description:e.description||null,imageUrl:e.display_image_url||e.image_url||e.original_image_url||null,originalImageUrl:e.original_image_url||e.image_url||null,animationUrl:e.display_animation_url||e.original_animation_url||null,metadataUrl:e.metadata_url||null,marketplaceUrl:e.opensea_url||null,estimatedValueUsd:e.estimated_value_usd!=null&&Number.isFinite(Number(e.estimated_value_usd))?Number(e.estimated_value_usd):null,spam:e.is_disabled===!0,disabled:e.is_disabled===!0,nsfw:e.is_nsfw===!0,traits:Array.isArray(e.traits)?e.traits:[],updatedAt:e.updated_at||null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"OpenSea account inventory does not expose trustworthy per-item acquisition cost"}}}function Jo(e={}){return{base:Y(e),headers:X(e),fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs}}async function Yo(e={}){if(!H(e))return{ok:!1,configured:!1,error:"OPENSEA_API_KEY not set"};try{let t=await Me("boredapeyachtclub",e);return{ok:!0,configured:!0,name:t.name||t.collection}}catch(t){return{ok:!1,configured:!0,error:String(t.message||t).slice(0,160)}}}async function Me(e,t={}){if(!e)throw new Error("collection slug required");if(!H(t))throw new Error("OPENSEA_API_KEY required");return G(`${Y(t)}/collections/${encodeURIComponent(e)}`,{headers:X(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function _r(e,t={}){if(!e)throw new Error("collection slug required");if(!H(t))throw new Error("OPENSEA_API_KEY required");return G(`${Y(t)}/collections/${encodeURIComponent(e)}/stats`,{headers:X(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Xo(e,t={}){let r=await Me(e,t),n=r.stats||r.total||{},o=r.floor_price??r.floorPrice??n.floor_price??n.floorPrice??null;if(o==null){let d=await _r(e,t);n=d?.total||d?.stats||d||{},o=n.floor_price??n.floorPrice??null}let i=(Array.isArray(r.contracts)?r.contracts:[]).map(d=>({chain:String(d?.chain||d?.chain_identifier||r.chain||"").trim().toLowerCase(),address:String(d?.address||d?.contract_address||d?.contract||"").trim()})).filter(d=>d.chain&&d.address),a=String(t.expectedChain||"").trim().toLowerCase(),s=String(t.expectedContract||"").trim(),c=null;if(a&&s){let d=m=>a==="solana"?m:m.toLowerCase();if(c=i.find(m=>m.chain===a&&d(m.address)===d(s))||null,!c)throw new Error("opensea: collection identity does not match held contract")}let l=c?.chain||String(r.chain||"").trim().toLowerCase()||i[0]?.chain||"",u=String(r.floor_price_symbol||r.floorPriceSymbol||n.floor_price_symbol||n.floorPriceSymbol||"").trim().toUpperCase()||null;return{slug:r.collection||e,name:r.name||null,floor:o,chain:l||null,contracts:i,currency:u,totalSupply:r.total_supply??n.total_supply??null,numOwners:r.num_owners??n.num_owners??null,raw:{contracts:i,fees:r.fees,category:r.category}}}async function Zo(e={},t={}){if(!H(t))throw new Error("OPENSEA_API_KEY required");let r=Tr(e.chain),n=Ir(e.address||e.owner,r),o=Math.min(Math.max(Number(e.pageSize??e.limit??200)||200,1),200),i=Math.min(Math.max(Number(e.maxPages??5)||5,1),25),a=[],s=e.next?String(e.next):null,c=0;do{let l=new URL(`${Y(t)}/chain/${encodeURIComponent(r)}/account/${encodeURIComponent(n)}/nfts`);l.searchParams.set("limit",String(o)),e.collection&&l.searchParams.set("collection",String(e.collection)),s&&l.searchParams.set("next",s);let u=await G(l.toString(),{headers:X(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});for(let d of Array.isArray(u?.nfts)?u.nfts:[])a.push(Ko(d,r,n));s=u?.next?String(u.next):null,c+=1}while(s&&c<i);return{provider:"opensea-nft",source:"opensea-account-inventory",chain:r,owner:n,count:a.length,pages:c,complete:!s,next:s,nfts:a,exec:!1,readOnly:!0}}async function Qo(e={},t={}){if(!H(t))throw new Error("OPENSEA_API_KEY required");let r=Ir(e.address||e.owner),n=await G(`${Y(t)}/account/${encodeURIComponent(r)}/pnl`,{headers:X(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});return{provider:"opensea-nft",source:"opensea-indexed-account-pnl",address:r,scope:"OpenSea-indexed account trading PnL across supported currencies, not per-item NFT cost basis",methodology:"provider-indexed",realizedPnlUsd:n?.realized_pnl_usd??null,unrealizedPnlUsd:n?.unrealized_pnl_usd??null,totalPnlUsd:n?.total_pnl_usd??null,netInvestedUsd:n?.net_invested_usd??null,currentValueUsd:n?.current_value_usd??null,returnPercentage:n?.return_percentage??null,itemLevelPnlAvailable:!1,raw:n,exec:!1,readOnly:!0}}function xe(e){let t=String(e||"").trim().toLowerCase(),r=mt[t];if(!r)throw new Error(`opensea: unsupported EVM chain ${t||"(missing)"}`);return{chain:t,chainId:r}}function D(e,t,{positive:r=!1}={}){let n=String(e??"").trim();if(!/^\d+$/.test(n))throw new Error(`opensea: ${t} must be an unsigned integer`);let o=BigInt(n);if(r&&o<=0n)throw new Error(`opensea: ${t} must be positive`);return o}function ei(e,t="transaction value"){let r;try{let n=String(e??"0").trim();if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(n))throw new Error("invalid");r=BigInt(n)}catch{throw new Error(`opensea: ${t} must be a non-negative integer quantity`)}if(r<0n)throw new Error(`opensea: ${t} must be non-negative`);return{amount:r,hex:`0x${r.toString(16)}`}}function Ee(e){let t=String(e??"").trim();if(!/^\d+$/.test(t))throw new Error("opensea: tokenId must be an unsigned integer string");return t}function Pr(e,t=10){let r=Number(e??1);if(!Number.isSafeInteger(r)||r<1||r>t)throw new Error(`opensea: quantity must be an integer from 1 through ${t}`);return r}function Or(e,t,r="listing expiry"){let n=e==null?"":String(e).trim(),o;if(/^\d+$/.test(n)){let i=Number(n);o=n.length<=10?i*1e3:i}else o=Date.parse(n);if(!n||!Number.isFinite(o))throw new Error(`opensea: ${r} missing or invalid`);if(o<=t)throw new Error(`opensea: ${r} is expired or stale`);return new Date(o).toISOString()}function ti(e){return!!e&&typeof e=="object"&&[0,1].includes(Number(e.itemType))}function ri(e,t){let r=Number(e?.itemType);if(![0,1].includes(r))throw new Error(`opensea: ${t} is not a native or ERC20 payment item`);let n=S(e?.token,t);if(r===0&&n!==le)throw new Error(`opensea: ${t} native payment item must use the zero address`);if(r===1&&n===le)throw new Error(`opensea: ${t} ERC20 payment item must name a non-zero token contract`);return n}function ni(e,t){let r=D(e?.startAmount,`${t} startAmount`),n=D(e?.endAmount??e?.startAmount,`${t} endAmount`);if(r!==n)throw new Error(`opensea: ${t} must be a fixed amount, not a decaying range`);return r}function ft(e,t,{required:r=!0}={}){let n=(Array.isArray(e)?e:[]).filter(ti);if(!n.length){if(r)throw new Error(`opensea: ${t} contains no native or ERC20 payment item`);return{paymentToken:null,totalWei:0n,count:0}}let o=null,i=0n;for(let a of n){let s=ri(a,`${t} payment token`);if(o==null)o=s;else if(s!==o)throw new Error(`opensea: ${t} mixes more than one payment token`);i+=ni(a,`${t} payment amount`)}return{paymentToken:o,totalWei:i,count:n.length}}function j(e,t){let r=String(e??"").trim();if(!/^\d+$/.test(r))throw new Error(`opensea: ${t} must be an unsigned integer`);return r}function gr(e,t){let r=String(e??"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(r))throw new Error(`opensea: ${t} must be a 32-byte hex value`);return r}function Nr(e,t){return{itemType:Number(j(e?.itemType,`${t} itemType`)),token:S(e?.token,`${t} token`),identifierOrCriteria:j(e?.identifierOrCriteria,`${t} identifierOrCriteria`),startAmount:j(e?.startAmount,`${t} startAmount`),endAmount:j(e?.endAmount,`${t} endAmount`)}}function ii(e,t){return{...Nr(e,t),recipient:S(e?.recipient,`${t} recipient`)}}function ai(e,t){if(!e||typeof e!="object")throw new Error(`opensea: ${t} has no canonical Seaport protocol parameters`);let r=Array.isArray(e.offer)?e.offer:null,n=Array.isArray(e.consideration)?e.consideration:null;if(!r||!r.length)throw new Error(`opensea: ${t} canonical offer array is missing`);if(!n||!n.length)throw new Error(`opensea: ${t} canonical consideration array is missing`);return{offerer:S(e.offerer,`${t} offerer`),zone:S(e.zone,`${t} zone`),offer:r.map((o,i)=>Nr(o,`${t} offer[${i}]`)),consideration:n.map((o,i)=>ii(o,`${t} consideration[${i}]`)),orderType:Number(j(e.orderType,`${t} orderType`)),startTime:j(e.startTime,`${t} startTime`),endTime:j(e.endTime,`${t} endTime`),zoneHash:gr(e.zoneHash,`${t} zoneHash`),salt:j(e.salt,`${t} salt`),conduitKey:gr(e.conduitKey,`${t} conduitKey`),counter:j(e.counter,`${t} counter`)}}function Rr(e,t,r){let n=String(e?.order_hash??e?.orderHash??"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(n))throw new Error(`opensea: invalid ${r} order hash`);let o=ai(t,r);if(pt.hashStruct("OrderComponents",oi,o).toLowerCase()!==n)throw new Error(`opensea: ${r} order hash does not match its canonical Seaport parameters`);return n}function Cr(e,t){let r=Number(e?.itemType);if([4,5].includes(r))throw new Error(`opensea: ${t} is a criteria item, not a fixed token`);if(![2,3].includes(r))throw new Error(`opensea: ${t} must be an ERC-721 or ERC-1155 item`);let n=S(e?.token,`${t} contract`),o=Ee(e?.identifierOrCriteria),i=D(e?.startAmount,`${t} startAmount`,{positive:!0}),a=D(e?.endAmount??e?.startAmount,`${t} endAmount`,{positive:!0});if(i!==a)throw new Error(`opensea: ${t} must be a fixed quantity, not a decaying range`);if(r===2&&i!==1n)throw new Error(`opensea: ${t} ERC-721 quantity must be exactly 1`);if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`opensea: ${t} quantity exceeds safe integer range`);return{itemType:r,contract:n,tokenId:o,quantity:Number(i)}}function si(e,t){let r=Array.isArray(e?.offer)?e.offer:[];if(r.some(o=>[4,5].includes(Number(o?.itemType))))throw new Error(`opensea: ${t} uses a criteria offer item, not a fixed token`);let n=r.filter(o=>[2,3].includes(Number(o?.itemType)));if(n.length!==1||r.length!==1)throw new Error(`opensea: ${t} must offer exactly one fixed ERC-721 or ERC-1155 item`);return Cr(n[0],`${t} offer NFT`)}function ci(e,t,r){let n=Array.isArray(e?.consideration)?e.consideration:[];if(n.some(a=>[4,5].includes(Number(a?.itemType))))throw new Error(`opensea: ${r} uses a criteria consideration item, not a fixed token`);let o=n.filter(a=>[2,3].includes(Number(a?.itemType)));if(o.length!==1)throw new Error(`opensea: ${r} must require exactly one fixed ERC-721 or ERC-1155 consideration item`);let i=Cr(o[0],`${r} consideration NFT`);if(i.tokenId!==t)throw new Error(`opensea: ${r} consideration token does not match the requested token`);return i}function ui(e,t,r,n){if(!(!e||typeof e!="object")){if(e.contract!=null&&String(e.contract).trim()!==""&&S(e.contract,`${n} display contract`)!==t)throw new Error(`opensea: ${n} display asset contract disagrees with the canonical Seaport offer`);if(e.identifier!=null&&String(e.identifier).trim()!==""&&String(e.identifier).trim()!==r)throw new Error(`opensea: ${n} display asset token disagrees with the canonical Seaport offer`)}}function li(e){let t=String(e??"").trim();return/^\d+$/.test(t)?t.length<=10?Number(t):Math.floor(Number(t)/1e3):Math.floor(Date.parse(t)/1e3)}function kr(e,t,r,n){let o=j(t?.startTime,`${n} startTime`),i=j(t?.endTime,`${n} endTime`),a=BigInt(Math.floor(r/1e3));if(BigInt(o)>a)throw new Error(`opensea: ${n} canonical startTime is in the future`);if(BigInt(i)<=a)throw new Error(`opensea: ${n} canonical endTime is expired or stale`);let s=Or(i,r,`${n} expiry`),c=e?.expiration_time??e?.expirationTime;if(c!=null&&String(c).trim()!==""&&li(c)!==Number(i))throw new Error(`opensea: ${n} display expiry disagrees with the canonical order endTime`);return s}function di(e,t,r){if(!e||typeof e!="object")throw new Error("opensea: invalid best listing");let n=String(e.chain||"").trim().toLowerCase();if(n!==t.chain)throw new Error("opensea: OpenSea returned a listing for the wrong chain");if(mt[n]!==t.chainId)throw new Error("opensea: OpenSea listing chain id mismatch");if(String(e.status||"").toUpperCase()!=="ACTIVE")throw new Error("opensea: OpenSea returned a non-active listing");let i=e.protocol_data?.parameters,a=si(i,"listing"),s=a.contract;if(t.contract&&s!==t.contract)throw new Error("opensea: OpenSea returned a listing for the wrong contract");let c=a.tokenId;ui(e.asset,s,c,"listing");let l=D(e.price?.current?.value,"listing price",{positive:!0}),u=Rr(e,i,"listing"),d=ft(i?.consideration,"listing consideration");if(d.totalWei!==l)throw new Error("opensea: listing consideration total does not equal the quoted listing price");return{orderHash:u,chain:t.chain,chainId:t.chainId,protocolAddress:S(e.protocol_address,"listing protocol address"),contract:s,tokenId:c,quantity:a.quantity,priceWei:l.toString(),paymentToken:d.paymentToken,currency:String(e.price?.current?.currency||"").trim()||null,decimals:Number(e.price?.current?.decimals??18),expiry:kr(e,i,r,"listing"),counter:j(i?.counter,"listing counter")}}async function $r(e={},t={}){if(!H(t))throw new Error("OPENSEA_API_KEY required");let r=xe(e.chain);r.contract=e.contract?S(e.contract,"NFT contract"):null;let n=String(e.slug||"").trim();if(!n)throw new Error("opensea: collection slug required");let o=Number(e.limit??12);if(!Number.isSafeInteger(o)||o<1||o>50)throw new Error("opensea: listing limit must be 1 through 50");let i=new URL(`${Y(t)}/listings/collection/${encodeURIComponent(n)}/best`);i.searchParams.set("limit",String(o)),e.next&&i.searchParams.set("next",String(e.next));let a=await G(i.toString(),{headers:X(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=Array.isArray(a?.listings)?a.listings:[];if(!s.length)throw new Error("opensea: no active best listings returned");let c=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();return{provider:"opensea-nft",source:"opensea-best-listings",chain:r.chain,chainId:r.chainId,slug:n,contract:r.contract,listings:s.map(l=>di(l,r,c)),next:a?.next?String(a.next):null,exec:!1,readOnly:!0}}async function fi(e={},t={}){let r=Ee(e.tokenId),n=Math.min(Math.max(Number(e.maxPages??20)||20,1),25),o=e.next?String(e.next):null,i=new Set;for(let a=1;a<=n;a+=1){let s=await $r({...e,tokenId:void 0,limit:50,next:o},t),c=s.listings.find(l=>l.tokenId===r);if(c)return{provider:"opensea-nft",source:"opensea-best-exact-listing",...c,pagesScanned:a,exact:!0,exec:!1,readOnly:!0};if(!s.next||i.has(s.next))break;i.add(s.next),o=s.next}throw new Error("opensea: no active exact NFT listing returned within page bound")}function pi(e,t,r,n){if(!e||typeof e!="object")throw new Error("opensea: invalid best offer");if(String(e.chain||"").trim().toLowerCase()!==t.chain)throw new Error("opensea: OpenSea returned an offer for the wrong chain");if(String(e.status||"").toUpperCase()!=="ACTIVE")throw new Error("opensea: OpenSea returned a non-active offer");let i=e.protocol_data?.parameters||{},s=ci(i,r,"offer").contract;if(t.contract&&s!==t.contract)throw new Error("opensea: OpenSea returned an offer for the wrong contract");let c=D(e.price?.current?.value??e.price?.value,"offer value",{positive:!0}),l=ft(i.offer,"offer payment"),u=l.paymentToken;if(l.totalWei!==c)throw new Error("opensea: offer payment total does not equal the quoted gross offer");let d=ft(i.consideration,"offer fee",{required:!1});if(d.count&&d.paymentToken!==u)throw new Error("opensea: offer fee consideration uses a different token than the offer payment");if(d.totalWei>c)throw new Error("opensea: offer fee consideration exceeds the gross offer");let m=d.totalWei.toString(),f=(c-d.totalWei).toString();return{provider:"opensea-nft",source:"opensea-best-exact-offer",orderHash:Rr(e,i,"offer"),chain:t.chain,chainId:t.chainId,protocolAddress:S(e.protocol_address,"offer protocol address"),contract:s,tokenId:r,grossOfferWei:c.toString(),sellerNetWei:f,feeWei:m,paymentToken:u,currency:String(e.price?.current?.currency||e.price?.currency||"").trim()||null,decimals:Number(e.price?.current?.decimals??e.price?.decimals??18),expiry:kr(e,i,n,"offer"),counter:j(i.counter,"offer counter"),exec:!1,readOnly:!0}}async function mi(e={},t={}){if(!H(t))throw new Error("OPENSEA_API_KEY required");let r=xe(e.chain);r.contract=e.contract?S(e.contract,"NFT contract"):null;let n=String(e.slug||"").trim();if(!n)throw new Error("opensea: collection slug required");let o=Ee(e.tokenId),i=await G(`${Y(t)}/offers/collection/${encodeURIComponent(n)}/nfts/${encodeURIComponent(o)}/best`,{headers:X(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=i?.offer||(Array.isArray(i?.offers)?i.offers[0]:i);if(!a)throw new Error("opensea: no active exact NFT offer returned");let s=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();return pi(a,r,o,s)}function hi(e){if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required after buyer, chain, contract, token, quantity, price cap, total cap, and expiry review")}function Lr(e){if(!e||typeof e!="object")return!1;let t=String(e.action??e.type??e.method??"");return/approv|setapprovalforall|permit/i.test(t)?!0:Object.values(e).some(r=>r&&typeof r=="object"&&Lr(r))}function Mr(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>/^(?:signed.*|rawtransaction|serializedtransaction|txsigned|r|s|v)$/i.test(t))}function Fr(e){return!e||typeof e!="object"?!1:Mr(e)?!0:Object.values(e).some(t=>t&&typeof t=="object"&&Fr(t))}function Br(e,t=[],r=new Set){if(!e||typeof e!="object"||r.has(e))return t;r.add(e),e.transaction&&typeof e.transaction=="object"?t.push(e.transaction):e.tx&&typeof e.tx=="object"&&t.push(e.tx);for(let[n,o]of Object.entries(e))(n==="transaction"||n==="tx")&&o&&typeof o=="object"||o&&typeof o=="object"&&Br(o,t,r);return t}function wr(e){return e&&typeof e=="object"&&typeof e.value=="string"?e.value:e}function qr(e,{buyer:t,chainId:r,targets:n}){if(!e||typeof e!="object")throw new Error("opensea: transaction object required");if(Mr(e))throw new Error("opensea: signed transaction material refused");if((e.from?S(wr(e.from),"transaction buyer"):t)!==t)throw new Error("opensea: OpenSea returned a transaction for the wrong buyer");let i=S(wr(e.to??e.target),"transaction target");if(!n.has(i))throw new Error("opensea: OpenSea returned a transaction for the wrong target");let a=e.data??e.calldata,s=e.input_data&&typeof e.input_data=="object"?e.input_data:e.input&&typeof e.input=="object"?e.input:null;if(a==null&&s){if(!String(e.function||"").replace(/^function\s+/,"").startsWith("fulfillAdvancedOrder("))throw new Error("opensea: only exact Seaport fulfillAdvancedOrder preparation is accepted");a=jo.encodeFunctionData("fulfillAdvancedOrder",[s.advancedOrder,s.criteriaResolvers,s.fulfillerConduitKey,s.recipient])}let c=String(a??"").trim().toLowerCase();if(!/^0x(?:[0-9a-f]{2})+$/.test(c))throw new Error("opensea: OpenSea returned invalid transaction calldata");let l=e.calldata_suffix==null?"":String(e.calldata_suffix).trim().toLowerCase();if(l){if(!/^0x[0-9a-f]{8}$/.test(l))throw new Error("opensea: invalid OpenSea calldata suffix");c.endsWith(l.slice(2))||(c+=l.slice(2))}let u=e.chainId??e.chain_id??e.chainIdentifier?.chainId;if(u!=null&&Number(u)!==r)throw new Error("opensea: OpenSea returned a transaction for the wrong chain");let d=ei(e.value_hex??e.valueHex??e.value??0);return{from:t,to:i,data:c,value:d.hex,chainId:r,valueWei:d.amount}}function Fe(e){return{from:e.from,to:e.to,data:e.data,value:e.value,chainId:e.chainId,...e.gasLimit==null?{}:{gasLimit:e.gasLimit},...e.maxFeePerGas==null?{}:{maxFeePerGas:e.maxFeePerGas},...e.maxPriorityFeePerGas==null?{}:{maxPriorityFeePerGas:e.maxPriorityFeePerGas},...e.worstCaseFeeWei==null?{}:{worstCaseFeeWei:e.worstCaseFeeWei}}}async function ht(e,t,r){let n=r.provider,o=!!r.rpcUrl;if(!n&&!o)return{simulated:!1,gasEstimates:[]};let i=await Gt(e,4,async c=>{let{chainId:l,...u}=Fe(c);if(n){if(typeof n.call!="function"||typeof n.estimateGas!="function")throw new Error("opensea: supplied provider must implement call and estimateGas");let[,p]=await Promise.all([n.call(u),n.estimateGas(u)]);return BigInt(p).toString()}let{rpcCall:d}=await Promise.resolve().then(()=>(J(),rt)),m={...r,fetchImpl:r.rpcFetchImpl||r.fetchImpl},[,f]=await Promise.all([d(t,"eth_call",[u,"pending"],m),d(t,"eth_estimateGas",[u],m)]);return BigInt(f).toString()}),a=null,s=null;if(n&&typeof n.getFeeData=="function"){let c=await n.getFeeData();s=c?.maxPriorityFeePerGas==null?0n:BigInt(c.maxPriorityFeePerGas),a=c?.maxFeePerGas==null?c?.gasPrice==null?null:BigInt(c.gasPrice):BigInt(c.maxFeePerGas)}else if(o){let{rpcCall:c}=await Promise.resolve().then(()=>(J(),rt)),l={...r,fetchImpl:r.rpcFetchImpl||r.fetchImpl},u=BigInt(await c(t,"eth_gasPrice",[],l));try{s=BigInt(await c(t,"eth_maxPriorityFeePerGas",[],l))}catch{s=0n}let d=await c(t,"eth_getBlockByNumber",["pending",!1],l),f=(d?.baseFeePerGas==null?0n:BigInt(d.baseFeePerGas))*2n+s;a=u>f?u:f}return a!=null&&s!=null&&e.forEach((c,l)=>{let d=(BigInt(i[l])*120n+99n)/100n;c.gasLimit=d.toString(),c.maxPriorityFeePerGas=s.toString(),c.maxFeePerGas=a.toString(),c.worstCaseFeeWei=(d*a).toString()}),{simulated:!0,gasEstimates:i}}function gi(e,t){if(Lr(e))throw new Error("opensea: approval steps are not permitted in NFT buy, sweep, or mint preparation");if(Fr(e))throw new Error("opensea: signed transaction material refused");let r=Br(e);if(!r.length&&e&&typeof e=="object"&&(e.to||e.target)&&r.push(e),!r.length)throw new Error("opensea: OpenSea returned no transaction action");return r.map(n=>qr(n,t))}function wi(e,t,r={}){return ke({...e,provider:"opensea-nft",kind:t,marketplace:"opensea",prepareReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1,note:"Unsigned OpenSea EVM NFT transaction preparation only. The private signer must revalidate every bound field before the user signs or broadcasts."},r)}async function bi(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}async function yi(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}function Ei(e,t,r){let o=(Array.isArray(e?.contracts)?e.contracts:[]).find(a=>String(a?.chain||t).toLowerCase()===t&&a?.address);if(!o)throw new Error("opensea: collection response contains no contract for requested chain");let i=S(o.address,"collection NFT contract");if(i!==r)throw new Error("opensea: OpenSea returned the wrong collection contract");return i}async function xi(e={},t={}){if(!H(t))throw new Error("OPENSEA_API_KEY required");hi(e);let{chain:r,chainId:n}=xe(e.chain),o=S(e.buyer||e.minter||e.address,"buyer"),i=S(e.contract,"NFT contract"),a=Pr(e.quantity),s=D(e.priceWei,"priceWei"),c=D(e.maxTotalWei,"maxTotalWei"),l=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now(),u=Or(e.expiry,l,"mint expiry");if(e.tokenId!=null)throw new Error("opensea: SeaDrop mint tokenId is unknown until the mined receipt and must not be caller supplied");let d=String(e.slug||"").trim();if(!d)throw new Error("opensea: collection slug required");let m=await Me(d,t),f=Ei(m,r,i),p=s*BigInt(a);if(p>c)throw new Error("opensea: mint total exceeds total cap");let h=await G(`${Y(t)}/drops/${encodeURIComponent(d)}/mint`,{method:"POST",headers:X(t),body:{minter:o,quantity:a},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),g=t.allowedMintTargets?.[r]??t.allowedMintTargets?.[n]??e.mintTarget,b=Array.isArray(g)?g:g?[g]:[];if(!b.length)throw new Error("opensea: reviewed SeaDrop mintTarget required");let I=new Set(b.map(C=>S(C,"SeaDrop mint target"))),w=gi(h,{buyer:o,chainId:n,targets:I});if(w.length!==1)throw new Error("opensea: mint must contain exactly one SeaDrop transaction");let E,P,L=null,x;try{E=$e.decodeFunctionData("mintPublic",w[0].data),P="public",x=$e.encodeFunctionData("mintPublic",[E[0],E[1],E[2],E[3]])}catch{try{E=$e.decodeFunctionData("mintAllowList",w[0].data),P="allowlist";let C=E[4],M=[...E[5]].map(String);if(M.length<1||M.length>64||M.some(A=>!/^0x[0-9a-fA-F]{64}$/.test(A)))throw new Error("opensea: allowlist mint requires a bounded canonical Merkle proof");let W=BigInt(C.startTime),N=BigInt(C.endTime),T=BigInt(Math.floor(l/1e3));if(W>T||N<=T)throw new Error("opensea: allowlist mint stage is not open");if(BigInt(C.mintPrice)!==s)throw new Error("opensea: allowlist stage price does not match exact approved price");if(BigInt(C.maxTotalMintableByWallet)<BigInt(a))throw new Error("opensea: allowlist wallet cap is below requested quantity");x=$e.encodeFunctionData("mintAllowList",[E[0],E[1],E[2],E[3],C,M]),L={mintPrice:BigInt(C.mintPrice).toString(),maxTotalMintableByWallet:BigInt(C.maxTotalMintableByWallet).toString(),startTime:W.toString(),endTime:N.toString(),dropStageIndex:BigInt(C.dropStageIndex).toString(),maxTokenSupplyForStage:BigInt(C.maxTokenSupplyForStage).toString(),feeBps:Number(C.feeBps),restrictFeeRecipients:!!C.restrictFeeRecipients,proof:M}}catch(C){throw/opensea:/.test(String(C?.message||""))?C:new Error("opensea: mint transaction must call reviewed SeaDrop mintPublic or mintAllowList")}}let v=S(E[0],"mint NFT contract"),_=S(E[1],"mint fee recipient"),F=S(E[2],"mint recipient");if(v!==f)throw new Error("opensea: mint calldata collection mismatch");if(F!==o)throw new Error("opensea: mint calldata recipient mismatch");if(BigInt(E[3])!==BigInt(a))throw new Error("opensea: mint calldata quantity mismatch");if(x.toLowerCase()!==w[0].data.toLowerCase())throw new Error("opensea: mint calldata must be canonical with no suffix");let y=w.reduce((C,M)=>C+M.valueWei,0n);if(y!==p)throw new Error("opensea: mint transaction total does not match exact approved price and quantity");if(y>c)throw new Error("opensea: mint total exceeds total cap");let O=await ht(w,n,{...t,provider:e.provider||t.provider});if(O.simulated!==!0)throw new Error("opensea: mint RPC simulation required");let te=e.gasPolicy||t.gasPolicy||{maxTotalGasWei:e.maxGasWei,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei},B=tr({chainId:n,tx:w[0],policy:te});return wi({action:"mint",mintType:P,...L?{stage:L}:{},chain:r,chainId:n,slug:d,buyer:o,contract:f,quantity:a,priceWei:s.toString(),totalWei:y.toString(),maxTotalWei:c.toString(),mintTarget:w[0].to,feeRecipient:_,expiry:u,transactions:w.map(Fe),gasWar:B,...O},"nft-mint",{nowMs:l,expiresAtMs:Math.min(l+ct,Date.parse(u),L?Number(BigInt(L.endTime)*1000n):Number.MAX_SAFE_INTEGER)})}function Si(e={}){let t=Tr(e.chain);if(vr.has(t))throw new Error("opensea: listing actions currently require an EVM NFT chain");let r=e.startTime||e.start_time?hr(e.startTime||e.start_time,"startTime"):{text:new Date().toISOString(),ms:Date.now()},n=hr(e.endTime||e.end_time,"endTime");if(n.ms<=r.ms)throw new Error("opensea: endTime must be after startTime");let o=String(e.tokenId??e.token_id??"").trim();if(!/^\d+$/.test(o))throw new Error("opensea: tokenId must be an unsigned integer string");return{chain:t,contract:S(e.contract,"NFT contract"),token_id:o,quantity:Vo(e.quantity??1,"quantity"),price:{amount:zo(e.price?.amount??e.amount??e.priceAmount,"price amount"),currency:S(e.price?.currency??e.currency??le,"price currency")},start_time:r.text,end_time:n.text}}function yr(e,t){return e?.[t]||(e?.action===t?e:null)}function Ai(e,{seller:t,item:r,chainId:n}){let o=Array.isArray(e?.steps)?e.steps:[],i=o.map(w=>yr(w,"createListingsAction")).find(Boolean)||o.find(w=>/createListings/i.test(String(w?.action||""))),a=i?.signatureRequest?.message??i?.typedData,s;try{s=typeof a=="string"?JSON.parse(a):a}catch{throw new Error("opensea: invalid listing typed-data JSON")}if(!s||s.primaryType!=="OrderComponents"||!s.domain||!s.message)throw new Error("opensea: exact Seaport OrderComponents action required");let c=s.domain;if(c.name!=="Seaport"||c.version!=="1.6"||Number(c.chainId)!==n)throw new Error("opensea: listing domain mismatch");let l=S(c.verifyingContract,"listing protocol"),u=s.message;if(S(u.offerer,"listing seller")!==t)throw new Error("opensea: listing seller mismatch");if(!Array.isArray(u.offer)||u.offer.length!==1)throw new Error("opensea: executable listing requires exactly one NFT offer");let d=u.offer[0];if(![2,3].includes(Number(d.itemType)))throw new Error("opensea: listing offer must be ERC721 or ERC1155");if(S(d.token,"listing collection")!==r.contract||String(d.identifierOrCriteria)!==r.token_id)throw new Error("opensea: listing NFT mismatch");if(String(d.startAmount)!==String(r.quantity)||String(d.endAmount)!==String(r.quantity))throw new Error("opensea: listing quantity mismatch");if(Number(u.orderType)!==2)throw new Error("opensea: only FULL_RESTRICTED listings are executable");if(!Array.isArray(u.consideration)||!u.consideration.length)throw new Error("opensea: listing consideration required");let m=0n;for(let w of u.consideration){if(Number(w.itemType)!==0||S(w.token,"listing payment token")!==le)throw new Error("opensea: executable listings currently require native fixed-price consideration");let E=BigInt(w.startAmount),P=BigInt(w.endAmount);if(E<=0n||E!==P)throw new Error("opensea: listing consideration must be fixed and positive");S(w.recipient,"listing consideration recipient"),m+=E}let f=Do(r.price.amount,18);if(m!==f)throw new Error("opensea: listing price mismatch");let p=BigInt(Math.floor(Date.parse(r.start_time)/1e3)),h=BigInt(Math.floor(Date.parse(r.end_time)/1e3));if(BigInt(u.startTime)!==p||BigInt(u.endTime)!==h)throw new Error("opensea: listing time bounds mismatch");let g=pt.hashStruct("OrderComponents",ue,u),b=o.map(w=>yr(w,"itemApprovalAction")).find(Boolean)||o.find(w=>/setApprovalForAll/i.test(String(w?.action||""))),I=null;if(b){let w=b.transaction||b.itemApprovalAction?.transaction,E=qr(w,{buyer:t,chainId:n,targets:new Set([r.contract])}),P;try{P=br.decodeFunctionData("setApprovalForAll",E.data)}catch{throw new Error("opensea: listing approval must be setApprovalForAll")}let L=S(P[0],"listing approval operator");if(P[1]!==!0||E.valueWei!==0n)throw new Error("opensea: listing approval must grant one exact operator with zero value");if(br.encodeFunctionData("setApprovalForAll",[L,!0]).toLowerCase()!==E.data.toLowerCase())throw new Error("opensea: listing approval calldata must be canonical");I={...E,operator:L}}return{protocolAddress:l,typedData:{domain:c,types:ue,primaryType:"OrderComponents",message:u},orderHash:g,priceWei:m,approval:I}}async function Ti(e={},t={}){if(!H(t))throw new Error("OPENSEA_API_KEY required");if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required after NFT, marketplace, price, currency, and expiry review");let r=S(e.seller||e.address||e.owner,"seller"),n=Array.isArray(e.items)&&e.items.length?e.items:[e];if(n.length!==1)throw new Error("opensea: executable listing preparation supports exactly one NFT per envelope");let o=n.map(Si);if(new Set(o.map(f=>f.chain)).size!==1)throw new Error("opensea: all prepared listing items must be on one chain");let a=e.useCreatorFee!==!1,s={address:r,items:o,use_creator_fee:a};e.taker&&(s.taker=S(e.taker,"taker"));let c=await G(`${Y(t)}/listings/actions`,{method:"POST",headers:X(t),body:s,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),{chainId:l}=xe(o[0].chain),u=Ai(c,{seller:r,item:o[0],chainId:l}),d=u.approval?[u.approval]:[],m=d.length?await ht(d,l,{...t,provider:e.provider||t.provider}):{simulated:!0};return ke({provider:"opensea-nft",marketplace:"opensea",chain:o[0].chain,chainId:l,kind:"nft-list",action:"list",prepareReady:!0,executionReady:m.simulated===!0,signingReady:m.simulated===!0,broadcastReady:m.simulated===!0,requiresUserSignature:!0,requiresSeparateApproval:d.length>0,seller:r,contract:o[0].contract,tokenId:o[0].token_id,quantity:o[0].quantity,priceWei:u.priceWei.toString(),typedData:u.typedData,orderHash:u.orderHash,submission:{chain:o[0].chain,protocol:"seaport",protocolAddress:u.protocolAddress},transactions:d.map(Fe),useCreatorFee:a,taker:s.taker||null,feeDisclosure:a?"Creator fees requested and bound into exact Seaport consideration recipients.":"Creator fees disabled by explicit request; every remaining consideration recipient is still bound.",...m})}async function Ii(e={},t={}){if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required for listing cancellation");let{chain:r,chainId:n}=xe(e.chain),o=S(e.seller||e.address||e.owner,"seller"),i=S(e.protocolAddress,"reviewed Seaport protocol address"),a=S(e.contract,"NFT contract"),s=Ee(e.tokenId),c=Pr(e.quantity),l=e.typedData;if(!l||l.primaryType!=="OrderComponents"||!l.domain||!l.message)throw new Error("opensea: exact Seaport OrderComponents typedData required for cancellation");for(let[v,_]of Object.entries(ue)){let F=l.types?.[v];if(!Array.isArray(F)||F.length!==_.length||F.some((y,O)=>y?.name!==_[O].name||y?.type!==_[O].type))throw new Error("opensea: cancellation requires canonical Seaport types")}if(Object.keys(l.types||{}).filter(v=>v!=="EIP712Domain").sort().join(",")!==Object.keys(ue).sort().join(","))throw new Error("opensea: cancellation requires canonical Seaport types");let d=l.domain;if(d.name!=="Seaport"||d.version!=="1.6"||Number(d.chainId)!==n)throw new Error("opensea: cancellation domain mismatch");let m=S(d.verifyingContract,"Seaport cancellation target");if(m!==i)throw new Error("opensea: cancellation target mismatch");let f=l.message;if(S(f.offerer,"listing seller")!==o)throw new Error("opensea: cancellation seller mismatch");if(!Array.isArray(f.offer)||f.offer.length!==1||!Array.isArray(f.consideration)||!f.consideration.length)throw new Error("opensea: cancellation requires one exact previously prepared listing order");if(Number(f.orderType)!==2)throw new Error("opensea: cancellation requires a FULL_RESTRICTED listing order");let p=f.offer[0];if(![2,3].includes(Number(p.itemType)))throw new Error("opensea: cancellation offer must be ERC721 or ERC1155");if(S(p.token,"cancellation NFT contract")!==a)throw new Error("opensea: cancellation NFT contract mismatch");if(Ee(p.identifierOrCriteria)!==s)throw new Error("opensea: cancellation tokenId mismatch");let h=D(p.startAmount,"cancellation offer startAmount",{positive:!0}),g=D(p.endAmount,"cancellation offer endAmount",{positive:!0});if(h!==BigInt(c)||g!==BigInt(c))throw new Error("opensea: cancellation quantity mismatch");for(let v of f.consideration){if(Number(v.itemType)!==0||S(v.token,"cancellation payment token")!==le)throw new Error("opensea: cancellation requires native fixed-price consideration");let _=D(v.startAmount,"cancellation consideration startAmount",{positive:!0}),F=D(v.endAmount,"cancellation consideration endAmount",{positive:!0});if(_!==F)throw new Error("opensea: cancellation consideration must be fixed and positive");S(v.recipient,"cancellation consideration recipient")}let b=D(f.startTime,"cancellation startTime");if(D(f.endTime,"cancellation endTime",{positive:!0})<=b)throw new Error("opensea: cancellation listing time bounds invalid");let w=pt.hashStruct("OrderComponents",ue,f),E=String(e.orderHash||"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(E)||E!==w.toLowerCase())throw new Error("opensea: cancellation order hash mismatch");let P=vi.encodeFunctionData("cancel",[[f]]),L=[{from:o,to:m,data:P,value:"0x0",valueWei:0n,chainId:n}],x=await ht(L,n,{...t,provider:e.provider||t.provider});if(x.simulated!==!0)throw new Error("opensea: cancellation RPC simulation required");return ke({provider:"opensea-nft",marketplace:"opensea",kind:"nft-cancel",action:"cancel-listing",prepareReady:!0,chain:r,chainId:n,seller:o,contract:a,tokenId:s,quantity:c,protocolAddress:m,orderHash:w,typedData:{domain:d,types:ue,primaryType:"OrderComponents",message:f},transactions:L.map(Fe),...x,requiresUserSignature:!0},{provider:"opensea-nft",kind:"nft-cancel"})}var Er,xr,jo,$e,Sr,Go,vr,le,Wo,Ho,mt,oi,ue,br,vi,jr=q(()=>{Ze();fr();dt();it();Er="https://api.opensea.io/api/v2",xr="fulfillAdvancedOrder(((address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,(uint256 orderIndex,uint8 side,uint256 index,uint256 identifier,bytes32[] criteriaProof)[] criteriaResolvers,bytes32 fulfillerConduitKey,address recipient)",jo=new Le([`function ${xr}`]),$e=new Le(["function mintPublic(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity) payable","function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),Sr=Object.freeze(["blast","base","ethereum","zora","arbitrum","sei","avalanche","polygon","optimism","ape_chain","flow","b3","soneium","ronin","bera_chain","solana","shape","unichain","gunzilla","abstract","animechain","hyperevm","somnia","monad","hyperliquid","megaeth","ink","robinhood","stablechain"]),Go=new Set(Sr),vr=new Set(["solana","flow"]),le="0x0000000000000000000000000000000000000000",Wo=le,Ho="0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73";mt=Object.freeze({robinhood:4663,ethereum:1,base:8453,arbitrum:42161,optimism:10,polygon:137,avalanche:43114,zora:7777777,blast:81457,sei:1329,ape_chain:33139,b3:8333,soneium:1868,ronin:2020,bera_chain:80094,shape:360,unichain:130,gunzilla:43419,abstract:2741,animechain:69e3,hyperevm:999,somnia:5031,monad:143,megaeth:4326,ink:57073,stablechain:988});oi=Object.freeze({OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]});ue={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]},br=new Le(["function setApprovalForAll(address operator,bool approved)"]),vi=new Le(["function cancel((address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 counter)[] orders) returns (bool cancelled)"])});import Be from"node:fs";import _i from"node:os";import fe from"node:path";import{fileURLToPath as Pi}from"node:url";function Gr(){return process.env.ORACLE_FAKE_HOME||_i.homedir()}function Ni(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function qe(){return Ni()?process.env.ORACLE_CONFIG_DIR||fe.join(Gr(),".config","oracle"):fe.join(Gr(),".config","oracle")}function Ri(){return fe.join(qe(),"desk.json")}function Ci(){return fe.join(qe(),"env")}function de({force:e=!1}={}){if(de._done&&!e)return de._result||null;de._done=!0;let t={},r=(o,i)=>{if(i==null)return;let a=String(i).trim();a&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=a,t[o]=a))};try{let o=Ci();if(Be.existsSync(o))for(let i of Be.readFileSync(o,"utf8").split(/\r?\n/)){let a=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),r(a[1],s)}}catch{}try{let o=Ri();if(Be.existsSync(o)){let i=JSON.parse(Be.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),de._result=Object.keys(t).length?t:null,de._result}var Oi,ys,Wr=q(()=>{Oi=fe.dirname(Pi(import.meta.url)),ys=fe.resolve(Oi,"../..");try{de()}catch{}});function gt(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(Fi.test(e)||Bi.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new De(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,i)=>gt(o,`${t}[${i}]`,r));ae(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(Mi.test(i))throw new De(`${t}.${o}`);e[o]!==void 0&&(n[o]=gt(e[o],`${t}.${o}`,o))}return n}function ae(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 pe(e,t){let r=String(Se(e,t)).toLowerCase();if(!ki.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function Z(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 wt(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 Hr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Hr(t);Object.freeze(e)}return e}function qi(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};ae(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:wt(String(n),`${t}.reason`)}}function Di(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>qi(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 ji(e){if(e==null)return null;if(ae(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:wt(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=Z(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=Z(e.gasLimit,"simulation.gasLimit")),t}function Gi(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)=>{ae(t,`assetDeltas[${r}]`);let n=Z(t.before,`assetDeltas[${r}].before`),o=Z(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),a;try{a=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(a!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:wt(String(Se(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:a}})}function Wi(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)=>{ae(t,`approvalDeltas[${r}]`);let n=Z(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:pe(t.token,`approvalDeltas[${r}].token`),spender:pe(t.spender,`approvalDeltas[${r}].spender`),owner:pe(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function Ur(e={}){ae(e,"input");let t=gt(e),r=t.tx==null?t:ae(t.tx,"tx"),n=Z(t.chainId??r.chainId,"chainId",{positive:!0}),o=pe(t.account??t.from??r.from,"account/from"),i=pe(t.destination??t.to??r.to,"destination/to"),a=String(Se(t.prepareHash,"prepareHash")).toLowerCase();if(!Li.test(a))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let s=t.route??t.venue;if(s==null)throw new TypeError("sign-time review: route/venue required");let c=t.decodedCalldata??t.decodedAction;if(c==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let l=String(Se(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!$i.test(l))throw new TypeError("sign-time review: calldata/data must be even-length hex");let u=t.policyChecks!==void 0&&t.policyChecks!==null,d=Di(u?t.policyChecks:[]),m=ji(t.simulation),f=Gi(t.assetDeltas),p=Wi(t.approvalDeltas),h=t.allowlistHits??[];if(!Array.isArray(h))throw new TypeError("sign-time review: allowlistHits must be an array");let g=m?.willRevert===!0||["failed","error"].includes(m?.status),b=m!=null&&m.willRevert===!1&&["ok","success"].includes(m.status),I=g||d.failed>0?"BLOCKED":b&&u&&d.checks.length>0&&f!=null?"READY":"UNKNOWN",w=typeof c=="string"?c:c.method??c.action??c.type??"transaction",E=`${I}: review ${w} on chain ${n}; policy ${d.passed} passed, ${d.failed} failed; ${f?.length??0} asset delta${f?.length===1?"":"s"}; local signature required`,P={reviewVersion:1,status:I,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:s,venue:t.venue??(typeof s=="string"?s:s.venue??s.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:pe(t.spender,"spender")},prepareHash:a,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:l,data:l,selector:l.length>=10?l.slice(0,10):null,value:Z(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:Z(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:Z(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:d,allowlistHits:h,assetDeltas:f,approvalDeltas:p,summary:E};return Hr(P)}var ki,$i,Li,Mi,Fi,Bi,De,zr=q(()=>{ki=/^0x[0-9a-f]{40}$/,$i=/^0x(?:[0-9a-f]{2})*$/,Li=/^(?:0x)?[0-9a-f]{64}$/,Mi=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,Fi=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,Bi=new Set([12,15,18,21,24]),De=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}}});import{createHash as Hi}from"node:crypto";function se(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))se(t);Object.freeze(e)}return e}function me(e,t){if(e==null||typeof e!="object"||Array.isArray(e))throw new TypeError(`prepare verification: ${t} must be an object`);return e}function yt(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(yt).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${yt(e[r])}`).join(",")}}`}function Jr(e){return Hi("sha256").update(yt(e),"utf8").digest("hex")}function Ji(e,t,r=500){let o=(e==null?t:String(e)).trim();return o?o.slice(0,r):t}function Yi(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function ve(e){let t=String(e||"").trim().toLowerCase().replace(/^0x/,"");return Ui.test(t)?t:""}function Yr(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 Xr(e,t="prepare verification"){if(me(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 zi)if(e[r])throw new Error(`${t}: prepared fact carries ${r}`);for(let r of Vi)if(e[r])throw new Error(`${t}: prepared fact claims executed ${r}`);return!0}function Xi(e){if(e==null)return se({status:"unavailable",willRevert:null,summary:"no simulation supplied",source:"unavailable"});me(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 se({status:r,willRevert:n,summary:Ji(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 Zi(e={},t={}){let r=Yr(e),n=e.localSignerEnvelope||e.envelope||{},o=t.provider||e.provider||e.source||n.provider||t.venue||e.venue||"unknown",i=t.kind||e.kind||e.artifactKind||n.action||e.action||"prepare",a=t.destination||e.destination||e.to||r?.to||n.destination||null,s=t.chainId??e.chainId??r?.chainId??n.chainId??null,c=t.account||e.account||e.from||r?.from||n.owner||null,l=[`Unsigned ${i} via ${o}`];return a&&l.push(`to ${a}`),s!=null&&s!==""&&l.push(`on chain ${s}`),t.note&&l.push(String(t.note)),l.push("for owner review only \u2014 not signed, not armed, not executed"),se({summary:l.join(" "),provider:String(o),kind:String(i),destination:a==null?null:String(a),chainId:s==null||s===""?null:String(s),account:c==null?null:String(c)})}function Qi({prepared:e={},env:t}={}){me(e,"prepared");let r=ve(e.prepareHash),n=typeof e.prepareMac=="string"&&e.prepareMac.length>=32,o=!1;if(r)try{o=ut(e)===String(e.prepareHash)}catch{o=!1}let i=!1,a=Yi(t);if(n&&a&&r)try{let u=lt(r,a);i=u.length>0&&u===String(e.prepareMac)}catch{i=!1}let s=n?bt.PREPARE_HMAC:r?bt.PREPARE_CHECKSUM:bt.NONE,c=[];r&&c.push(o?"prepare-body-sha256-bound":"prepare-hash-present-unverified"),n&&c.push(i?"keyed-prepare-mac-verified":"keyed-prepare-mac-present-unverified");let l=i?"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 se({kind:s,teeAttested:!1,cryptographicallyAttested:i,checksumBound:o,claims:c,notClaimed:[...Ki],custody:"none",execution:"prepare-only",note:l})}function ea(e,t,r){let n=Yr(e),o=e.localSignerEnvelope||e.envelope||{};try{let i=Ur({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 se({status:i.status,summary:i.summary,requiresLocalSignature:!0,custody:i.custody,execution:i.execution})}catch{return null}}function ta({prepared:e,simulation:t,intent:r,env:n,nowMs:o=Date.now()}={}){me(e,"prepared"),Xr(e);let i=Number(o);if(!Number.isSafeInteger(i)||i<=0)throw new TypeError("prepare verification: bounded createdAt required");let a=Xi(t??e.simulation??e.sim),s=Zi(e,r&&typeof r=="object"?r:{}),c=Qi({prepared:e,env:n}),l=ve(e.prepareHash)||null,u=l?ea(e,l,a):null,d={version:Vr,kind:Kr,prepareHash:l,simulation:a,intent:s,intentSummary:s.summary,attestation:c,review:u,custody:"none",execution:"prepare-only",signingReady:!1,broadcastReady:!1,executionReady:!1,createdAt:i};return se({...d,artifactHash:Jr(d)})}function Zr(e,t={}){let r=t.label||"prepare verification";if(me(e,"artifact"),Number(e.version)!==Vr)throw new Error(`${r}: unsupported verification artifact version`);if(e.kind!==Kr)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(ve(n)!==Jr(o))throw new Error(`${r}: artifactHash mismatch \u2014 verification artifact was altered`);if(t.prepareHash){let i=ve(t.prepareHash),a=ve(e.prepareHash);if(!i||i!==a)throw new Error(`${r}: verification artifact does not bind this prepare`)}return e}function Qr(e,t={}){me(e,"prepared");let r=t.artifact&&typeof t.artifact=="object"?t.artifact:ta({prepared:e,simulation:t.simulation,intent:t.intent,env:t.env,nowMs:t.nowMs});return Zr(r,{label:t.label||"prepare verification"}),{...e,prepareVerification:r}}function en(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 Zr(n,{label:r,...e.prepareHash?{prepareHash:e.prepareHash}:{}}),Xr(e,r),n}var Vr,Kr,bt,Ui,zi,Vi,Ki,Et=q(()=>{zr();dt();Vr=1,Kr="prepare-verification",bt=Object.freeze({NONE:"none",PREPARE_CHECKSUM:"prepare-checksum",PREPARE_HMAC:"prepare-hmac"}),Ui=/^(?:0x)?[0-9a-f]{64}$/i,zi=Object.freeze(["signature","signedTx","signedTransaction","rawTransaction","signedPayload","signedRaw"]),Vi=Object.freeze(["txid","txHash","transactionHash","broadcastHash"]),Ki=Object.freeze(["tee-attestation","remote-attestation","hardware-enclave","trusted-execution-environment","execution-authorization","signature","broadcast"])});var nn={};We(nn,{armPreparedAction:()=>xt,callSigner:()=>tn,queueOwnerAction:()=>rn});import{existsSync as ra,readFileSync as na}from"node:fs";import{request as oa}from"node:http";import ia from"node:path";function sa(e=process.env){let t=String(e.ORACLE_SIGNER_URL||aa).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 ca(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=ia.join(qe(),"signer","signer-token");return ra(t)?na(t,"utf8").trim():null}function tn(e,{method:t="GET",body:r=null,env:n=process.env,timeoutMs:o=4e3}={}){let i=sa(n),a=ca(n);return!i||!a?Promise.resolve({ok:!1,error:"local signer is not running"}):new Promise(s=>{let c=new URL(e,i),l=r?Buffer.from(JSON.stringify(r)):null,u=oa({hostname:c.hostname,port:c.port||80,path:c.pathname,method:t,timeout:o,headers:{authorization:`Bearer ${a}`,origin:i,...l?{"content-type":"application/json","content-length":l.length}:{}}},d=>{let m=[];d.on("data",f=>m.push(f)),d.on("end",()=>{let f=Buffer.concat(m).toString("utf8"),p={};try{p=f?JSON.parse(f):{}}catch{p={error:"signer refused"}}s({httpStatus:d.statusCode,...p})})});u.on("timeout",()=>{u.destroy(),s({ok:!1,error:"local signer timed out"})}),u.on("error",()=>s({ok:!1,error:"local signer is not running"})),l&&u.write(l),u.end()})}async function rn(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return tn("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function xt(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 en(e,{env:t,label:"armPreparedAction"}),rn(r,t)}var aa,St=q(()=>{Wr();Et();aa="http://127.0.0.1:9462"});J();it();J();var mo=5,at=[50,75,90],rr=Object.freeze({normal:{percentile:0,baseFeeMultiplier:2n,label:"normal"},fast:{percentile:1,baseFeeMultiplier:3n,label:"fast"},war:{percentile:2,baseFeeMultiplier:4n,label:"war"}});function ie(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 ho(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 nr(e={},t={}){let r=t.rpcCall||$,n=Number(e.chainId);if(!Number.isInteger(n))return{status:"error",error:"chainId is required",viable:!1};let o=rr[e.urgency||"fast"];if(!o)return{status:"error",viable:!1,error:`urgency must be one of: ${Object.keys(rr).join(", ")}`};let i,a,s,c;try{i=ie(e.maxFeePerGasWei,"maxFeePerGasWei"),a=ie(e.maxPriorityFeePerGasWei,"maxPriorityFeePerGasWei"),s=ie(e.gasLimit,"gasLimit"),c=ie(e.maxTotalGasWei,"maxTotalGasWei")}catch(x){return{status:"error",viable:!1,error:x.message}}let l,u;try{[l,u]=await Promise.all([r(n,"eth_feeHistory",[`0x${mo.toString(16)}`,"pending",at],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 d=ie(u?.baseFeePerGas,"baseFeePerGas")??ie(l?.baseFeePerGas?.[l.baseFeePerGas.length-1],"baseFeePerGas");if(d==null)return{status:"unavailable",viable:!1,error:"chain did not report a baseFeePerGas (pre-EIP-1559?)",notes:["this pricer is EIP-1559 only"]};let f=(Array.isArray(l?.reward)?l.reward:[]).map(x=>{try{return ie(x?.[o.percentile],"reward")}catch{return null}}).filter(x=>x!=null&&x>0n),p=ho(f),h=[];p==null&&h.push("no non-zero tips observed in recent blocks; using a 1 gwei floor");let g=p??1000000000n,b=d*o.baseFeeMultiplier+g,I=[];a!=null&&g>a&&(I.push({field:"maxPriorityFeePerGas",wanted:g.toString(),capped:a.toString()}),g=a,b=d*o.baseFeeMultiplier+g),i!=null&&b>i&&(I.push({field:"maxFeePerGas",wanted:b.toString(),capped:i.toString()}),b=i,g>b&&(g=b));let w=s!=null?s*b:null;c!=null&&w!=null&&w>c&&I.push({field:"totalGas",wanted:w.toString(),capped:c.toString()});let E=p==null||g>=p,P=c==null||w==null||w<=c,L=E&&P;return E||h.push(`tip cap ${g} is below the observed ${at[o.percentile]}th-percentile tip ${p}; this bid is unlikely to land`),P||h.push(`worst-case gas ${w} exceeds the ${c} total cap`),h.push("maxFeePerGas is a ceiling \u2014 unused headroom above basefee+tip is refunded, not spent"),{status:"ok",viable:L,chainId:n,urgency:o.label,baseFeePerGas:d.toString(),observedTip:p==null?null:p.toString(),percentile:at[o.percentile],maxFeePerGas:b.toString(),maxPriorityFeePerGas:g.toString(),worstCaseGasWei:w==null?null:w.toString(),clamps:I,notes:h}}J();var go=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"}}),wo=Object.freeze([{label:"eip1967",slot:"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"},{label:"zeppelinos",slot:"0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3"},{label:"eip1822",slot:"0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"}]),bo=`0x${"0".repeat(64)}`;function yo(e){return!e||e==="0x"||e===bo}async function or(e={},t={}){let r=t.rpcCall||$,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 i;try{i=await r(o,"eth_getCode",[n,"latest"],t)}catch(h){return{address:n,chainId:o,status:"unavailable",error:h?.message||"eth_getCode failed",risk:"unknown-risk",findings:[],isProxy:!1,codeSize:0,notes:["could not read contract code; treat as unverified"]}}if(!i||i==="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 a=[],s=[],c=i.slice(2).toLowerCase();for(let[h,g]of Object.entries(go))c.includes(h)&&s.push({selector:`0x${h}`,...g});let l=!1,u=null,d=null,m=await Promise.all(wo.map(async({label:h,slot:g})=>{try{let b=await r(o,"eth_getStorageAt",[n,g,"latest"],t);return{label:h,word:b,error:null}}catch{return{label:h,word:null,error:`proxy slot (${h}) unreadable; proxy status uncertain`}}}));for(let h of m)h.error&&a.push(h.error),!l&&h.word&&!yo(h.word)&&(l=!0,u=h.label,d=`0x${String(h.word).slice(-40)}`);l&&(s.push({selector:u,name:"proxy",weight:"high",note:"implementation is upgradeable \u2014 current behaviour is not a guarantee"}),a.push(`bytecode scan covers the proxy (${u}), not the implementation ${d} it delegates to`));let p=s.filter(h=>h.weight==="high").length>0?"high":s.length>0?"elevated":"unknown-risk";return p==="unknown-risk"&&a.push("no owner-power selectors found; this is weak evidence, not a safety guarantee"),{address:n,chainId:o,status:"ok",risk:p,findings:s,isProxy:l,proxyStandard:u,implementation:d,codeSize:Math.floor(c.length/2),notes:a}}J();var Eo="08c379a0",xo="4e487b71",So=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 vo(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===Eo)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===xo){let n=parseInt(t.slice(8,72),16);return{kind:"panic",code:n,reason:So[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 Ao(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 To(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 Io(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 ir(e={},t={}){let r=t.rpcCall||$,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 i=Io(o),a=[],s=null,c=!1,l=null;try{s=await r(n,"eth_call",[i,"pending"],t)}catch(p){let h=Ao(p);if(!To(p,!!h))return{status:"unavailable",willRevert:null,chainId:n,error:p?.message||"simulation unavailable",notes:["could not reach the node; this is NOT evidence the transaction would fail"]};c=!0,l=vo(h),h||(l.reason="execution reverted (node did not return a reason payload)",l.kind="revert-no-data")}if(c)return{status:"ok",willRevert:!0,chainId:n,revert:l,summary:`would REVERT: ${l.reason}`,notes:["simulated against current chain state; signing this now would burn gas and fail"]};let u=null,d=null;if(e.estimateGas!==!1)try{let p=await r(n,"eth_estimateGas",[i,"pending"],t);u=BigInt(p);let h=BigInt(Math.max(0,Math.floor(e.gasBufferPercent??20)));d=u+u*h/100n,a.push(`gasLimit includes a ${h}% buffer over the ${u} estimate`)}catch(p){a.push(`gas estimation failed: ${p?.message||"unknown"}`)}a.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 m=`0x${"0".repeat(64)}`,f=s===m;return f&&a.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:f,chainId:n,returnData:s,gasEstimate:u==null?null:u.toString(),gasLimit:d==null?null:d.toString(),summary:f?"executes but returns FALSE \u2014 the contract is rejecting this operation":u?`would succeed, ~${u} gas`:"would succeed",notes:a}}var _o=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 Po(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 Oo(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 ar(e,{minter:t,quantity:r}){let n=`0x${e.selector}`;for(let o of e.args)if(o==="to")n+=Oo(t);else if(o==="quantity")n+=Po(r);else throw new Error(`unsupported mint argument: ${o}`);return n}function No({address:e,chainId:t,minter:r,quantity:n,tx:o,nowMs:i,ttlMs:a=3e4}){if(!o?.gasLimit||!o?.maxFeePerGas)throw new Error("local-signer envelope requires gasLimit and maxFeePerGas");let s=Number(i??Date.now()),c=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:c,slippageBps:0,expiresAtMs:s+Math.min(Math.max(Number(a)||3e4,1e3),6e4),fee:{oracleFeeBps:0},artifact:{chainId:t,owner:r,contract:e,quantity:String(n),totalWei:c,transactions:[{chainId:t,from:r,to:e,data:o.data,value:c,gasLimit:String(o.gasLimit),maxFeePerGas:String(o.maxFeePerGas),...o.maxPriorityFeePerGas!=null?{maxPriorityFeePerGas:String(o.maxPriorityFeePerGas),type:2}:{}}]}}}async function Ro(e={},t={}){let r=t.rpcCall||$,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 i;try{i=await r(o,"eth_getCode",[n,"latest"],t)}catch(c){return{status:"unavailable",error:c?.message||"eth_getCode failed",found:[]}}if(!i||i==="0x")return{status:"ok",found:[],notes:["no contract deployed at this address"]};let a=i.slice(2).toLowerCase(),s=_o.filter(c=>a.includes(c.selector));return{status:"ok",address:n,chainId:o,found:s,notes:s.length?[]:["no known public mint selector found; this contract may use a custom or allowlist-only entrypoint"]}}async function Ce(e={},t={}){let r=String(e.contract||e.address||"").trim().toLowerCase(),n=Number(e.chainId),o=String(e.minter||e.from||"").trim().toLowerCase(),i=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(i)||i<1)return{status:"error",error:"quantity must be a positive integer"};if(!Number.isInteger(n))return{status:"error",error:"chainId is required"};let a=await Ro({address:r,chainId:n},t);if(a.status!=="ok")return{status:a.status,error:a.error};if(!a.found.length)return{status:"unsupported",error:"no known public mint function found in this contract's bytecode",notes:a.notes};let s=e.signature?a.found.find(w=>w.signature===e.signature):a.found[0];if(!s)return{status:"error",error:`requested signature ${e.signature} not present in this contract`,available:a.found.map(w=>w.signature)};let c=a.found.length>1&&!e.signature,l=await or({address:r,chainId:n},t),u=null;if(e.simulate!==!1&&(u=await ir({chainId:n,tx:{from:o,to:r,data:ar(s,{minter:o,quantity:i}),value:e.valueWei},gasBufferPercent:e.gasBufferPercent},t),u.willRevert===!0&&e.ignoreRevert!==!0))return{status:"would-revert",error:`mint would revert: ${u.revert.reason}`,simulation:u,mintFunction:s.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 d=e.gasLimit??(u?.gasLimit?Number(u.gasLimit):null),m=await nr({chainId:n,urgency:e.urgency||"war",gasLimit:d,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei,maxTotalGasWei:e.maxTotalGasWei},t);if(m.status!=="ok")return{status:"unavailable",error:m.error,notes:m.notes};let f;try{f=ar(s,{minter:o,quantity:i})}catch(w){return{status:"error",error:w.message}}let p={chainId:n,from:o,to:r,data:f,value:e.valueWei==null?"0":String(e.valueWei),gasLimit:d==null?null:String(d),maxFeePerGas:m.maxFeePerGas,maxPriorityFeePerGas:m.maxPriorityFeePerGas},h={ok:!0,skipped:!0,reason:"no gasLimit or cap supplied"};if(d!=null&&(e.maxTotalGasWei!=null||e.grant!=null)&&(h=ot({chainId:n,tx:{gasLimit:d,maxFeePerGas:m.maxFeePerGas,maxPriorityFeePerGas:m.maxPriorityFeePerGas},policy:{maxTotalGasWei:e.maxTotalGasWei,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei,grant:e.grant}}),!h.ok))return{status:"refused",error:`gas-war cap exceeded: ${h.reason||h.error}`,gas:m,capCheck:h};let g=[];c&&g.push(`contract exposes ${a.found.length} mint entrypoints (${a.found.map(w=>w.signature).join(", ")}); defaulted to ${s.signature} \u2014 pass signature to choose`),l.risk==="high"&&g.push(`contract risk HIGH: ${l.findings.map(w=>w.name).join(", ")}`),m.viable||g.push(m.notes[0]),h.skipped&&g.push("gas-war caps NOT enforced: supply gasLimit plus maxTotalGasWei or a grant");let b=null,I=null;try{b=No({address:r,chainId:n,minter:o,quantity:i,tx:p,nowMs:t.nowMs,ttlMs:e.ttlMs??e.expiresInMs})}catch(w){I=String(w?.message||w).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:p,localSignerEnvelope:b,localSignerBlockedReason:I,mintFunction:s.signature,alternatives:a.found.map(w=>w.signature),quantity:i,gas:m,simulation:u,contractRisk:{risk:l.risk,findings:l.findings,isProxy:l.isProxy},capCheck:h,warnings:g}}var ns=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"});function sr(e=process.env){return String(e.ORACLE_AUTONOMOUS_TRADING??"").trim()==="1"}J();function ua(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 on(e={},t={}){let n=e.actionMode==="execute"?"execute":e.actionMode||"alert_only",o=String(e.contract||"").trim().toLowerCase(),i=Number(e.chainId),a=[];if(!/^0x[a-f0-9]{40}$/.test(o))return{status:"error",error:"contract must be a 0x-prefixed EVM address"};if(!Number.isInteger(i))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:i,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 s=n;if(n==="execute")if(!sr(t.env||process.env))s="alert_only",a.push("DOWNGRADED to alert_only: autonomous trading is off \u2014 set ORACLE_AUTONOMOUS_TRADING=1 to let a trigger fire unattended");else{let c=ua(e.grant,{nowMs:t.nowMs});c.ok?(c.contract!==o||c.chainId!==i)&&(s="alert_only",a.push("DOWNGRADED to alert_only: grant does not match this contract/chain \u2014 a grant authorizes one exact target")):(s="alert_only",a.push(`DOWNGRADED to alert_only: ${c.problems.join("; ")}`))}return s==="alert_only"?a.push("alert_only: Oracle will notify and prepare an artifact; you sign it"):a.push("ARMED until mint opens: this trigger will submit one prepared, capped mint automatically when the mint opens"),{status:"ok",actionMode:s,requestedMode:n,downgraded:s!==n,contract:o,chainId:i,quantity:e.quantity==null?1:Number(e.quantity),urgency:e.urgency||"war",grant:s==="execute"?e.grant:null,armedUntil:s==="execute"?"mint-opens":null,mechanism:e.mechanism||null,marketplace:e.marketplace||null,provider:e.provider||null,slug:e.slug||null,mintTarget:e.mintTarget||null,priceWei:e.priceWei!=null?String(e.priceWei):null,maxTotalWei:e.maxTotalWei!=null?String(e.maxTotalWei):null,feeRecipient:e.feeRecipient||null,dropStart:e.dropStart!=null?String(e.dropStart):null,dropEnd:e.dropEnd!=null?String(e.dropEnd):null,notes:a}}function la(e={}){let t=String(e.mechanism||"").toLowerCase(),r=String(e.marketplace||"").toLowerCase(),n=String(e.provider||"").toLowerCase();return t==="seadrop"||r==="opensea"||n==="opensea-nft"}function da(e,{minter:t,nowMs:r=Date.now()}={}){let n=e?.transactions?.[0]||e?.tx;if(!n?.to||!n?.data)throw new Error("opensea mint missing unsigned transaction");if(!n.gasLimit||!n.maxFeePerGas)throw new Error("local-signer envelope requires gasLimit and maxFeePerGas");let o=Number(r),i=String(e.totalWei??n.value??"0");return{version:1,surface:"evm-nft",action:"mint",provider:"opensea-nft",owner:t,destination:n.to,contract:e.contract,quantity:String(e.quantity??1),totalWei:i,slippageBps:0,expiresAtMs:o+3e4,fee:{oracleFeeBps:0},artifact:{chainId:e.chainId,owner:t,contract:e.contract,quantity:String(e.quantity??1),totalWei:i,mintTarget:e.mintTarget||n.to,transactions:[{chainId:e.chainId,from:t,to:n.to,data:n.data,value:i,gasLimit:String(n.gasLimit),maxFeePerGas:String(n.maxFeePerGas),...n.maxPriorityFeePerGas!=null?{maxPriorityFeePerGas:String(n.maxPriorityFeePerGas),type:2}:{}}]}}}async function vt(e={},t={}){let r=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();if(e.dropStart!=null&&e.dropEnd!=null){let s=Number(e.dropStart),c=Number(e.dropEnd);if(Number.isFinite(s)&&Number.isFinite(c)&&c>s){let l=Math.floor(r/1e3),u=s>1e12?Math.floor(s/1e3):s,d=c>1e12?Math.floor(c/1e3):c;return{status:"ok",open:l>=u&&l<d,evidence:"publicDrop.window"}}}let n=t.rpcCall||$,o=String(e.contract||"").trim().toLowerCase(),i=Number(e.chainId);if(!/^0x[a-f0-9]{40}$/.test(o)||!Number.isInteger(i))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 s of a)try{let c=await n(i,"eth_call",[{to:o,data:s.selector},"latest"],t);if(c&&c!=="0x"){let l=BigInt(c)===1n;return{status:"ok",open:s.openWhen?l:!l,evidence:s.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 an(e={},t={}){if(e.status!=="ok")return{status:"error",error:"invalid trigger"};let r=await vt({contract:e.contract,chainId:e.chainId,dropStart:e.dropStart,dropEnd:e.dropEnd},t);if(!r.open)return{status:"waiting",open:!1,reason:r.notes?.[0]||`sale flag ${r.evidence||"unknown"} reports closed`};let n=e.minter||t.minter,o;if(la(e)){let c=t.prepareSeaDrop||(async(l,u)=>{let{openseaPrepareMint:d}=await Promise.resolve().then(()=>(jr(),Dr));return d(l,u)});try{let l=await c({chain:e.chainId,chainId:e.chainId,contract:e.contract,buyer:n,minter:n,quantity:e.quantity,slug:e.slug,mintTarget:e.mintTarget,priceWei:e.priceWei??"0",maxTotalWei:e.maxTotalWei??e.grant?.maxValueWei??"0",maxGasWei:e.grant?.maxTotalGasWei??e.maxTotalGasWei,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei,expiry:e.expiresAt},t);if((l?.status||(l?.transactions||l?.tx?"ok":"error"))!=="ok"&&!l?.transactions&&!l?.oraclePrepared)return{status:"blocked",open:!0,reason:l?.error||"seadrop prepare failed",prepared:l};let d=l.localSignerEnvelope;if(!d)try{d=da(l,{minter:n,nowMs:t.nowMs})}catch(m){return{status:e.actionMode==="execute"?"blocked":"alert",open:!0,reason:String(m?.message||m),prepared:{...l,status:"ok",localSignerBlockedReason:String(m?.message||m)},signed:!1}}o={status:"ok",...l,tx:l.tx||l.transactions?.[0],localSignerEnvelope:d}}catch(l){return{status:"blocked",open:!0,reason:String(l?.message||l),prepared:null}}}else o=await Ce({contract:e.contract,chainId:e.chainId,minter:n,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(o.status!=="ok")return{status:"blocked",open:!0,reason:o.error,prepared:o};if(e.actionMode==="execute"&&e.grant?.maxValueWei!=null){let c=BigInt(o.tx?.value||o.totalWei||"0");if(c>BigInt(e.grant.maxValueWei))return{status:"refused",open:!0,reason:`mint price ${c} exceeds granted maxValueWei ${e.grant.maxValueWei}`,prepared:o}}if(e.actionMode!=="execute")return{status:"alert",open:!0,actionMode:e.actionMode,prepared:o,signed:!1};let i=o.localSignerEnvelope;if(!i||i.version!==1||i.surface!=="evm-nft")return{status:"blocked",open:!0,reason:o.localSignerBlockedReason||"execute fire requires a v1 evm-nft local-signer envelope",prepared:o,signed:!1};let s=await(t.queueOwnerAction||(async(c,l)=>{let{armPreparedAction:u}=await Promise.resolve().then(()=>(St(),nn));return u(c,l)}))(o,t.env||process.env);return!s||s.ok!==!0?{status:"blocked",open:!0,reason:s?.error||"local signer refused the mint queue",prepared:o,queued:s||null,signed:!1}:{status:"fire",open:!0,actionMode:"execute",prepared:o,queued:s,signed:!1}}J();var Ms=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}]),R=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"}),fa=Object.freeze({1:{chain:"Ethereum",regime:R.BUILDER_AUCTION},137:{chain:"Polygon",regime:R.BUILDER_AUCTION},56:{chain:"BNB Chain",regime:R.BUILDER_AUCTION},43114:{chain:"Avalanche C-Chain",regime:R.BUILDER_AUCTION},988:{chain:"Stable Mainnet",regime:R.BUILDER_AUCTION},8453:{chain:"Base",regime:R.OP_STACK_SEQUENCER},10:{chain:"OP Mainnet",regime:R.OP_STACK_SEQUENCER},7777777:{chain:"Zora",regime:R.OP_STACK_SEQUENCER},81457:{chain:"Blast",regime:R.OP_STACK_SEQUENCER},42161:{chain:"Arbitrum One",regime:R.NITRO_FCFS},4663:{chain:"Robinhood Chain",regime:R.NITRO_FCFS},2741:{chain:"Abstract",regime:R.NITRO_FCFS},999:{chain:"HyperEVM",regime:R.HYPERBFT}}),pa=Object.freeze({solana:{chain:"Solana",regime:R.SOLANA_LEADER},bitcoin:{chain:"Bitcoin",regime:R.BITCOIN_FEE_RATE},ordinals:{chain:"Bitcoin Ordinals",regime:R.BITCOIN_FEE_RATE}}),ma=Object.freeze({[R.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"]},[R.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"]},[R.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"]},[R.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"]},[R.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"]},[R.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 sn(e){let t=e&&typeof e=="object"?e.chainId??e.family??e.chain:e,r=String(t??"").trim().toLowerCase(),n=pa[r]||fa[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=ma[n.regime];return{chainId:Number.isInteger(Number(t))?Number(t):null,chain:n.chain,regime:n.regime,...o,notes:[...o.notes]}}var qs=Object.freeze({"0x02c88989":"setSaleIsActive(bool)","0x34918dfd":"flipSaleState()","0x5a67de07":"setSaleState(uint8)","0x3f4ba83a":"unpause()","0x16c38b3c":"setPaused(bool)","0xb66a0e5d":"startSale()","0xee1cc944":"setMintActive(bool)"});function ha(e){let t=sn(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 cn(e){let t=ha(e);return{chainId:Number(e),mempoolVisible:t.visible,reason:t.reason,fallback:t.visible?null:"poll sale state with probeMintOpenFast"}}St();import{Interface as ya,MaxUint256 as xc,isAddress as Sc,keccak256 as vc,toUtf8Bytes as Ac}from"ethers";import{Interface as wa,isAddress as tc}from"ethers";import{isAddress as Js}from"ethers";var ic=new wa(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as ba,isAddress as cc}from"ethers";var fc=new ba(["function approve(address spender,uint256 amount) returns (bool)"]),pc=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var Nc=new ya(["function approve(address spender,uint256 amount) returns (bool)"]);var Ea=new Set([10n,8453n,84532n,42161n,421614n,11155420n,7777777n]);function un(e){try{return Ea.has(BigInt(e))}catch{return!1}}Et();var dn=`oracle mint <watch|check|prepare> <contract> --chain <id> [options]
5
6
 
6
7
  oracle mint check <contract> --chain <id> [--rpc-url <url>] [--json]
7
8
  oracle mint prepare <contract> --chain <id> --minter <address> --max-total-gas-wei <wei> [--rpc-url <url>] [--queue] [--json]
@@ -12,11 +13,11 @@ Safe posture:
12
13
  --queue sends one prepared envelope to the loopback local signer for owner approval
13
14
  this command never signs or broadcasts
14
15
  --execute, --arm, and --fire are refused because autonomous trigger attestation minting is not shipped
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
- `),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 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};
16
+ `,ln=/^0x[0-9a-fA-F]{40}$/,xa=["--execute","--arm","--fire"];function U(e,t){let r=e.indexOf(t);return r>=0?e[r+1]:void 0}function Sa(e){let t=e.reduce((o,i,a)=>i==="--rpc-url"?[...o,a]: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 he(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 va(e,{requireMinter:t=!1}={}){let r=String(e[1]||"").trim().toLowerCase(),n=Number(U(e,"--chain")),o=String(U(e,"--minter")||"").trim().toLowerCase();if(!ln.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&&!ln.test(o))throw new Error("--minter must be a 0x-prefixed EVM address");return{contract:r,chainId:n,...t?{minter:o}:{},quantity:Number(he(U(e,"--quantity")??"1","quantity",{min:1})),urgency:U(e,"--urgency")||"war",signature:U(e,"--signature"),valueWei:he(U(e,"--value-wei"),"valueWei",{optional:!0}),gasLimit:he(U(e,"--gas-limit"),"gasLimit",{optional:!0,min:1}),maxTotalGasWei:he(U(e,"--max-total-gas-wei"),"maxTotalGasWei",{optional:!0,min:1}),maxFeePerGasWei:he(U(e,"--max-fee-per-gas-wei"),"maxFeePerGasWei",{optional:!0,min:1}),maxPriorityFeePerGasWei:he(U(e,"--max-priority-fee-per-gas-wei"),"maxPriorityFeePerGasWei",{optional:!0})}}function Tt(e,t={}){return{...e,...t,broadcast:!1}}function It(e,t,r){e.write(`${JSON.stringify(t,null,r?0:2)}
17
+ `)}var Aa={createTrigger:on,evaluateTrigger:an,checkOpen:vt,prepare:Ce,queuePrepared:xt,mempoolSupport:cn,isRollup:un};async function Ta(e=[],{out:t=process.stdout,err:r=process.stderr,env:n=process.env,deps:o={}}={}){let i=xa.find(u=>e.includes(u));if(i)return r.write(`oracle mint: ${i} refused; autonomous trigger attestation minting is not shipped
18
+ `),1;if(e.length===0||["--help","-h","help"].includes(e[0]))return t.write(dn),0;let a={...Aa,...o},s=e[0],c=e.includes("--json"),l=e.includes("--queue");try{if(!["watch","check","prepare"].includes(s))return r.write(`oracle mint: unknown verb '${s}'. Try: oracle mint --help
19
+ `),1;let u=va(e,{requireMinter:s!=="check"}),d=Sa(e),m={env:n,...d?{rpcUrl:d}:{}};if(l&&u.maxTotalGasWei==null)return r.write(`oracle mint: --max-total-gas-wei is required before --queue
20
+ `),1;if(l&&a.isRollup(u.chainId))return r.write(`oracle mint: queue refused on rollups because the prepared envelope does not yet carry required l1FeeWei and operatorFeeWei attestations
21
+ `),1;if(s==="check"){let g=await a.checkOpen({contract:u.contract,chainId:u.chainId},m);return It(t,Tt({status:g.status,sale:g,mempool:a.mempoolSupport(u.chainId),queued:!1}),c),0}let f;if(s==="prepare"){let g=await a.prepare(u,m);f={status:g?.status||(g?.localSignerEnvelope?"ok":"error"),prepared:g,signed:!1}}else{let g=a.createTrigger({...u,actionMode:"alert_only"},{env:n});f=await a.evaluateTrigger(g,{...m,minter:u.minter,...u})}if(!l||!["alert","fire","ok"].includes(f?.status))return It(t,Tt(f||{status:"error"},{queued:!1}),c),0;let p=f.prepared,h=await a.queuePrepared(Qr(p,{simulation:p?.simulation,env:n}),n);return h?.ok!==!0?(r.write(`oracle mint: ${h?.error||"local signer refused the pending mint"}
22
+ `),1):(It(t,Tt(f,{queued:!0,queue:h}),c),0)}catch(u){return r.write(`oracle mint: ${u?.message||u}
23
+ `),1}}var Gc={name:"mint",summary:"evaluate and queue one bounded mint for local owner approval; never signs or broadcasts",usage:dn,run:e=>Ta(e.argv||[])};export{Gc as default,Ta as runMintCommand};