@oracle-agent/oracle 0.12.0 → 0.13.1

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 (124) hide show
  1. package/README.md +31 -4
  2. package/SETUP.md +5 -2
  3. package/artifacts/specialist-packs/oracle-full-crypto.json +3 -0
  4. package/dist/address-book.mjs +2 -2
  5. package/dist/assets/profiles/_template/SOUL.md +54 -0
  6. package/dist/assets/profiles/_template/profile.json +22 -0
  7. package/dist/assets/profiles/bitcoin-agent/SOUL.md +31 -0
  8. package/dist/assets/profiles/bitcoin-agent/profile.json +32 -0
  9. package/dist/assets/profiles/hyperliquid-agent/SOUL.md +34 -0
  10. package/dist/assets/profiles/hyperliquid-agent/profile.json +38 -0
  11. package/dist/assets/profiles/oracle/SOUL.md +134 -0
  12. package/dist/assets/profiles/oracle/profile.json +40 -0
  13. package/dist/assets/profiles/polymarket-agent/SOUL.md +35 -0
  14. package/dist/assets/profiles/polymarket-agent/profile.json +34 -0
  15. package/dist/assets/profiles/profile.schema.json +90 -0
  16. package/dist/assets/profiles/protocol-builder/SOUL.md +57 -0
  17. package/dist/assets/profiles/protocol-builder/profile.json +39 -0
  18. package/dist/assets/profiles/robinhood-agent/SOUL.md +53 -0
  19. package/dist/assets/profiles/robinhood-agent/profile.json +41 -0
  20. package/dist/assets/profiles/solana-agent/SOUL.md +37 -0
  21. package/dist/assets/profiles/solana-agent/profile.json +38 -0
  22. package/dist/assets/profiles/stable-agent/SOUL.md +43 -0
  23. package/dist/assets/profiles/stable-agent/profile.json +38 -0
  24. package/dist/assets/skills/balance/SKILL.md +176 -0
  25. package/dist/assets/skills/bitcoin-l1.md +33 -0
  26. package/dist/assets/skills/chain-defi-ecosystem-profiling.md +27 -0
  27. package/dist/assets/skills/evm-contract-research.md +27 -0
  28. package/dist/assets/skills/hyperliquid.md +26 -0
  29. package/dist/assets/skills/multichain-exec-desk.md +33 -0
  30. package/dist/assets/skills/oracle-action-semantics/SKILL.md +40 -0
  31. package/dist/assets/skills/oracle-best-execution/SKILL.md +127 -0
  32. package/dist/assets/skills/oracle-best-execution.md +27 -0
  33. package/dist/assets/skills/oracle-bitcoin/SKILL.md +53 -0
  34. package/dist/assets/skills/oracle-chain-graphs-telegram-cards/SKILL.md +59 -0
  35. package/dist/assets/skills/oracle-chat/SKILL.md +61 -0
  36. package/dist/assets/skills/oracle-chat/chain.SKILL.md +31 -0
  37. package/dist/assets/skills/oracle-chat/setup.SKILL.md +37 -0
  38. package/dist/assets/skills/oracle-circuit-breaker/SKILL.md +51 -0
  39. package/dist/assets/skills/oracle-contract-research/SKILL.md +55 -0
  40. package/dist/assets/skills/oracle-desk/SKILL.md +58 -0
  41. package/dist/assets/skills/oracle-desk.md +27 -0
  42. package/dist/assets/skills/oracle-dex-launch/SKILL.md +38 -0
  43. package/dist/assets/skills/oracle-equities/SKILL.md +62 -0
  44. package/dist/assets/skills/oracle-grants/SKILL.md +69 -0
  45. package/dist/assets/skills/oracle-hypercore-staking/SKILL.md +57 -0
  46. package/dist/assets/skills/oracle-hyperliquid/SKILL.md +56 -0
  47. package/dist/assets/skills/oracle-meme-token-sniper/SKILL.md +73 -0
  48. package/dist/assets/skills/oracle-multichain-nft-launch/SKILL.md +338 -0
  49. package/dist/assets/skills/oracle-multichain-token-launch/SKILL.md +300 -0
  50. package/dist/assets/skills/oracle-nft-gacha-launch/SKILL.md +48 -0
  51. package/dist/assets/skills/oracle-nft-mint-gas-war/SKILL.md +63 -0
  52. package/dist/assets/skills/oracle-polymarket/SKILL.md +60 -0
  53. package/dist/assets/skills/oracle-protocol-builder/SKILL.md +59 -0
  54. package/dist/assets/skills/oracle-protocol-security/SKILL.md +60 -0
  55. package/dist/assets/skills/oracle-public-product/SKILL.md +44 -0
  56. package/dist/assets/skills/oracle-receipts/SKILL.md +52 -0
  57. package/dist/assets/skills/oracle-receipts.md +29 -0
  58. package/dist/assets/skills/oracle-rfq-tokenized-assets/SKILL.md +69 -0
  59. package/dist/assets/skills/oracle-smart-wallet-scanner/SKILL.md +49 -0
  60. package/dist/assets/skills/oracle-solana/SKILL.md +65 -0
  61. package/dist/assets/skills/oracle-solana-nft/SKILL.md +54 -0
  62. package/dist/assets/skills/oracle-token-research/SKILL.md +67 -0
  63. package/dist/assets/skills/solana.md +22 -0
  64. package/dist/bin/desk-server.mjs +56 -11
  65. package/dist/bin/oracle-data-mcp.mjs +6 -6
  66. package/dist/bin/oracle-equities.mjs +20 -0
  67. package/dist/bin/oracle-init.mjs +19 -19
  68. package/dist/bin/oracle-public-server.mjs +4 -4
  69. package/dist/bin/oracle-route.mjs +13 -13
  70. package/dist/bin/oracle-scan.mjs +10 -10
  71. package/dist/bin/oracle.mjs +35 -27
  72. package/dist/cli/commands/auth.mjs +11 -11
  73. package/dist/cli/commands/bootstrap.mjs +6 -6
  74. package/dist/cli/commands/chain.mjs +12 -12
  75. package/dist/cli/commands/chat.mjs +39 -29
  76. package/dist/cli/commands/data-mcp.mjs +2 -2
  77. package/dist/cli/commands/data.mjs +5 -5
  78. package/dist/cli/commands/doctor.mjs +3 -3
  79. package/dist/cli/commands/equities.mjs +15 -0
  80. package/dist/cli/commands/farm.mjs +59 -0
  81. package/dist/cli/commands/follow.mjs +28 -0
  82. package/dist/cli/commands/gate.mjs +4 -4
  83. package/dist/cli/commands/harness.mjs +15 -0
  84. package/dist/cli/commands/init.mjs +3 -3
  85. package/dist/cli/commands/mcp.mjs +50 -23
  86. package/dist/cli/commands/model.mjs +44 -34
  87. package/dist/cli/commands/plugins.mjs +38 -0
  88. package/dist/cli/commands/prepare.mjs +2 -2
  89. package/dist/cli/commands/public.mjs +3 -3
  90. package/dist/cli/commands/resolve.mjs +23 -0
  91. package/dist/cli/commands/route.mjs +2 -2
  92. package/dist/cli/commands/scan.mjs +2 -2
  93. package/dist/cli/commands/setup.mjs +12 -12
  94. package/dist/cli/commands/sign.mjs +19 -2
  95. package/dist/cli/commands/swap.mjs +36 -0
  96. package/dist/cli/commands/upgrade.mjs +2 -2
  97. package/dist/cli/commands/version.mjs +2 -2
  98. package/dist/data/desk-data.mjs +53 -10
  99. package/dist/data/names.mjs +2 -0
  100. package/dist/data/providers/farming.mjs +2 -0
  101. package/dist/equities/index.mjs +1 -0
  102. package/dist/index.mjs +58 -15
  103. package/dist/public-api/agent-grants.mjs +3 -0
  104. package/dist/router/index.mjs +2 -2
  105. package/dist/scanner/index.mjs +3 -3
  106. package/package.json +8 -3
  107. package/public/oracle-splash/_variants/ice.html +2073 -0
  108. package/public/oracle-splash/_variants/ivory.html +2075 -0
  109. package/public/oracle-splash/assets/agents/claude.png +0 -0
  110. package/public/oracle-splash/assets/agents/codex.png +0 -0
  111. package/public/oracle-splash/assets/desktop-app.jpg +0 -0
  112. package/public/oracle-splash/assets/hero/cli-session-poster.jpg +0 -0
  113. package/public/oracle-splash/assets/hero/cli-session.mp4 +0 -0
  114. package/public/oracle-splash/assets/hero/cli-session.webm +0 -0
  115. package/public/oracle-splash/assets/hero/orb-poster.jpg +0 -0
  116. package/public/oracle-splash/assets/hero/orb.webm +0 -0
  117. package/public/oracle-splash/assets/hero/risk-session-poster.jpg +0 -0
  118. package/public/oracle-splash/assets/hero/risk-session.mp4 +0 -0
  119. package/public/oracle-splash/assets/hero/risk-session.webm +0 -0
  120. package/public/oracle-splash/assets/hero/route-session-poster.jpg +0 -0
  121. package/public/oracle-splash/assets/hero/route-session.mp4 +0 -0
  122. package/public/oracle-splash/assets/hero/route-session.webm +0 -0
  123. package/public/oracle-splash/downloads/index.html +241 -0
  124. package/public/oracle-splash/index.html +1211 -242
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as Io}from"node:http";import{readFileSync as gn,existsSync as ko}from"node:fs";import{dirname as No,join as Ge,normalize as Co,sep as Po}from"node:path";import{fileURLToPath as To}from"node:url";import{createHash as _n}from"node:crypto";var te=1,Xe=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),In=Object.freeze(["read","simulate"]),Qe=1e4,Ze=1440*60,et=128,tt=256,nt=64,rt=256,ot=/^0x[0-9a-fA-F]{40}$/,kn=/^[a-z][a-z0-9_-]*:[a-z0-9._-]+$/,Nn=/^[a-z][a-z0-9_-]*:\*$/,Cn=/^[A-Za-z0-9._:-]+$/,Pn=/^[A-Za-z0-9._:-]+$/,st=/^(0|[1-9][0-9]*)$/,M=class extends Error{constructor(t){let r=t.map(n=>`${n.field}: ${n.message}`);super(`invalid grant (${t.length} error${t.length===1?"":"s"}): ${r.join("; ")}`),this.name="GrantValidationError",this.errors=t}};function at(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Tn(e){if(typeof e=="bigint")return e>=0n?e.toString(10):null;if(typeof e=="number")return!Number.isSafeInteger(e)||e<0?null:String(e);if(typeof e=="string"){let t=e.trim();return st.test(t)?t:null}return null}function F(e){if(typeof e=="bigint")return e<0n||e>BigInt(Number.MAX_SAFE_INTEGER)?null:Number(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0?null:e;if(typeof e=="string"){let t=e.trim();if(!st.test(t))return null;let r=Number(t);return Number.isSafeInteger(r)?r:null}return null}function Se(e){let t=String(e).split(":")[0];return In.includes(t)}function ve(e,t={}){let r=[],n=(u,m)=>r.push({field:u,message:m});if(!at(e))return n("grant","grant must be a plain object"),{ok:!1,errors:r,grant:null};for(let u of Object.keys(e))Xe.includes(u)||n(u,"unknown field is not allowed");for(let u of Xe)(!(u in e)||e[u]==null)&&n(u,"required field is missing");if(r.length)return{ok:!1,errors:r,grant:null};let o={},s=F(e.chainId);s==null||s<=0?n("chainId","must be a positive integer chain id"):o.chainId=s;for(let u of["agentAddress","accountAddress"]){let m=e[u];typeof m!="string"||!ot.test(m.trim())?n(u,"must be a 0x-prefixed 20-byte hex address"):o[u]=m.trim().toLowerCase()}if(!Array.isArray(e.actions)||e.actions.length===0)n("actions","must be a non-empty array of action scopes");else if(e.actions.length>nt)n("actions",`too many actions (max ${nt})`);else{let u=[];for(let m of e.actions){let l=typeof m=="string"?m.trim():null;if(!l){n("actions","action entries must be non-empty strings");continue}if(l.includes("*")){t.allowWildcardActions===!0&&Nn.test(l)?u.push(l):n("actions",`broad wildcard action "${l}" is rejected (fail closed)`);continue}if(!kn.test(l)){n("actions",`malformed action "${l}" (expected verb:resource)`);continue}u.push(l)}o.actions=[...new Set(u)].sort()}if(!Array.isArray(e.targets))n("targets","must be an array of contract addresses");else if(e.targets.length>rt)n("targets",`too many targets (max ${rt})`);else{let u=[];for(let m of e.targets){let l=typeof m=="string"?m.trim():null;if(!l||!ot.test(l)){n("targets",`target "${m}" must be a 0x-prefixed 20-byte hex address (wildcards not allowed)`);continue}u.push(l.toLowerCase())}if(o.targets=[...new Set(u)].sort(),o.targets.length===0&&Array.isArray(o.actions)){let m=o.actions.filter(l=>!Se(l));(m.length>0||o.actions.length===0)&&n("targets",`empty targets are only allowed for read/simulate scopes (blocked by: ${m.join(", ")||"no valid actions"})`)}}for(let u of["maxValueWei","maxGasWei"]){let m=Tn(e[u]);m==null?n(u,"must be a non-negative integer wei amount"):o[u]=m}let a=F(e.maxSlippageBps);a==null||a>Qe?n("maxSlippageBps",`must be an integer between 0 and ${Qe}`):o.maxSlippageBps=a;let i=864e10,c=F(e.expiresAt);if(c==null||c<=0)n("expiresAt","must be a positive unix-seconds timestamp");else if(c>i)n("expiresAt","exceeds the max unix-seconds timestamp (pass seconds, not milliseconds)");else if(o.expiresAt=c,t.now!=null){let u=F(t.now);u==null?n("expiresAt","opts.now must be a unix-seconds integer"):c<=u?n("expiresAt",`grant is expired (expiresAt ${c} <= now ${u})`):c-u>Ze&&n("expiresAt",`grant exceeds the hard 24-hour TTL (${Ze} seconds)`)}let d=typeof e.nonce=="string"?e.nonce.trim():F(e.nonce)!=null?String(F(e.nonce)):null;!d||d.length>et||!Cn.test(d)?n("nonce",`must be a non-empty string (max ${et} chars, [A-Za-z0-9._:-])`):o.nonce=d;let h=typeof e.revocationKey=="string"?e.revocationKey.trim():null;return!h||h.length>tt||!Pn.test(h)?n("revocationKey",`must be a non-empty public identifier (max ${tt} chars, [A-Za-z0-9._:-])`):o.revocationKey=h,r.length?{ok:!1,errors:r,grant:null}:{ok:!0,errors:[],grant:o}}function ae(e,t={}){let{ok:r,errors:n,grant:o}=ve(e,t);if(!r)throw new M(n);return o}function Ae(e,t={}){let r=ae(e,t),o=Object.keys(r).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(r[s])}`);return`{"version":${te},${o.join(",")}}`}function ie(e,t={}){return _n("sha256").update(Ae(e,t),"utf8").digest("hex")}function it(e,t){let r=F(t),n=F(at(e)?e.expiresAt:null);return r==null||n==null?!0:n<=r}var ct="oracle-connect-request",Rn="oracle-unsigned-grant",$n="oracle-grant-canonical-json-utf8-v1",O=class extends Error{constructor(t,r){super(`secret material must never appear in a public API object (at ${t}, rule: ${r})`),this.name="SecretLeakError",this.path=t,this.rule=r}},On=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,Ln=Object.freeze(["privkey","wif","xprv","seed"]);function xe(e){let t=String(e),r=t.toLowerCase().replace(/[\s._-]+/g,"");return On.test(t)||Ln.includes(r)}var lt=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),ut=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function Un(e){return e.replace(/"([A-Za-z0-9_-]+)"\s*:\s*"(?:0x)?([0-9a-fA-F]{64})"/g,(t,r)=>ut.includes(String(r).toLowerCase().replace(/[_-]/g,""))?`"${r}":"<hex64>"`:t)}function dt(e){let t;try{t=JSON.stringify(e)}catch(o){throw new O("$",`unserializable-payload: ${String(o?.message||o)}`)}if(t===void 0)return"null";let r=Un(t);for(let{rule:o,re:s}of lt)if(s.test(r))throw new O("$<serialized>",o);if(/(?:^|[^0-9a-fA-Fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/.test(r))throw new O("$<serialized>","raw-32-byte-hex-embedded");return JSON.parse(t,(o,s)=>{if(o&&xe(o))throw new O(`$<serialized>.${o}`,"forbidden-key-name");return s}),t}function R(e,t="$",r=new Set,n=""){if(e==null)return e;if(typeof e=="string"){let o=ut.includes(String(n).toLowerCase().replace(/[_-]/g,""));for(let{rule:s,re:a}of lt)if(!(o&&s.startsWith("raw-32-byte-hex"))&&a.test(e))throw new O(t,s);return e}if(typeof e!="object"||r.has(e)||(r.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[o,s]of e.entries()){if(typeof o=="string"&&xe(o))throw new O(`${t}[${JSON.stringify(o)}]`,"forbidden-key-name");R(o,`${t}[key]`,r),R(s,`${t}[${String(o)}]`,r)}return e}if(e instanceof Set){let o=0;for(let s of e.values())R(s,`${t}[${o++}]`,r);return e}if(Array.isArray(e))return e.forEach((o,s)=>R(o,`${t}[${s}]`,r)),e;for(let[o,s]of Object.entries(e)){if(xe(o))throw new O(`${t}.${o}`,"forbidden-key-name");R(s,`${t}.${o}`,r,o)}return e}function ne(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))ne(t)}return e}function pt(e,t){let r=Number(typeof e=="string"?e.trim():e);if(!Number.isSafeInteger(r)||r<=0)throw new M([{field:t,message:"must be a positive unix-seconds integer"}]);return r}function ft(e){if(e?.now==null)throw new M([{field:"opts.now",message:"explicit reference time is required for live grant construction"}]);return pt(e.now,"opts.now")}function Mn(e){return new Date(e*1e3).toISOString()}function Bn(e,t){let r=e.actions.every(n=>Se(n));return["ORACLE \u2014 CONNECT AGENT (unsigned grant, you sign it, we never do)","=================================================================",`Grant ID: ${t}`,`Version: ${te}`,`Chain: ${e.chainId}`,`Agent: ${e.agentAddress}`,`Your account: ${e.accountAddress}`,`Actions: ${e.actions.join(", ")}`,`Targets: ${e.targets.length?e.targets.join(", "):"(none \u2014 read/simulate only)"}`,`Max value: ${e.maxValueWei} wei`,`Max gas: ${e.maxGasWei} wei`,`Max slippage: ${e.maxSlippageBps} bps`,`Expires: ${Mn(e.expiresAt)} (unix ${e.expiresAt})`,`Nonce: ${e.nonce}`,`Revocation: ${e.revocationKey}`,"-----------------------------------------------------------------",r?"Scope: read/simulate only \u2014 this grant cannot move funds.":"Scope: includes state-changing actions bounded by the caps above.","Self-custodial: this payload is UNSIGNED and contains public data only.","Sign the bytes below with YOUR wallet; Oracle never holds your keys."].join(`
3
- `)}function mt(e={},t={}){if(e==null||typeof e!="object"||Array.isArray(e))throw new M([{field:"request",message:"request must be a plain object"}]);let r=ft(t),{ttlSeconds:n,...o}=e,s={...o};if(n!=null){if(s.expiresAt!=null)throw new M([{field:"ttlSeconds",message:"pass either ttlSeconds or expiresAt, not both"}]);let c=pt(n,"ttlSeconds");s.expiresAt=r+c}let a=ae(s,{now:r,allowWildcardActions:t.allowWildcardActions===!0}),i=ne({kind:ct,version:te,grant:a});return R(i)}function ht(e={},t={}){let r=ft(t),n=e&&e.kind===ct?e.grant:e,o=ae(n,{now:r,allowWildcardActions:t.allowWildcardActions===!0}),s=Ae(o),a=ie(o),i=Buffer.from(s,"utf8"),c=ne({kind:Rn,unsigned:!0,payload:ne({version:te,grantId:a,grant:o,canonical:s}),signing:ne({scheme:$n,message:s,bytesHex:`0x${i.toString("hex")}`,byteLength:i.length,sha256:a}),render:Bn(o,a)});return R(c)}var G=Object.freeze({ACTIVE:"active",EXPIRED:"expired",REVOKED:"revoked",INVALID:"invalid"});function bt(e){if(e==null)return[];if(Array.isArray(e))return e;if(e instanceof Map)return[...e.values()];if(typeof e[Symbol.iterator]=="function")return[...e];throw new TypeError("grant store must be an array, Map, or iterable of grant records")}function qn(e){return e&&typeof e=="object"&&!Array.isArray(e)&&e.grant!=null?{grant:e.grant,revoked:e.revoked===!0||e.revokedAt!=null}:{grant:e,revoked:!1}}function Ee(e){let t=Number(typeof e=="string"?e.trim():e);if(!Number.isSafeInteger(t)||t<0)throw new TypeError("an explicit unix-seconds `now` is required (deterministic liveness, no wall-clock fallback)");return t}function Dn(e,t,r){if(e==null)return!1;if(typeof e=="function")return e(t,r)===!0;let n=[t,r.revocationKey];return e instanceof Set?n.some(o=>e.has(o)):Array.isArray(e)?n.some(o=>e.includes(o)):typeof e.has=="function"?n.some(o=>e.has(o)):!1}function yt(e,{now:t,revoked:r}={}){let n=Ee(t),{grant:o,revoked:s}=qn(e),{ok:a,grant:i}=ve(o);if(!a)return{status:G.INVALID,id:null,grant:null};let c=ie(i);return s||Dn(r,c,i)?{status:G.REVOKED,id:c,grant:i}:it(i,n)?{status:G.EXPIRED,id:c,grant:i}:{status:G.ACTIVE,id:c,grant:i}}function gt(e,{now:t,revoked:r,agentAddress:n,accountAddress:o,chainId:s}={}){let a=Ee(t),i=n!=null?String(n).trim().toLowerCase():null,c=o!=null?String(o).trim().toLowerCase():null,d=s!=null?Number(s):null,h=[];for(let u of bt(e)){let{status:m,id:l,grant:w}=yt(u,{now:a,revoked:r});m===G.ACTIVE&&(i!=null&&w.agentAddress!==i||c!=null&&w.accountAddress!==c||d!=null&&w.chainId!==d||h.push(Object.freeze({id:l,grant:w})))}return h.sort((u,m)=>u.id<m.id?-1:u.id>m.id?1:0),R(Object.freeze(h))}function wt(e,t,{now:r,revoked:n}={}){let o=Ee(r),s=String(t??"").trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(s))return null;for(let a of bt(e)){let i=yt(a,{now:o,revoked:n});if(i.status!==G.INVALID&&i.id===s)return R(Object.freeze({id:i.id,status:i.status,grant:i.grant}))}return null}import{Interface as Ot,getAddress as ar,id as Lt}from"ethers";import{createHash as Fn}from"node:crypto";var Hn=new Set([408,425,429,500,502,503,504]),St=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Vn=2,vt=4e3,xt=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],zn=new Set([301,302,303,307,308]),At=3;function jn(e){let t=String(e||"").toLowerCase();return xt.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function Kn(e){let t={};for(let[r,n]of Object.entries(e||{}))jn(r)||(t[r]=n);return t}function Gn(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 Wn(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var _e=new Map;function Yn(e,t,r){let n={};for(let[c,d]of Object.entries(r||{}))n[c.toLowerCase()]=d;let o=Object.keys(n).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),a=[...new Set([...xt,...o])].sort().map(c=>`${c}=${n[c]??""}`).join(`
4
- `),i=Fn("sha256").update(a).digest("hex").slice(0,32);return`${e} ${t} ${i}`}function Jn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,vt):Math.min(250*2**e,vt)+Math.floor(Math.random()*100)}var Xn=e=>new Promise(t=>setTimeout(t,e));async function Qn(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s}){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let c=String(e),d={...n||{}};for(let h=0;h<=At;h+=1){let u=await t(c,{method:r,headers:d,body:o,signal:a.signal,redirect:"manual"}),m=await u.text(),l=null;if(m)try{l=JSON.parse(m)}catch{l=null}if(zn.has(u.status)){if(r!=="GET"&&r!=="HEAD"){let A=new Error(`HTTP ${u.status} ${r} ${c} redirected non-idempotent request`);throw A.status=u.status,A.body=l??m.slice(0,300),A}if(h===At)throw new Error(`HTTP redirect loop for ${e}`);let w=Gn(u.headers?.get?.("location"),c);Wn(w,c)||(d=Kn(d)),c=w;continue}if(!u.ok){let w=new Error(`HTTP ${u.status} ${r} ${c}`);throw w.status=u.status,w.retryAfter=u.headers?.get?.("retry-after")??null,w.body=l??m.slice(0,300),w}return l??m}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(i)}}async function N(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),s={Accept:"application/json",...t.headers||{}},a=t.body;a!=null&&typeof a!="string"&&(s["Content-Type"]=s["Content-Type"]||"application/json",a=JSON.stringify(a));let i=Number.isInteger(t.retries)?Math.max(t.retries,0):Vn,c=async()=>{let l;for(let w=0;w<=i;w++)try{return await Qn(e,{fetchImpl:r,method:o,headers:s,body:a,timeoutMs:n})}catch(A){l=A;let v=A?.status,_=A?.name==="AbortError",k=new Set([408,425,429]),q=v!=null?k.has(v)||Hn.has(v)&&St.has(o):!_&&St.has(o);if(w===i||!q)throw A;await Xn(Jn(w,A?.retryAfter))}throw l};if(!(t.dedupe!==!1&&o==="GET"&&a==null))return c();let h=Yn(o,e,s),u=_e.get(h);if(u)return u;let m=c().finally(()=>_e.delete(h));return _e.set(h,m),m}async function I(e){let t=Date.now();try{let r=await e();return{ok:!0,ms:Date.now()-t,data:r}}catch(r){return{ok:!1,ms:Date.now()-t,error:String(r.message||r),status:r.status??null}}}async function H(e,t,r){let n=Array.from(e),o=Math.max(1,Math.min(Number(t)||1,n.length||1)),s=new Array(n.length),a=0;return await Promise.all(Array.from({length:o},async()=>{for(;a<n.length;){let i=a++;s[i]=await r(n[i],i)}})),s}var Et={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}},Zn=new Map(Object.values(Et).map(e=>[e.chainId,e]));function _t(e){return Zn.get(Number(e))||null}function It(e,t=process.env){let r=_t(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 er,getAddress as tr}from"ethers";var kt=new er(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ie(e,t){try{return tr(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var nr={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 rr(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=It(e,r);return n||nr[Number(e)]||null}var or=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function sr(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!or.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}async function B(e,t,r=[],n={}){let o=String(t||"");sr(o);let s=rr(e,n);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let i=await N(s,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:r},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(i?.error){let c=new Error(i.error.message||JSON.stringify(i.error));throw c.code=i.error.code,c}return i.result}async function ke(e,t={}){let r=await B(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Ne(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await B(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Nt(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Ie(e.token||e.tokenAddress,"token"),o=Ie(e.owner,"owner"),s=Ie(e.spender,"spender"),a=kt.encodeFunctionData("allowance",[o,s]),i=await B(r,"eth_call",[{to:n,data:a},e.blockTag||"latest"],t),c=kt.decodeFunctionResult("allowance",i),d=BigInt(c[0]);return{chainId:r,token:n,owner:o,spender:s,allowance:d.toString(),allowanceHex:`0x${d.toString(16)}`,blockTag:e.blockTag||"latest"}}var xs=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),Ce=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),Pe=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var ce=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venues:[]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venues:[]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venues:[]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);var Ct=new Ot(["function decimals() view returns (uint8)","function symbol() view returns (string)"]),Pt=new Ot(["function isApprovedForAll(address owner, address operator) view returns (bool)","function name() view returns (string)"]),ir=Lt("Approval(address,address,uint256)"),Js=Lt("ApprovalForAll(address,address,bool)"),cr=1e4,lr=2e5,ur=Object.freeze({"0x1111111254eeb25477b68fb85ed929f73a960582":"1inch v5 Router","0x111111125421ca6dc452d289314280a0f8842a65":"1inch v6 Router","0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45":"Uniswap Universal Router","0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad":"Uniswap Universal Router","0x000000000022d473030f116ddee9f6b43ac78ba3":"Permit2","0xe592427a0aece92de3edee1f18e0157c05861564":"Uniswap v3 Router","0x7a250d5630b4cf539739df2c5dacb4c659f2488d":"Uniswap v2 Router","0xdef1c0ded9bec7f1a1670819833240f027b25eff":"0x Exchange Proxy","0x2626664c2603336e57b271c5c0b26f421741e481":"Uniswap SwapRouter02 (Base)","0x6131b5fae19ea4f9d964eac0408e4408b66337b5":"KyberSwap Meta Aggregator","0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC (token contract)"}),dr=Object.freeze([{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"},{address:"0x1111111254eeb25477b68fb85ed929f73a960582",label:"1inch v5 Router"},{address:"0x111111125421ca6dc452d289314280a0f8842a65",label:"1inch v6 Router"},{address:"0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45",label:"Uniswap Universal Router"},{address:"0xe592427a0aece92de3edee1f18e0157c05861564",label:"Uniswap v3 Router"},{address:"0x7a250d5630b4cf539739df2c5dacb4c659f2488d",label:"Uniswap v2 Router"},{address:"0xdef1c0ded9bec7f1a1670819833240f027b25eff",label:"0x Exchange Proxy"},{address:"0x2626664c2603336e57b271c5c0b26f421741e481",label:"Uniswap SwapRouter02"}]),pr=Object.freeze([{address:"0x1e0049783f008a0085193e00003d00cd54003c71",label:"OpenSea Seaport Conduit"},{address:"0x00000000000000adc04c56bf30ac9d3c0aaf14dc",label:"Seaport 1.5"},{address:"0x0000000000000068f116a894984e2db1123eb395",label:"Seaport 1.6"},{address:"0x00000000000001ad428e4906ae43d8f9852d0dd6",label:"Seaport 1.4"},{address:"0x000000000000ad05ccc4f10045630fb830b95127",label:"Blur Marketplace"},{address:"0x00000000000000000000000000000000000000a5",label:"Blur Execution Delegate"},{address:"0xf42aa99f011a1fa7cda90e5e98b277e306bca83e",label:"Rarible Transfer Proxy"},{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"}]),fr=Object.freeze({1:[{address:"0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",name:"Bored Ape Yacht Club"},{address:"0x60e4d786628fea6478f785a6d7e704777c86a7c6",name:"Mutant Ape Yacht Club"},{address:"0xed5af388653567af2f388e6224dc7c4b3241c544",name:"Azuki"},{address:"0x8a90cab2b38dba80c64b7734e58ee1db38b8992e",name:"Doodles"},{address:"0x49cf6f5d44e70224e2e23fdcdd2c053f30ada28b",name:"CloneX"},{address:"0x23581767a106ae21c074b2276d25e5c3e136a68b",name:"Moonbirds"}]}),mr=Object.freeze({1:[{address:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",symbol:"USDC",decimals:6},{address:"0xdac17f958d2ee523a2206206994597c13d831ec7",symbol:"USDT",decimals:6},{address:"0x6b175474e89094c44da98b954eedeac495271d0f",symbol:"DAI",decimals:18},{address:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",symbol:"WETH",decimals:18},{address:"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",symbol:"WBTC",decimals:8}],8453:[{address:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],42161:[{address:"0xaf88d065e77c8cc2239327c5edb3a432268e5831",symbol:"USDC",decimals:6},{address:"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9",symbol:"USDT",decimals:6},{address:"0x82af49447d8a07e3bd95bd0d56f35241523fbab1",symbol:"WETH",decimals:18}],10:[{address:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],137:[{address:"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",symbol:"USDC",decimals:6},{address:"0xc2132d05d31c914a87c6611c10748aeb04b58e8f",symbol:"USDT",decimals:6}]}),hr=(1n<<256n)-1n,br=hr/2n,yr=4320*60*60*1e3,gr=360*60*1e3,wr=600*1e3,Sr=45*1e3,vr=512,Ar=128,Tt=new Map,Te=new Map,Rt=new Map;function W(e){return e?.cache===!1?!1:!e?.fetchImpl||e.cache===!0}function $e(e,t,r){let n=e.get(t);return n?Date.now()-n.at>r?(e.delete(t),null):n:null}function le(e,t,r,n){for(e.delete(t),e.set(t,{at:Date.now(),value:r});e.size>n;){let o=e.keys().next();if(o.done)break;e.delete(o.value)}}function xr(e,t){try{return ar(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function Er(e){return`0x${e.slice(2).toLowerCase().padStart(64,"0")}`}function $t(e){return`0x${String(e).slice(-40).toLowerCase()}`}function _r({unlimited:e,spenderLabel:t,lastActivityAt:r}){if(e)return"unlimited";if(!t)return"unknown-spender";if(r){let n=Date.parse(r);if(Number.isFinite(n)&&Date.now()-n>yr)return"stale"}return"scoped"}function Ir(e,t,r){if(r)return"UNLIMITED";if(t==null)return e.toString();let n=10n**BigInt(t),o=e/n,s=e%n;if(s===0n)return o.toLocaleString("en-US");let a=s.toString().padStart(t,"0").replace(/0+$/,"").slice(0,6);return`${o.toLocaleString("en-US")}${a?`.${a}`:""}`}async function kr(e,t,r,n){let o=`${e}:${t}`,s=n?.get(o);if(s)return s;if(W(r)){let i=$e(Tt,o,gr);if(i)return i.value}let a=(async()=>{let i=async u=>{try{let m=Ct.encodeFunctionData(u,[]),l=await B(e,"eth_call",[{to:t,data:m},"latest"],r);return!l||l==="0x"?null:Ct.decodeFunctionResult(u,l)[0]}catch{return null}},[c,d]=await Promise.all([i("decimals"),i("symbol")]),h={decimals:c==null?null:Number(c),symbol:d==null?null:String(d).slice(0,24)};return W(r)&&le(Tt,o,h,vr),h})();return n?.set(o,a),a}async function Nr(e,t,r){let n=Math.min(Math.max(Number(r.lookbackBlocks)||cr,1),lr),o=await ke(e,r);if(!Number.isFinite(o))throw new Error("chain head unavailable");let s=Math.max(0,o-n),a=await B(e,"eth_getLogs",[{fromBlock:`0x${s.toString(16)}`,toBlock:"latest",topics:[ir,Er(t)]}],r);if(!Array.isArray(a))throw new Error("log scan returned no array");let i=new Map;for(let c of a){let d=String(c?.address||"").toLowerCase(),h=c?.topics?.[2];!d||!h||i.set(`${d}:${$t(h)}`,{token:d,spender:$t(h)})}return{pairs:[...i.values()],fromBlock:s,toBlock:o}}function Cr(e){return(mr[e]||[]).flatMap(r=>dr.map(n=>({token:r.address,spender:n.address,symbol:r.symbol,decimals:r.decimals})))}async function Pr(e,t,r={}){let n=[],o="direct-probe",s=null,a=Cr(e),i=Re(e),c=W(r)&&$e(Te,e,wr)?.value===!1;if(a.length===0&&i.length===0&&c)return{scan:{chainId:e,status:"unconfigured",method:o,error:"no Approval log access and no candidate token or collection set for this chain"},approvals:[]};try{let d=await Nr(e,t,r);n=d.pairs,o="log-scan",s={fromBlock:d.fromBlock,toBlock:d.toBlock},W(r)&&le(Te,e,!0,64)}catch{if(W(r)&&le(Te,e,!1,64),n=a,n.length===0&&i.length===0)return{scan:{chainId:e,status:"unconfigured",method:o,error:"no Approval log access and no candidate token or collection set for this chain"},approvals:[]}}try{let d=new Map,u=(await H(n,r.concurrency||4,async l=>{try{let w=await Nt({chainId:e,token:l.token,owner:t,spender:l.spender},r),A=BigInt(w.allowance);if(A<=0n)return null;let v=l.symbol?{symbol:l.symbol,decimals:l.decimals??null}:await kr(e,l.token,r,d),_=A>=br,k=ur[l.spender]||null;return{id:`${e}:${l.token}:${l.spender}`,chainId:e,standard:"erc20",token:l.token,tokenSymbol:v.symbol,decimals:v.decimals,spender:l.spender,spenderLabel:k,allowance:A.toString(),allowanceDisplay:Ir(A,v.decimals,_),unlimited:_,lastActivityAt:null,risk:_r({unlimited:_,spenderLabel:k,lastActivityAt:null})}}catch{return null}})).filter(Boolean),m=await Rr(e,t,r);return{scan:{chainId:e,status:"ok",method:o,pairsProbed:n.length,collectionsProbed:Re(e).length,...s||{}},approvals:[...u,...m]}}catch(d){return{scan:{chainId:e,status:"unavailable",method:o,error:String(d?.message||d).slice(0,200)},approvals:[]}}}async function Tr(e,t,r,n,o){try{let s=Pt.encodeFunctionData("isApprovedForAll",[r,n]),a=await B(e,"eth_call",[{to:t,data:s},"latest"],o);return!a||a==="0x"?null:!!Pt.decodeFunctionResult("isApprovedForAll",a)[0]}catch{return null}}function Re(e){return(fr[e]||[]).flatMap(r=>pr.map(n=>({collection:r.address,collectionName:r.name,operator:n.address,operatorLabel:n.label})))}async function Rr(e,t,r){let n=Re(e);return n.length===0?[]:(await H(n,r.concurrency||4,async s=>await Tr(e,s.collection,t,s.operator,r)!==!0?null:{id:`${e}:${s.collection}:${s.operator}:all`,chainId:e,standard:"erc721",token:s.collection,tokenSymbol:s.collectionName,decimals:null,spender:s.operator,spenderLabel:s.operatorLabel,allowance:null,allowanceDisplay:"ALL ITEMS",unlimited:!0,lastActivityAt:null,risk:"operator-all"})).filter(Boolean)}async function Ut(e={},t={}){let r=xr(e.owner||e.address,"owner"),n=new Map(ce.map(l=>[l.chainId,l])),o=Array.isArray(e.chainIds)&&e.chainIds.length?[...new Set(e.chainIds.map(Number))].filter(l=>n.has(l)):[...n.keys()],s=`${r}:${[...o].sort((l,w)=>l-w).join(",")}:${e.lookbackBlocks??""}`,a=W(t)&&!e.refresh;if(a){let l=$e(Rt,s,Sr);if(l)return{...l.value,cached:!0,cachedAgeMs:Date.now()-l.at}}let i=await H(o,e.concurrency||3,l=>Pr(l,r,{...t,lookbackBlocks:e.lookbackBlocks})),c=i.flatMap(l=>l.approvals),d=i.map(l=>l.scan),h=d.find(l=>l.method==="log-scan"&&l.toBlock),u=d.some(l=>l.method==="direct-probe"&&l.status==="ok"),m={provider:"approvals",operation:"scan",readOnly:!0,queriedAt:new Date().toISOString(),owner:r,scannedRange:h?`last ${h.toBlock-h.fromBlock} blocks`:u?"known routers, live allowance probe":null,approvals:c,scans:d,warnings:["Approval discovery is scoped. Log scanning is used where the endpoint permits it; otherwise a curated router set is probed directly. An empty result means nothing was found in that scope, not that the wallet is safe.","NFT operator approval (setApprovalForAll) is checked against a curated collection and marketplace set on supported chains only. A collection outside that set is not checked."]};return a&&le(Rt,s,m,Ar),{...m,cached:!1,cachedAgeMs:0}}import{getAddress as Qr}from"ethers";var Mt="mainnet-beta",$r="https://api.mainnet-beta.solana.com",Oe="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";function Or(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||$r).trim()}function z(e,t="address"){let r=String(e||"").trim();if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(r))throw new Error(`solana-rpc: ${t} must be a base58 public key`);return r}function Lr(e,t){return t?[...e,{commitment:t}]:e}async function Bt(e,t=[],r={}){let n=String(e||"");if(n==="sendTransaction"||n==="sendRawTransaction"||n==="requestAirdrop"||n==="requestAirDrop"||/airdrop/i.test(n)||/^send/i.test(n))throw new Error(`solana-rpc: ${n} refused \u2014 @oracle-agent/oracle is prepare-only (no broadcast/airdrop)`);let o=await N(Or(r),{method:"POST",body:{jsonrpc:"2.0",id:r.id||1,method:e,params:t},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3});if(o?.error)throw new Error(`solana-rpc ${e}: ${o.error.message||JSON.stringify(o.error)}`);return o?.result}async function qt(e={},t={}){let r=z(e.address||e.owner,"address"),n=await Bt("getBalance",Lr([r],e.commitment),t);return{provider:"solana-rpc",cluster:Mt,address:r,lamports:String(n?.value??0),slot:n?.context?.slot??null,raw:n}}function Ur(e={}){let t=e.account?.data?.parsed?.info||{},r=t.tokenAmount||{};return{pubkey:e.pubkey,mint:t.mint||null,owner:t.owner||null,amount:String(r.amount??"0"),decimals:r.decimals??null,uiAmount:r.uiAmount??null,uiAmountString:r.uiAmountString??null,raw:e}}async function Le(e={},t={}){let r=z(e.owner||e.address,"owner"),n=e.mint?{mint:z(e.mint,"mint")}:{programId:z(e.programId||Oe,"token program")},o={encoding:"jsonParsed"};e.commitment&&(o.commitment=e.commitment);let s=await Bt("getTokenAccountsByOwner",[r,n,o],t),a=Array.isArray(s?.value)?s.value.map(Ur):[];return{provider:"solana-rpc",cluster:Mt,owner:r,filter:n,slot:s?.context?.slot??null,accounts:a,raw:s}}var Mr="mainnet",Br="https://mempool.space/api",qr="https://mempool.space/testnet/api";function Dt(e={}){return String(e.network||process.env.BTC_NETWORK||Mr).trim().toLowerCase()==="testnet"?"testnet":"mainnet"}function Dr(e={}){return e.baseUrl?String(e.baseUrl).replace(/\/$/,""):process.env.BTC_ESPLORA_URL?String(process.env.BTC_ESPLORA_URL).replace(/\/$/,""):Dt(e)==="testnet"?qr:Br}function V(e,t="address"){let r=String(e||"").trim();if(!/^(bc1|tb1|bcrt1)[a-z0-9]{20,90}$/i.test(r)&&!/^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(r))throw new Error(`bitcoin-esplora: ${t} must look like a Bitcoin address`);return r}async function Fr(e,t={}){let r=`${Dr(t)}${e.startsWith("/")?e:`/${e}`}`,o=await(t.fetchImpl||fetch)(r,{method:"GET",headers:{accept:"application/json,text/plain;q=0.9,*/*;q=0.8"},signal:AbortSignal.timeout(t.timeoutMs??12e3)}),s=await o.text();if(!o.ok)throw new Error(`bitcoin-esplora GET ${e}: HTTP ${o.status} ${s.slice(0,160)}`);return s}async function Hr(e,t={}){let r=await Fr(e,t);try{return JSON.parse(r)}catch{return r}}async function Ft(e={},t={}){let r=V(e.address||e.addr,"address"),n=await Hr(`/address/${r}`,t),o=n.chain_stats||{},s=n.mempool_stats||{},a=Number(o.funded_txo_sum||0)+Number(s.funded_txo_sum||0),i=Number(o.spent_txo_sum||0)+Number(s.spent_txo_sum||0);return{provider:"bitcoin-esplora",network:Dt(t),address:r,balanceSats:String(a-i),chainStats:o,mempoolStats:s,raw:n}}var Ht="ORACLE_ALLOW_CUSTOM_PROVIDER_URL";function Y({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:Vt(t)};let i;try{i=new URL(a)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=i.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([Vt(t),...r]).has(c)){let h=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return i.protocol==="http:"&&!h?{baseUrl:a,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:a,trusted:!0,host:c}}if(String(process.env[Ht]||"")==="1")return{baseUrl:a,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${Ht}=1 to permit it)`);return{baseUrl:a,trusted:!1,host:c}}function Vt(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function j(e,t,r){let n={...e};if(!r)return n;for(let[o,s]of Object.entries(t||{}))s&&(n[o]=s);return n}function Ue(e={}){return String(e.baseUrl||process.env.BTC_META_API_URL||process.env.UNISAT_API_URL||"").trim().replace(/\/$/,"")}var Vr=["open-api.unisat.io","open-api-testnet.unisat.io","api.bestinslot.xyz","api.hiro.so"];function zr(e={}){let t=e.apiKey||process.env.UNISAT_API_KEY||process.env.BESTINSLOT_API_KEY||process.env.BTC_META_API_KEY||"",r=!1;try{let n=Ue(e);if(n){let o=new URL(n).host,s=new URL(n).protocol,a=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(o);r=Vr.includes(o)&&(s==="https:"||a)}}catch{r=!1}return j({accept:"application/json","user-agent":"oracle-btc-meta/0.1"},{authorization:t?`Bearer ${t}`:"","x-api-key":t},r)}async function zt(e,t={}){let n=await(t.fetchImpl||fetch)(e,{method:"GET",headers:zr(t),signal:AbortSignal.timeout(t.timeoutMs??12e3)}),o=await n.text(),s;try{s=JSON.parse(o)}catch{s=o}if(!n.ok)throw new Error(`bitcoin-meta GET ${e}: HTTP ${n.status} ${String(o).slice(0,160)}`);return s}async function jt(e={},t={}){let r=V(e.address||e.addr,"address"),n=Ue(t);if(!n)return{provider:"bitcoin-meta",address:r,ok:!1,balances:[],error:"no indexer configured (set BTC_META_API_URL or vendor API key env)"};let o=[`${n}/v1/indexer/address/${r}/runes/balance-list?start=0&limit=100`,`${n}/v1/runes/address/${r}`,`${n}/runes/balance/${r}`,`${n}/address/${r}/runes`],s=null;for(let a of o)try{let i=await zt(a,t),c=jr(i);return{provider:"bitcoin-meta",address:r,ok:!0,count:c.length,balances:c,source:a}}catch(i){s=i}return{provider:"bitcoin-meta",address:r,ok:!1,balances:[],error:String(s?.message||s||"all indexer paths failed")}}function jr(e){let t=e?.data?.detail||e?.data?.list||e?.data||e?.balances||e?.results||e?.runes||(Array.isArray(e)?e:[]);return(Array.isArray(t)?t:[]).map(n=>({rune:n.rune||n.runeid||n.runeId||n.spacedRune||n.name||n.ticker||null,runeId:n.runeid||n.runeId||n.id||null,amount:String(n.amount??n.balance??n.total??n.qty??"0"),symbol:n.symbol||null,divisibility:n.divisibility??n.div??null,raw:n}))}async function ue(e={},t={}){let r=V(e.address||e.addr,"address"),n=Ue(t);if(!n)return{provider:"bitcoin-meta",address:r,ok:!1,inscriptions:[],error:"no indexer configured \u2014 address-indexed lookups need a keyed indexer (BTC_META_API_URL + UNISAT_API_KEY / BESTINSLOT_API_KEY). ordinals.com recursive is keyless but has no address index.",unknownNotEmpty:!0,keylessAlternatives:["btc_inscription_info (by inscription id)","btc_meta_health"]};let o=Math.min(Number(e.limit||50),200),s=[`${n}/v1/indexer/address/${r}/inscription-data?cursor=0&size=${o}`,`${n}/v1/inscriptions/address/${r}?limit=${o}`,`${n}/address/${r}/inscriptions?limit=${o}`],a=null;for(let i of s)try{let c=await zt(i,t),d=Kr(c);return{provider:"bitcoin-meta",address:r,ok:!0,count:d.length,inscriptions:d,source:i}}catch(c){a=c}return{provider:"bitcoin-meta",address:r,ok:!1,inscriptions:[],error:String(a?.message||a||"all indexer paths failed")}}function Kr(e){let t=e?.data?.inscription||e?.data?.detail||e?.data?.list||e?.data||e?.inscriptions||e?.results||(Array.isArray(e)?e:[]);return(Array.isArray(t)?t:[]).map(n=>({id:n.inscriptionId||n.id||n.inscription_id||null,number:n.inscriptionNumber??n.number??null,sat:n.sat||n.satoshi||null,contentType:n.contentType||n.content_type||null,utxo:n.utxo||n.output||(n.txid!=null?`${n.txid}:${n.vout??n.n}`:null),raw:n}))}var Gr="https://api.hyperliquid.xyz/info",Wr="https://api.hyperliquid-testnet.xyz/info";function Yr({testnet:e,baseUrl:t}={}){if(t)return t.replace(/\/$/,"").endsWith("/info")?t:`${t.replace(/\/$/,"")}/info`;if(process.env.HL_INFO_URL)return process.env.HL_INFO_URL;if(process.env.HL_API_URL){let r=process.env.HL_API_URL.replace(/\/$/,"");return r.endsWith("/info")?r:`${r}/info`}return e||process.env.HL_TESTNET==="1"?Wr:Gr}async function Me(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let r=Yr(t);return N(r,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Kt(e={}){return Me({type:"allMids"},e)}async function Gt(e,t={}){if(!e)throw new Error("hlClearinghouse requires user address");return Me({type:"spotClearinghouseState",user:e},t)}async function Wt(e,t={}){if(!e)throw new Error("hlUserState requires user");return Me({type:"clearinghouseState",user:e},t)}var Jr="https://coins.llama.fi";function Xr(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Jr).replace(/\/$/,"")}async function Yt(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return N(`${Xr(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}var Zr="TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",Xt=Object.freeze({ETH:"coingecko:ethereum",POL:"coingecko:polygon-ecosystem-token",BNB:"coingecko:binancecoin",AVAX:"coingecko:avalanche-2",HYPE:"coingecko:hyperliquid",USDT0:"coingecko:tether",SOL:"coingecko:solana",BTC:"coingecko:bitcoin"});function J(e={},t){return{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,env:e.env,...e[t]||{}}}function de(e,...t){for(let r of t){let n=String(e?.[r]||"").trim();if(n)return n}return null}function Jt(e){if(!e)return null;try{return Qr(String(e).trim().toLowerCase())}catch{throw new Error("portfolio: EVM address must be a valid 20-byte address")}}function Fe(e={},t=process.env){let r=e.addresses||{},n=Jt(r.evm||e.evmAddress||de(t,"ORACLE_EVM_ADDRESS","ORACLE_DEFAULT_ADDRESS","MAD_OPERATOR_ADDRESS")),o=r.solana||e.solanaAddress||de(t,"ORACLE_SOLANA_ADDRESS"),s=r.bitcoin||e.bitcoinAddress||de(t,"ORACLE_BITCOIN_ADDRESS"),a=Jt(r.hyperliquid||e.hyperliquidAddress||de(t,"ORACLE_HYPERLIQUID_ADDRESS")||n);return{evm:n,solana:o?z(o,"portfolio Solana address"):null,bitcoin:s?V(s,"portfolio Bitcoin address"):null,hyperliquid:a}}function pe(e,t){let r=BigInt(String(e||"0")),n=Number(t);if(!Number.isInteger(n)||n<0||n>36)throw new Error("portfolio: decimals must be an integer from 0 to 36");if(n===0)return r.toString();let o=r<0n,s=o?-r:r,a=10n**BigInt(n),i=s/a,c=String(s%a).padStart(n,"0").replace(/0+$/,"");return`${o?"-":""}${i}${c?`.${c}`:""}`}function re(e){let t=Number(e);return Number.isFinite(t)?t:null}function De(e){return Number.isFinite(e)?Number(e.toFixed(2)):null}function X(e){let t=Number(e);return Number.isFinite(t)&&t!==0}function Qt(e,t){let r=Xt[t],n=r?e?.coins?.[r]:null,o=Number(n?.price);return{key:r||null,priceUsd:Number.isFinite(o)?o:null,timestamp:n?.timestamp??null,confidence:n?.confidence??null}}function eo(e){let t=new Map;for(let r of e)if(r?.ok)for(let n of r.data?.accounts||[]){let o=BigInt(String(n.amount||"0"));if(o===0n||!n.mint)continue;let s=`${n.mint}:${n.decimals??"unknown"}`,a=t.get(s)||{mint:n.mint,amountRaw:0n,decimals:n.decimals??null,programs:new Set,accounts:0};a.amountRaw+=o,a.accounts+=1,r.program&&a.programs.add(r.program),t.set(s,a)}return[...t.values()].map(r=>{let n=r.amountRaw.toString(),o=r.decimals==null?null:pe(n,r.decimals),s=r.decimals===0&&r.amountRaw===1n;return{mint:r.mint,amountRaw:n,amount:o,decimals:r.decimals,tokenPrograms:[...r.programs],accountCount:r.accounts,verification:"unverified",classification:s?"collectible-candidate":"fungible-or-unclassified",priceUsd:null,usdValue:null}})}function Be(e,t){return{family:e,status:"unsupported",reason:t}}function qe(e,t){if(!e||e.status!=="ok")return e;let r=Qt(t,e.symbol),n=re(e.amount),o=n!=null&&r.priceUsd!=null?De(n*r.priceUsd):null;return{...e,price:r,usdValue:o}}async function Zt(e={},t={}){let r=new Date().toISOString(),n=Fe(e,t.env||process.env),o=e.includePrices!==!1,s=e.includeTokens!==!1,a=e.includeCollectibles!==!1,i=new Map(ce.map(f=>[f.chainId,f])),c=Array.isArray(e.evmChainIds)&&e.evmChainIds.length?[...new Set(e.evmChainIds.map(Number))]:[...i.keys()],d=[...new Set(Object.values(Xt))],h=o?I(()=>Yt(d,J(t,"prices"))):Promise.resolve({ok:!1,ms:0,error:"price lookup disabled"}),u=H(c,e.concurrency||5,async f=>{let g=i.get(f);if(!g)return{family:"evm",chainId:f,name:null,address:n.evm,status:"unsupported",error:"chainId is not in Oracle's configured EVM registry"};if(!n.evm)return{family:"evm",chainId:f,name:g.name,address:null,status:"not-configured",error:"set ORACLE_EVM_ADDRESS or pass addresses.evm"};let S={...J(t,"evm"),rpcUrl:e.rpcUrls?.[f]||t.evm?.rpcUrls?.[f]},E=await I(()=>Ne(f,n.evm,S));if(!E.ok)return{family:"evm",chainId:f,name:g.name,address:n.evm,status:"unavailable",latencyMs:E.ms,error:E.error};let U=g.nativeCurrency?.decimals??18,$=g.nativeCurrency?.symbol||"NATIVE",b=E.data.balanceWei;return{family:"evm",chainId:f,name:g.name,address:n.evm,status:"ok",latencyMs:E.ms,native:{status:"ok",symbol:$,amountRaw:b,decimals:U,amount:pe(b,U)},fungibleTokens:{status:s?"unavailable":"not-requested",assets:[],reason:s?"EVM JSON-RPC cannot enumerate wallet tokens without an address indexer":"token discovery disabled"},collectibles:{status:a?"unavailable":"not-requested",assets:[],reason:a?"EVM JSON-RPC cannot enumerate wallet NFTs without an address indexer":"collectible discovery disabled"},source:"evm-rpc"}}),m=(async()=>{if(!n.solana)return{family:"solana",name:"Solana Mainnet",address:null,status:"not-configured",error:"set ORACLE_SOLANA_ADDRESS or pass addresses.solana"};let f=J(t,"solana"),g=await I(()=>qt({address:n.solana},f)),S=s||a?await Promise.all([I(()=>Le({owner:n.solana,programId:Oe},f)).then(T=>({...T,program:"spl-token"})),I(()=>Le({owner:n.solana,programId:Zr},f)).then(T=>({...T,program:"token-2022"}))]):[],E=eo(S),U=E.filter(T=>T.classification==="collectible-candidate"),$=E.filter(T=>T.classification!=="collectible-candidate"),b=S.filter(T=>!T.ok).map(T=>T.error);return{family:"solana",name:"Solana Mainnet",address:n.solana,status:g.ok||S.some(T=>T.ok)?"ok":"unavailable",native:g.ok?{status:"ok",symbol:"SOL",amountRaw:g.data.lamports,decimals:9,amount:pe(g.data.lamports,9),slot:g.data.slot}:{status:"unavailable",symbol:"SOL",error:g.error},fungibleTokens:{status:s?b.length===S.length?"unavailable":b.length?"partial":"ok":"not-requested",assets:s?$:[],errors:b,note:"SPL accounts are unverified until a metadata/indexer source confirms symbol and spam status"},collectibles:{status:a?b.length===S.length?"unavailable":"partial":"not-requested",assets:a?U:[],errors:b,note:"decimals=0 and amount=1 is only a collectible candidate, not verified NFT metadata"},source:"solana-rpc"}})(),l=(async()=>{if(!n.bitcoin)return{family:"bitcoin",name:"Bitcoin Mainnet",address:null,status:"not-configured",error:"set ORACLE_BITCOIN_ADDRESS or pass addresses.bitcoin"};let f=J(t,"bitcoin"),g=J(t,"bitcoinMeta"),[S,E,U]=await Promise.all([I(()=>Ft({address:n.bitcoin},f)),s?I(()=>jt({address:n.bitcoin},g)):Promise.resolve({ok:!1,ms:0,error:"token discovery disabled"}),a?I(()=>ue({address:n.bitcoin},g)):Promise.resolve({ok:!1,ms:0,error:"collectible discovery disabled"})]),$=E.ok?E.data:null,b=U.ok?U.data:null;return{family:"bitcoin",name:"Bitcoin Mainnet",address:n.bitcoin,status:S.ok||$?.ok||b?.ok?"ok":"unavailable",native:S.ok?{status:"ok",symbol:"BTC",amountRaw:S.data.balanceSats,decimals:8,amount:pe(S.data.balanceSats,8)}:{status:"unavailable",symbol:"BTC",error:S.error},fungibleTokens:{status:s?$?.ok?"ok":"unavailable":"not-requested",assets:$?.balances||[],error:$?.ok?null:$?.error||E.error,verification:"indexer-reported"},collectibles:{status:a?b?.ok?"ok":"unavailable":"not-requested",assets:b?.inscriptions||[],error:b?.ok?null:b?.error||U.error,unknownNotEmpty:!!b?.unknownNotEmpty,verification:"indexer-reported"},source:"bitcoin-esplora+bitcoin-meta"}})(),w=(async()=>{if(!n.hyperliquid)return{family:"hyperliquid",name:"Hyperliquid HyperCore",address:null,status:"not-configured",error:"set ORACLE_HYPERLIQUID_ADDRESS or pass addresses.hyperliquid"};let f=J(t,"hyperliquid"),[g,S,E]=await Promise.all([I(()=>Gt(n.hyperliquid,f)),I(()=>Wt(n.hyperliquid,f)),I(()=>Kt(f))]),U=(g.ok&&Array.isArray(g.data?.balances)?g.data.balances:[]).filter(b=>X(b.total)||X(b.hold)).map(b=>({coin:b.coin||null,total:String(b.total??"0"),hold:String(b.hold??"0"),priceUsd:null,usdValue:null})),$=(S.ok&&Array.isArray(S.data?.assetPositions)?S.data.assetPositions:[]).map(b=>b.position||b).filter(b=>X(b.szi)).map(b=>({coin:b.coin||null,size:String(b.szi??"0"),entryPrice:b.entryPx??null,positionValueUsd:b.positionValue??null,unrealizedPnlUsd:b.unrealizedPnl??null,liquidationPrice:b.liquidationPx??null}));return{family:"hyperliquid",name:"Hyperliquid HyperCore",address:n.hyperliquid,status:g.ok||S.ok?"ok":"unavailable",spot:{status:g.ok?"ok":"unavailable",balances:U,error:g.ok?null:g.error},perps:{status:S.ok?"ok":"unavailable",accountValueUsd:S.data?.marginSummary?.accountValue??null,withdrawableUsd:S.data?.withdrawable??null,positions:$,error:S.ok?null:S.error},mids:E.ok?E.data:{},source:"hyperliquid-info"}})(),[A,v,_,k,q]=await Promise.all([u,m,l,w,h]),p=q.ok?q.data:null,y=A.map(f=>f.native?{...f,native:qe(f.native,p)}:f);v.native&&(v.native=qe(v.native,p)),_.native&&(_.native=qe(_.native,p));let x=0,L=0,Z=0;for(let f of[...y,v,_])f.native?.status!=="ok"||!X(f.native.amount)||(f.native.usdValue!=null?(x+=f.native.usdValue,L+=1):Z+=1);let vn=Qt(p,"HYPE");for(let f of k.spot?.balances||[]){let g=String(f.coin||"").toUpperCase(),S=g==="USDC"||g==="USDT"||g==="USDT0"?1:g==="HYPE"?vn.priceUsd||re(k.mids?.HYPE):re(k.mids?.[f.coin]),E=re(f.total);f.priceUsd=S,f.usdValue=E!=null&&S!=null?De(E*S):null,X(f.total)&&(f.usdValue!=null?(x+=f.usdValue,L+=1):Z+=1)}let ye=re(k.perps?.accountValueUsd);ye!=null&&ye!==0&&(x+=ye,L+=1);let An=[...v.fungibleTokens?.assets||[],...v.collectibles?.assets||[]].filter(f=>X(f.amount)).length,xn=(_.fungibleTokens?.assets||[]).length+(_.collectibles?.assets||[]).length;Z+=An+xn;let ge=[...y,v,_,k],K=f=>ge.filter(g=>g.status===f).length,ee=[];y.some(f=>f.fungibleTokens?.status==="unavailable")&&ee.push("EVM token and NFT discovery is unavailable without a configured address indexer; native balances are still live."),(v.fungibleTokens?.assets?.length||v.collectibles?.assets?.length)&&ee.push("Solana token accounts are unverified and may include spam; collectible candidates are not confirmed NFTs."),_.collectibles?.unknownNotEmpty&&ee.push("Bitcoin inscription holdings are unknown, not zero, because no address indexer is configured."),q.ok||ee.push(`Price provider unavailable: ${q.error}`);let we=[Be("cosmos","requires a chain-specific bech32 address and LCD/RPC adapter"),Be("sui","Sui balance adapter is not installed"),Be("aptos","Aptos balance adapter is not installed")],En=ge.some(f=>["unavailable","partial","not-configured"].includes(f.fungibleTokens?.status)||["unavailable","partial","not-configured"].includes(f.collectibles?.status));return{provider:"portfolio",operation:"balances",readOnly:!0,queriedAt:r,addresses:n,coverage:{requestedSurfaces:ge.length,ok:K("ok"),unavailable:K("unavailable"),notConfigured:K("not-configured"),unsupported:K("unsupported")+we.length,evmChainsRequested:c.length,evmChainsOk:y.filter(f=>f.status==="ok").length},valuation:{knownUsd:De(x),label:"known priced value, not a complete portfolio total",pricedItems:L,unpricedNonzeroItems:Z,complete:Z===0&&!En&&K("unavailable")===0&&K("not-configured")===0&&we.length===0,priceSource:o?"DefiLlama":null,priceStatus:q.ok?"ok":"unavailable",priceQueriedAt:r},chains:[...y,v,_,k],unsupportedFamilies:we,warnings:ee}}import{readFileSync as to,existsSync as no}from"node:fs";import{getAddress as ro}from"ethers";var Sa=300*1e3,va=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();var oo="https://api.opensea.io/api/v2",so=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"]),ao=new Set(so),io=new Set(["solana","flow"]);function co(){let e=process.env.OPENSEA_ENV_FILE||`${process.env.HOME||""}/.config/locals-only/opensea.env`;if(!no(e))return"";try{for(let t of to(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 He(e={}){return e.apiKey||process.env.OPENSEA_API_KEY||process.env.OPEN_SEA_API_KEY||co()}function nn(e={}){return Y({provider:"opensea",defaultUrl:oo,hosts:["api.opensea.io","testnets-api.opensea.io"],url:e.baseUrl||process.env.OPENSEA_API_URL})}function rn(e={}){return nn(e).baseUrl}function on(e={}){return j({accept:"application/json"},{"x-api-key":He(e)},nn(e).trusted)}function lo(e){let t=String(e||"ethereum").trim().toLowerCase();if(!ao.has(t))throw new Error(`opensea: unsupported account chain ${t}`);return t}function en(e,t="address"){try{return ro(String(e||"").trim().toLowerCase())}catch{throw new Error(`opensea: invalid ${t}`)}}function sn(e,t=null){let r=String(e||"").trim();if(!r)throw new Error("opensea: account address required");if(t&&!io.has(t)||!t&&/^0x[0-9a-fA-F]{40}$/.test(r))return en(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 uo(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,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||e.is_nsfw===!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"}}}async function Ve(e={},t={}){if(!He(t))throw new Error("OPENSEA_API_KEY required");let r=lo(e.chain),n=sn(e.address||e.owner,r),o=Math.min(Math.max(Number(e.pageSize??e.limit??200)||200,1),200),s=Math.min(Math.max(Number(e.maxPages??5)||5,1),25),a=[],i=e.next?String(e.next):null,c=0;do{let d=new URL(`${rn(t)}/chain/${encodeURIComponent(r)}/account/${encodeURIComponent(n)}/nfts`);d.searchParams.set("limit",String(o)),e.collection&&d.searchParams.set("collection",String(e.collection)),i&&d.searchParams.set("next",i);let h=await N(d.toString(),{headers:on(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});for(let u of Array.isArray(h?.nfts)?h.nfts:[])a.push(uo(u,r,n));i=h?.next?String(h.next):null,c+=1}while(i&&c<s);return{provider:"opensea-nft",source:"opensea-account-inventory",chain:r,owner:n,count:a.length,pages:c,complete:!i,next:i,nfts:a,exec:!1,readOnly:!0}}async function an(e={},t={}){if(!He(t))throw new Error("OPENSEA_API_KEY required");let r=sn(e.address||e.owner),n=await N(`${rn(t)}/account/${encodeURIComponent(r)}/pnl`,{headers:on(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}}var fo="https://api.satflow.com/v1";function cn(e={}){return Y({provider:"satflow",defaultUrl:fo,hosts:["api.satflow.com"],url:e.baseUrl||process.env.SATFLOW_API_URL})}function mo(e={}){return cn(e).baseUrl}function ln(e={}){return String(e.apiKey||process.env.SATFLOW_API_KEY||process.env.BTC_SATFLOW_API_KEY||"").trim()}function ho(e={}){return j({accept:"application/json","content-type":"application/json","user-agent":"oracle-btc-satflow/0.1"},{"x-api-key":ln(e)},cn(e).trusted)}async function bo(e,{method:t="GET",body:r,opts:n={}}={}){if(!ln(n))throw new Error("satflow: SATFLOW_API_KEY not set (request key via Satflow docs form)");let s=`${mo(n)}${e.startsWith("/")?e:`/${e}`}`,i=await(n.fetchImpl||fetch)(s,{method:t,headers:ho(n),body:r!=null?JSON.stringify(r):void 0,signal:AbortSignal.timeout(n.timeoutMs??2e4)}),c=await i.text(),d;try{d=JSON.parse(c)}catch{d=c}if(!i.ok)throw new Error(`satflow ${t} ${e}: HTTP ${i.status} ${String(c).slice(0,200)}`);return d}async function un(e={},t={}){let r=V(e.address||e.addr,"address"),n=new URLSearchParams({address:r});e.type&&n.set("type",e.type),e.limit!=null&&n.set("limit",String(e.limit)),e.offset!=null&&n.set("offset",String(e.offset));let o=await bo(`/address/wallet-contents?${n}`,{opts:t});return{provider:"satflow",address:r,contents:o}}var Ha=Object.freeze(["i.seadn.io","openseauserdata.com","arweave.net","ipfs.io","nftstorage.link","dweb.link","cloudflare-ipfs.com","ordinals.com","ordinals.g.com","cdn.helius-rpc.com","shdw-drive.genesysgo.net"]);var yo=Object.freeze([{chain:"ethereum",chainId:1,family:"evm"},{chain:"optimism",chainId:10,family:"evm"},{chain:"polygon",chainId:137,family:"evm"},{chain:"stablechain",chainId:988,family:"evm"},{chain:"hyperevm",chainId:999,family:"evm"},{chain:"abstract",chainId:2741,family:"evm"},{chain:"robinhood",chainId:4663,family:"evm"},{chain:"base",chainId:8453,family:"evm"},{chain:"arbitrum",chainId:42161,family:"evm"},{chain:"avalanche",chainId:43114,family:"evm"},{chain:"hyperliquid",chainId:null,family:"hyperliquid"}]),go=Object.freeze([{family:"evm",chain:"bsc",chainId:56,reason:"OpenSea account inventory does not support BSC"},{family:"cosmos",reason:"requires a chain-specific bech32 address and NFT indexer"},{family:"sui",reason:"owner inventory adapter not installed"},{family:"aptos",reason:"owner inventory adapter not installed"}]);function ze(e={},t){return{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,...e[t]||{}}}async function oe(e,t){let r=await I(t);return r.ok?{ok:!0,data:r.data}:{ok:!1,error:`${e}: ${r.error}`.slice(0,300)}}function wo(e){if(Array.isArray(e))return e;for(let t of["items","results","ordinals","inscriptions","data"])if(Array.isArray(e?.[t]))return e[t];return[]}function So(e={},t){let r=e.inscription_id||e.inscriptionId||e.id||e.inscription||null;return{chain:"bitcoin",family:"bitcoin",owner:t,contract:null,tokenId:r==null?null:String(r),tokenStandard:"ordinal",collection:e.collection_slug||e.collectionSlug||e.collection?.slug||e.collection||null,name:e.name||e.meta?.name||(r?`Inscription ${r}`:"Bitcoin inscription"),description:e.description||e.meta?.description||null,imageUrl:e.image_url||e.imageUrl||e.content_url||e.contentUrl||e.thumbnail||null,originalImageUrl:e.content_url||e.contentUrl||e.image_url||e.imageUrl||null,animationUrl:null,metadataUrl:e.metadata_url||e.metadataUrl||null,marketplaceUrl:e.marketplace_url||e.marketplaceUrl||null,estimatedValueUsd:e.estimated_value_usd!=null&&Number.isFinite(Number(e.estimated_value_usd))?Number(e.estimated_value_usd):null,estimatedValueSats:(e.floor_price_sats??e.price_sats)!=null&&Number.isFinite(Number(e.floor_price_sats??e.price_sats))?Number(e.floor_price_sats??e.price_sats):null,spam:!1,disabled:!1,nsfw:!1,listed:e.listed===!0||e.is_listed===!0,listingId:e.listing_id||e.listingId||null,traits:Array.isArray(e.traits)?e.traits:[],updatedAt:e.updated_at||e.updatedAt||null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"Satflow wallet inventory does not expose trustworthy acquisition cost"},listingAdapter:"satflow",source:"satflow-wallet-contents"}}function vo(e,t){return{chain:"bitcoin",family:"bitcoin",owner:t,contract:null,tokenId:String(e),tokenStandard:"ordinal",collection:null,name:`Inscription ${e}`,description:null,imageUrl:null,originalImageUrl:null,animationUrl:null,metadataUrl:null,marketplaceUrl:null,estimatedValueUsd:null,spam:!1,disabled:!1,nsfw:!1,traits:[],updatedAt:null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"address indexer returned no acquisition or valuation data"},listingAdapter:"satflow",source:"bitcoin-meta-address-indexer"}}function dn(e={}){return[e.chain||"unknown",e.contract||"native",e.tokenId||"unknown"].join(":").toLowerCase()}function Ao(e){let t=new Map;if(Array.isArray(e)){for(let r of e)r?.assetKey&&t.set(String(r.assetKey).toLowerCase(),r);return t}if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))t.set(r.toLowerCase(),n);return t}function xo(e,t){let r=dn(e),n=t.get(r),o=e.estimatedValueUsd==null?null:Number(e.estimatedValueUsd);if(!n)return{...e,assetKey:r};let s=Number(n.costUsd),a=Number(n.feesUsd??0);if(!Number.isFinite(s)||s<0||!Number.isFinite(a)||a<0)return{...e,assetKey:r,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"invalid user-supplied cost basis"}};let i=Math.round((s+a)*100)/100;return Number.isFinite(o)?{...e,assetKey:r,acquisitionCost:{costUsd:s,feesUsd:a,totalCostUsd:i,acquiredAt:n.acquiredAt||null,source:n.source||"user-supplied"},itemPnl:{status:"estimated",methodology:"provider estimated current value minus supplied USD acquisition cost and fees",unrealizedUsd:Math.round((o-i)*100)/100,currentValueUsd:o,totalCostUsd:i,realizedUsd:null}}:{...e,assetKey:r,acquisitionCost:{costUsd:s,feesUsd:a,totalCostUsd:i,acquiredAt:n.acquiredAt||null,source:n.source||"user-supplied"},itemPnl:{status:"unavailable",reason:"current NFT valuation is unavailable"}}}function Eo(e){let t=new Map;for(let r of e){let n=dn(r);t.has(n)||t.set(n,r)}return[...t.values()]}function _o(e,t){let r=e.filter(s=>s.itemPnl?.status==="estimated"),n=e.length-r.length,o=Math.round(r.reduce((s,a)=>s+Number(a.itemPnl.unrealizedUsd||0),0)*100)/100;return{nftItemPnl:{status:n===0&&e.length?"estimated-complete-for-held-items":r.length?"partial":"unavailable",methodology:"Only items with explicit acquisition cost and provider estimated current value are included",knownUnrealizedUsd:o,knownItems:r.length,unknownItems:n,realizedUsd:null,warning:"Transfers, gifts, airdrops, mints, bridges, gas, royalties, and off-market sales can make cost basis unavailable or incomplete."},providerAccountPnl:t}}async function pn(e={},t={}){let r=new Date().toISOString(),n=Fe(e,t.env||process.env),o=Array.isArray(e.chains)&&e.chains.length?new Set(e.chains.map(p=>String(p).toLowerCase())):null,s=yo.filter(p=>!o||o.has(p.chain)),a=[],i=[],c=ze(t,"opensea"),d=n.evm?s.filter(p=>p.family!=="solana"):[],h=await H(d,4,async p=>({row:p,result:await oe(`opensea-${p.chain}`,()=>Ve({chain:p.chain,address:n.evm,pageSize:e.pageSize,maxPages:e.maxPages},c),t.timeoutMs??35e3)}));for(let{row:p,result:y}of h)if(y.ok){let x=y.data.nfts.map(L=>({...L,family:p.family,chainId:p.chainId,listingAdapter:"opensea",source:"opensea-account-inventory"}));i.push(...x),a.push({family:p.family,chain:p.chain,chainId:p.chainId,status:y.data.complete?"ok":"partial",count:x.length,complete:y.data.complete,next:y.data.next,source:"opensea"})}else a.push({family:p.family,chain:p.chain,chainId:p.chainId,status:"unavailable",error:y.error,source:"opensea"});if(!n.evm)for(let p of s.filter(y=>y.family!=="solana"))a.push({family:p.family,chain:p.chain,chainId:p.chainId,status:"not-configured",reason:"EVM address missing"});if(n.solana&&(!o||o.has("solana"))){let p=await oe("opensea-solana",()=>Ve({chain:"solana",address:n.solana,pageSize:e.pageSize,maxPages:e.maxPages},c),t.timeoutMs??35e3);if(p.ok){let y=p.data.nfts.map(x=>({...x,family:"solana",chainId:null,listingAdapter:null,source:"opensea-account-inventory"}));i.push(...y),a.push({family:"solana",chain:"solana",status:p.data.complete?"ok":"partial",count:y.length,complete:p.data.complete,next:p.data.next,source:"opensea"})}else a.push({family:"solana",chain:"solana",status:"unavailable",error:p.error,source:"opensea"})}else(!o||o.has("solana"))&&a.push({family:"solana",chain:"solana",status:"not-configured",reason:"Solana address missing"});if(n.bitcoin&&(!o||o.has("bitcoin"))){let p=await oe("satflow-wallet-contents",()=>un({address:n.bitcoin,type:"ordinals",limit:e.bitcoinLimit??100,offset:0},ze(t,"satflow")),t.timeoutMs??35e3);if(p.ok){let y=wo(p.data.contents).map(L=>So(L,n.bitcoin));i.push(...y);let x=y.length<Number(e.bitcoinLimit??100);a.push({family:"bitcoin",chain:"bitcoin",status:x?"ok":"partial",count:y.length,complete:x,source:"satflow"})}else{let y=await oe("bitcoin-meta-inscriptions",()=>ue({address:n.bitcoin},ze(t,"bitcoinMeta")),t.timeoutMs??35e3),x=y.ok&&y.data?.ok&&Array.isArray(y.data.inscriptions)?y.data.inscriptions:[];i.push(...x.map(L=>vo(L,n.bitcoin))),a.push({family:"bitcoin",chain:"bitcoin",status:x.length?"partial":"unavailable",count:x.length,complete:!1,source:x.length?"bitcoin-meta":"satflow",error:x.length?"Satflow unavailable; fallback has IDs only":p.error})}}else(!o||o.has("bitcoin"))&&a.push({family:"bitcoin",chain:"bitcoin",status:"not-configured",reason:"Bitcoin address missing"});let u=[];if(e.includePnl!==!1)for(let p of[...new Set([n.evm,n.solana].filter(Boolean))]){let y=await oe(`opensea-pnl-${p}`,()=>an({address:p},c),t.timeoutMs??35e3);u.push(y.ok?{status:"ok",...y.data}:{status:"unavailable",address:p,source:"opensea-indexed-account-pnl",error:y.error})}let m=Ao(e.costBasis),l=Eo(i).map(p=>xo(p,m)),w=l.filter(p=>!p.spam),A=l.filter(p=>p.spam),v=w.filter(p=>p.estimatedValueUsd!=null&&Number.isFinite(Number(p.estimatedValueUsd))),_=Math.round(v.reduce((p,y)=>p+Number(y.estimatedValueUsd),0)*100)/100,k=w.length-v.length,q=a.filter(p=>p.status!=="ok"||p.complete===!1);return{provider:"nft-portfolio",operation:"inventory",readOnly:!0,generatedAt:r,addresses:n,coverage:a,unsupported:go,inventory:{count:l.length,visibleCount:w.length,flaggedCount:A.length,items:l,visibleItems:w,flaggedItems:A},valuation:{estimatedCurrentValueUsd:_,valuedItems:v.length,unvaluedItems:k,complete:k===0&&q.length===0,methodology:"Sum of provider estimated_value_usd for non-flagged items. It is not an executable bid."},pnl:_o(w,u),listingCoverage:{opensea:"EVM listing actions available with OPENSEA_API_KEY, explicit price/currency/expiry, and user confirmation",satflow:"Bitcoin unsigned listing PSBT available with SATFLOW_API_KEY, explicit price/expiry, and user confirmation",solana:"Magic Eden unsigned list transaction available with MAGICEDEN_API_KEY, explicit SOL price/expiry, and user confirmation",unsupported:"Sui, Aptos, Cosmos, BSC, and unknown marketplaces fail closed"},metadataSafety:{imagesAreUntrusted:!0,animationAndHtmlNotRendered:!0,galleryRasterOnly:!0,missingImagesUsePlaceholders:!0}}}import{homedir as fn}from"node:os";import{join as mn}from"node:path";var oi=mn(fn(),".config","oracle"),si=mn(fn(),".config","mad-desk");function je(e,t,r=""){let n=process.env[e];if(n!=null&&String(n).trim()!=="")return n;let o=t?process.env[t]:void 0;return o!=null&&String(o).trim()!==""?o:r}var Ro=JSON.parse(gn(new URL("../../package.json",import.meta.url),"utf8")),Q="public",$o="127.0.0.1",Oo=8799,me=Ro.version,Lo=new Set(["127.0.0.1","localhost","::1"]),Uo=Ge(No(To(import.meta.url)),"../.."),Ke=Ge(Uo,"public","oracle-console"),hn=Object.freeze({"/":{file:"index.html",type:"text/html; charset=utf-8"},"/index.html":{file:"index.html",type:"text/html; charset=utf-8"},"/app.js":{file:"app.js",type:"application/javascript; charset=utf-8"},"/styles.css":{file:"styles.css",type:"text/css; charset=utf-8"},"/oracle-console":{file:"index.html",type:"text/html; charset=utf-8"},"/oracle-console/":{file:"index.html",type:"text/html; charset=utf-8"},"/oracle-console/index.html":{file:"index.html",type:"text/html; charset=utf-8"},"/oracle-console/app.js":{file:"app.js",type:"application/javascript; charset=utf-8"},"/oracle-console/styles.css":{file:"styles.css",type:"text/css; charset=utf-8"}}),Mo=1e6,P=class extends Error{constructor(t,r,n){super(n||r),this.status=t,this.code=r}};function D(e,t,r){let n=t,o;try{R(r),o=dt(r)}catch{n=500,o=JSON.stringify({error:"secret-leak-blocked"})}e.writeHead(n,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","x-oracle-plane":Q,"x-oracle-unsigned":"true"}),e.end(o)}function Bo(e){return new Promise((t,r)=>{let n=[],o=0;e.on("data",s=>{if(o+=s.length,o>Mo){r(new P(413,"payload-too-large","request body too large")),e.destroy();return}n.push(s)}),e.on("end",()=>{let s=Buffer.concat(n).toString("utf8").trim();if(s==="")return t({});try{t(JSON.parse(s))}catch{r(new P(400,"invalid-json","request body must be valid JSON"))}}),e.on("error",()=>r(new P(400,"bad-request","request stream error")))})}function C(e,t){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new P(400,t,`${t} must be a JSON object`);return e}function qo(e){return String(e||"").trim().toLowerCase().replace(/^\[|\]$/g,"")}function Do(e){let t=qo(e);if(!Lo.has(t))throw new TypeError(`oracle-public only binds loopback hosts; got ${String(e)}`);return t==="::1"?"::1":String(e).trim()}function Fo(){return{status:200,body:{ok:!0,plane:Q,version:me}}}function he(e){return{...e,allowWildcardActions:!1,now:Math.floor(Date.now()/1e3)}}function Ho(e){let t=C(e,"body"),r=t.input!==void 0?C(t.input,"input"):t,n=he(C(t.opts,"opts")),o=r===t?(({opts:s,...a})=>a)(t):r;return{status:200,body:mt(o,n)}}function Vo(e){let t=C(e,"body"),r=t.request!==void 0?C(t.request,"request"):t.input!==void 0?C(t.input,"input"):t,n=he(C(t.opts,"opts")),o=r===t?(({opts:s,...a})=>a)(t):r;return{status:200,body:ht(o,n)}}function zo(e){let t=C(e,"body"),r=he(C(t.opts,"opts")),n=gt(t.store??[],r);return{status:200,body:{ok:!0,count:n.length,grants:n}}}function jo(e){let t=C(e,"body"),r=he(C(t.opts,"opts")),n=wt(t.store??[],t.id,r);return n==null?{status:404,body:{error:"grant-not-found"}}:{status:200,body:n}}function Ko(){let e=(process.env.ORACLE_PRIVY_APP_ID||process.env.PRIVY_APP_ID||"").trim(),t=e.length>0,r=!0,n=[];return t&&n.push("privy"),r&&n.push("injected"),{status:200,body:{ok:!0,plane:Q,version:me,custody:{selfCustodial:!0,signer:"user-wallet",privyEnabled:t,injectedEnabled:r,modes:n},privy:{appId:e||null}}}}var fe=12;async function Go(e){let t=C(e,"body"),r=typeof t.owner=="string"?t.owner:null;if(!r)throw new P(400,"owner-required","owner must be an EVM address");let n=Array.isArray(t.chainIds)?t.chainIds.map(Number).filter(Number.isFinite):void 0;if(n&&n.length>fe)throw new P(400,"too-many-chains",`at most ${fe} chainIds per request`);let s=await Ut({owner:r,chainIds:n},{});return{status:200,body:{ok:!0,owner:s.owner,scannedRange:s.scannedRange,approvals:s.approvals,scans:s.scans,warnings:s.warnings}}}function wn(e){if(typeof e=="string")return e.trim()===""?null:e;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e.evm;if(typeof t=="string"&&t.trim()!=="")return t}return null}async function Wo(e){let t=C(e,"body"),r=wn(t.owner);if(!r)throw new P(400,"owner-required","owner must be an EVM address");let n=Array.isArray(t.chainIds)?t.chainIds.map(Number).filter(Number.isFinite):void 0;if(n&&n.length>fe)throw new P(400,"too-many-chains",`at most ${fe} chainIds per request`);let o=await Zt({addresses:{evm:r},evmChainIds:n,includePrices:!0,includeTokens:!0,includeCollectibles:!1},{env:{}}),s=[],a=[];for(let i of o.chains||[]){if(i.family!=="evm")continue;a.push({chainId:i.chainId,name:i.name,status:i.status,error:i.error??null,tokenDiscovery:i.fungibleTokens?.status??"unavailable",tokenDiscoveryReason:i.fungibleTokens?.reason??null});let c=i.native;i.status!=="ok"||!c||c.status!=="ok"||!c.amountRaw||c.amountRaw==="0"||c.amountRaw==="0x0"||s.push({chainId:i.chainId,chain:i.name,symbol:c.symbol,decimals:c.decimals,amount:String(c.amountRaw),amountRaw:String(c.amountRaw),amountFormatted:c.amount,kind:"native"})}return{status:200,body:{ok:!0,owner:o.addresses?.evm??r,queriedAt:o.queriedAt,portfolio:{rows:s,chains:a,coverage:o.coverage,complete:!1,incompleteReason:"EVM JSON-RPC returns native balances only; token enumeration requires an address indexer"},warnings:o.warnings}}}async function Yo(e){let t=C(e,"body"),r=wn(t.owner);if(!r)throw new P(400,"owner-required","owner must be an EVM address");let n=await pn({addresses:{evm:r}},{env:{}});return{status:200,body:{ok:!0,owner:r,queriedAt:n.queriedAt??new Date().toISOString(),nfts:{items:Array.isArray(n.items)?n.items:[],chains:n.chains??[],coverage:{operational:n.ok!==!1,complete:n.complete===!0,hasGaps:n.complete!==!0}},warnings:n.warnings}}}var Jo=6e4,Xo=120,Qo=10,bn=Object.freeze(new Set(["/public/approvals","/public/portfolio","/public/nfts"])),Zo=4096,se=new Map;function es(e){if(process.env.ORACLE_TRUST_PROXY==="1"){let t=e.headers["x-forwarded-for"];if(typeof t=="string"&&t.length>0){let r=t.split(",")[0].trim();if(r)return r.slice(0,64)}}return e.socket?.remoteAddress||"unknown"}function ts(e,t){let r=bn.has(t)?Qo:Xo,n=Date.now(),o=`${es(e)}:${bn.has(t)?"amp":"std"}`,s=se.get(o);if(!s||n>=s.resetAt){for(se.set(o,{count:1,resetAt:n+Jo});se.size>Zo;){let a=se.keys().next();if(a.done)break;se.delete(a.value)}return{allowed:!0,limit:r,remaining:r-1,retryAfterSec:0}}return s.count+=1,s.count>r?{allowed:!1,limit:r,remaining:0,retryAfterSec:Math.max(1,Math.ceil((s.resetAt-n)/1e3))}:{allowed:!0,limit:r,remaining:r-s.count,retryAfterSec:0}}var yn=Object.freeze({"GET /public/health":Fo,"GET /public/config":Ko,"POST /public/connect/request":Ho,"POST /public/connect/assemble":Vo,"POST /public/grants/active":zo,"POST /public/grants/get":jo,"POST /public/approvals":Go,"POST /public/portfolio":Wo,"POST /public/nfts":Yo});function We(e={}){return{"cache-control":"no-store","x-oracle-plane":Q,"x-oracle-unsigned":"true",...e}}function ns(e,t,r,n){e.writeHead(t,We({"content-type":r})),e.end(n)}function rs(e,t,r){if(e.method!=="GET"&&e.method!=="HEAD")return!1;let n=r===""?"/":r,o=hn[n]||hn[n.replace(/\/+$/,"")||"/"];if(!o)return!1;let s=Co(Ge(Ke,o.file));if(!s.startsWith(Ke+Po)&&s!==Ke)return D(t,404,{error:"not-found",message:"unknown static path"}),!0;if(!ko(s))return D(t,404,{error:"not-found",message:`missing static file ${o.file}`}),!0;let a=gn(s);return e.method==="HEAD"?(t.writeHead(200,We({"content-type":o.type,"content-length":String(a.length)})),t.end(),!0):(ns(t,200,o.type,a),!0)}async function os(e,t){let n=new URL(e.url,"http://localhost").pathname||"/";n.length>1&&n.endsWith("/")&&n!=="/oracle-console/"&&(n=n.replace(/\/+$/,"")),n===""&&(n="/");let o=n.replace(/\/+$/,"")||"/",s=`${e.method} ${o}`,a=yn[s];try{if(!a){if(rs(e,t,n))return;throw Object.keys(yn).some(u=>u.endsWith(` ${o}`))?new P(405,"method-not-allowed",`unsupported method for ${o}`):new P(404,"not-found",`unknown route ${o}`)}let i=ts(e,o);if(!i.allowed){t.writeHead(429,We({"content-type":"application/json","retry-after":String(i.retryAfterSec),"x-ratelimit-limit":String(i.limit),"x-ratelimit-remaining":"0"})),t.end(JSON.stringify({error:"rate-limited",message:`too many requests for ${o}; retry in ${i.retryAfterSec}s`}));return}let c=e.method==="GET"||e.method==="HEAD"?void 0:await Bo(e),d=await a(c);D(t,d.status,d.body)}catch(i){if(i instanceof O){D(t,500,{error:"secret-leak-blocked"});return}if(i instanceof M){D(t,400,{error:"invalid-grant",errors:i.errors.map(c=>({field:c.field,message:c.message}))});return}if(i instanceof P){D(t,i.status,{error:i.code,message:i.message});return}if(i instanceof TypeError){D(t,400,{error:"bad-request",message:i.message});return}D(t,500,{error:"internal-error"})}}function ss(){return Io((e,t)=>{os(e,t).catch(()=>{try{D(t,500,{error:"internal-error"})}catch{}})})}function Ye({host:e,port:t}={}){let r=Do(e??je("ORACLE_PUBLIC_HOST","MAD_PUBLIC_HOST",$o)),n=t??je("ORACLE_PUBLIC_PORT","MAD_PUBLIC_PORT",String(Oo)),o=Number(n);if(!Number.isInteger(o)||o<0||o>65535)throw new TypeError(`invalid public port: ${String(n)}`);return{host:r,port:o}}function Sn(e={}){let{host:t,port:r}=Ye(e),n=ss();return n.listen(r,t),n}var Je=Ye(),be=Sn(Je);be.on("listening",()=>{let e=be.address(),t=typeof e=="object"&&e?e.address:Je.host,r=typeof e=="object"&&e?e.port:Je.port;console.log(`oracle-public-server listening on http://${t}:${r} (plane=${Q}, version=${me}, unsigned-only)`)});be.on("error",e=>{console.error(`oracle-public-server failed to bind: ${e.code||e.message}`),process.exit(1)});for(let e of["SIGINT","SIGTERM"])process.on(e,()=>{be.close(()=>process.exit(0)),setTimeout(()=>process.exit(0),1e3).unref()});
2
+ import{createServer as No}from"node:http";import{readFileSync as wn,existsSync as Co}from"node:fs";import{dirname as To,join as Ye,normalize as Po,sep as Ro}from"node:path";import{fileURLToPath as Oo}from"node:url";import{createHash as In}from"node:crypto";var te=1,Ze=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),kn=Object.freeze(["read","simulate"]),et=1e4,tt=1440*60,nt=128,rt=256,ot=64,st=256,at=/^0x[0-9a-fA-F]{40}$/,Nn=/^[a-z][a-z0-9_-]*:[a-z0-9._-]+$/,Cn=/^[a-z][a-z0-9_-]*:\*$/,Tn=/^[A-Za-z0-9._:-]+$/,Pn=/^[A-Za-z0-9._:-]+$/,it=/^(0|[1-9][0-9]*)$/,B=class extends Error{constructor(t){let r=t.map(n=>`${n.field}: ${n.message}`);super(`invalid grant (${t.length} error${t.length===1?"":"s"}): ${r.join("; ")}`),this.name="GrantValidationError",this.errors=t}};function ct(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Rn(e){if(typeof e=="bigint")return e>=0n?e.toString(10):null;if(typeof e=="number")return!Number.isSafeInteger(e)||e<0?null:String(e);if(typeof e=="string"){let t=e.trim();return it.test(t)?t:null}return null}function F(e){if(typeof e=="bigint")return e<0n||e>BigInt(Number.MAX_SAFE_INTEGER)?null:Number(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0?null:e;if(typeof e=="string"){let t=e.trim();if(!it.test(t))return null;let r=Number(t);return Number.isSafeInteger(r)?r:null}return null}function Se(e){let t=String(e).split(":")[0];return kn.includes(t)}function ve(e,t={}){let r=[],n=(d,h)=>r.push({field:d,message:h});if(!ct(e))return n("grant","grant must be a plain object"),{ok:!1,errors:r,grant:null};for(let d of Object.keys(e))Ze.includes(d)||n(d,"unknown field is not allowed");for(let d of Ze)(!(d in e)||e[d]==null)&&n(d,"required field is missing");if(r.length)return{ok:!1,errors:r,grant:null};let o={},s=F(e.chainId);s==null||s<=0?n("chainId","must be a positive integer chain id"):o.chainId=s;for(let d of["agentAddress","accountAddress"]){let h=e[d];typeof h!="string"||!at.test(h.trim())?n(d,"must be a 0x-prefixed 20-byte hex address"):o[d]=h.trim().toLowerCase()}if(!Array.isArray(e.actions)||e.actions.length===0)n("actions","must be a non-empty array of action scopes");else if(e.actions.length>ot)n("actions",`too many actions (max ${ot})`);else{let d=[];for(let h of e.actions){let u=typeof h=="string"?h.trim():null;if(!u){n("actions","action entries must be non-empty strings");continue}if(u.includes("*")){t.allowWildcardActions===!0&&Cn.test(u)?d.push(u):n("actions",`broad wildcard action "${u}" is rejected (fail closed)`);continue}if(!Nn.test(u)){n("actions",`malformed action "${u}" (expected verb:resource)`);continue}d.push(u)}o.actions=[...new Set(d)].sort()}if(!Array.isArray(e.targets))n("targets","must be an array of contract addresses");else if(e.targets.length>st)n("targets",`too many targets (max ${st})`);else{let d=[];for(let h of e.targets){let u=typeof h=="string"?h.trim():null;if(!u||!at.test(u)){n("targets",`target "${h}" must be a 0x-prefixed 20-byte hex address (wildcards not allowed)`);continue}d.push(u.toLowerCase())}if(o.targets=[...new Set(d)].sort(),o.targets.length===0&&Array.isArray(o.actions)){let h=o.actions.filter(u=>!Se(u));(h.length>0||o.actions.length===0)&&n("targets",`empty targets are only allowed for read/simulate scopes (blocked by: ${h.join(", ")||"no valid actions"})`)}}for(let d of["maxValueWei","maxGasWei"]){let h=Rn(e[d]);h==null?n(d,"must be a non-negative integer wei amount"):o[d]=h}let a=F(e.maxSlippageBps);a==null||a>et?n("maxSlippageBps",`must be an integer between 0 and ${et}`):o.maxSlippageBps=a;let i=864e10,c=F(e.expiresAt);if(c==null||c<=0)n("expiresAt","must be a positive unix-seconds timestamp");else if(c>i)n("expiresAt","exceeds the max unix-seconds timestamp (pass seconds, not milliseconds)");else if(o.expiresAt=c,t.now!=null){let d=F(t.now);d==null?n("expiresAt","opts.now must be a unix-seconds integer"):c<=d?n("expiresAt",`grant is expired (expiresAt ${c} <= now ${d})`):c-d>tt&&n("expiresAt",`grant exceeds the hard 24-hour TTL (${tt} seconds)`)}let l=typeof e.nonce=="string"?e.nonce.trim():F(e.nonce)!=null?String(F(e.nonce)):null;!l||l.length>nt||!Tn.test(l)?n("nonce",`must be a non-empty string (max ${nt} chars, [A-Za-z0-9._:-])`):o.nonce=l;let f=typeof e.revocationKey=="string"?e.revocationKey.trim():null;return!f||f.length>rt||!Pn.test(f)?n("revocationKey",`must be a non-empty public identifier (max ${rt} chars, [A-Za-z0-9._:-])`):o.revocationKey=f,r.length?{ok:!1,errors:r,grant:null}:{ok:!0,errors:[],grant:o}}function ae(e,t={}){let{ok:r,errors:n,grant:o}=ve(e,t);if(!r)throw new B(n);return o}function Ae(e,t={}){let r=ae(e,t),o=Object.keys(r).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(r[s])}`);return`{"version":${te},${o.join(",")}}`}function ie(e,t={}){return In("sha256").update(Ae(e,t),"utf8").digest("hex")}function lt(e,t){let r=F(t),n=F(ct(e)?e.expiresAt:null);return r==null||n==null?!0:n<=r}var ut="oracle-connect-request",On="oracle-unsigned-grant",Ln="oracle-grant-canonical-json-utf8-v1",L=class extends Error{constructor(t,r){super(`secret material must never appear in a public API object (at ${t}, rule: ${r})`),this.name="SecretLeakError",this.path=t,this.rule=r}},$n=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,Un=Object.freeze(["privkey","wif","xprv","seed"]);function xe(e){let t=String(e),r=t.toLowerCase().replace(/[\s._-]+/g,"");return $n.test(t)||Un.includes(r)}var dt=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),pt=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function Bn(e){return e.replace(/"([A-Za-z0-9_-]+)"\s*:\s*"(?:0x)?([0-9a-fA-F]{64})"/g,(t,r)=>pt.includes(String(r).toLowerCase().replace(/[_-]/g,""))?`"${r}":"<hex64>"`:t)}function ft(e){let t;try{t=JSON.stringify(e)}catch(o){throw new L("$",`unserializable-payload: ${String(o?.message||o)}`)}if(t===void 0)return"null";let r=Bn(t);for(let{rule:o,re:s}of dt)if(s.test(r))throw new L("$<serialized>",o);if(/(?:^|[^0-9a-fA-Fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/.test(r))throw new L("$<serialized>","raw-32-byte-hex-embedded");return JSON.parse(t,(o,s)=>{if(o&&xe(o))throw new L(`$<serialized>.${o}`,"forbidden-key-name");return s}),t}function R(e,t="$",r=new Set,n=""){if(e==null)return e;if(typeof e=="string"){let o=pt.includes(String(n).toLowerCase().replace(/[_-]/g,""));for(let{rule:s,re:a}of dt)if(!(o&&s.startsWith("raw-32-byte-hex"))&&a.test(e))throw new L(t,s);return e}if(typeof e!="object"||r.has(e)||(r.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[o,s]of e.entries()){if(typeof o=="string"&&xe(o))throw new L(`${t}[${JSON.stringify(o)}]`,"forbidden-key-name");R(o,`${t}[key]`,r),R(s,`${t}[${String(o)}]`,r)}return e}if(e instanceof Set){let o=0;for(let s of e.values())R(s,`${t}[${o++}]`,r);return e}if(Array.isArray(e))return e.forEach((o,s)=>R(o,`${t}[${s}]`,r)),e;for(let[o,s]of Object.entries(e)){if(xe(o))throw new L(`${t}.${o}`,"forbidden-key-name");R(s,`${t}.${o}`,r,o)}return e}function ne(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))ne(t)}return e}function mt(e,t){let r=Number(typeof e=="string"?e.trim():e);if(!Number.isSafeInteger(r)||r<=0)throw new B([{field:t,message:"must be a positive unix-seconds integer"}]);return r}function ht(e){if(e?.now==null)throw new B([{field:"opts.now",message:"explicit reference time is required for live grant construction"}]);return mt(e.now,"opts.now")}function Mn(e){return new Date(e*1e3).toISOString()}function qn(e,t){let r=e.actions.every(n=>Se(n));return["ORACLE \u2014 CONNECT AGENT (unsigned grant, you sign it, we never do)","=================================================================",`Grant ID: ${t}`,`Version: ${te}`,`Chain: ${e.chainId}`,`Agent: ${e.agentAddress}`,`Your account: ${e.accountAddress}`,`Actions: ${e.actions.join(", ")}`,`Targets: ${e.targets.length?e.targets.join(", "):"(none \u2014 read/simulate only)"}`,`Max value: ${e.maxValueWei} wei`,`Max gas: ${e.maxGasWei} wei`,`Max slippage: ${e.maxSlippageBps} bps`,`Expires: ${Mn(e.expiresAt)} (unix ${e.expiresAt})`,`Nonce: ${e.nonce}`,`Revocation: ${e.revocationKey}`,"-----------------------------------------------------------------",r?"Scope: read/simulate only \u2014 this grant cannot move funds.":"Scope: includes state-changing actions bounded by the caps above.","Self-custodial: this payload is UNSIGNED and contains public data only.","Sign the bytes below with YOUR wallet; Oracle never holds your keys."].join(`
3
+ `)}function bt(e={},t={}){if(e==null||typeof e!="object"||Array.isArray(e))throw new B([{field:"request",message:"request must be a plain object"}]);let r=ht(t),{ttlSeconds:n,...o}=e,s={...o};if(n!=null){if(s.expiresAt!=null)throw new B([{field:"ttlSeconds",message:"pass either ttlSeconds or expiresAt, not both"}]);let c=mt(n,"ttlSeconds");s.expiresAt=r+c}let a=ae(s,{now:r,allowWildcardActions:t.allowWildcardActions===!0}),i=ne({kind:ut,version:te,grant:a});return R(i)}function yt(e={},t={}){let r=ht(t),n=e&&e.kind===ut?e.grant:e,o=ae(n,{now:r,allowWildcardActions:t.allowWildcardActions===!0}),s=Ae(o),a=ie(o),i=Buffer.from(s,"utf8"),c=ne({kind:On,unsigned:!0,payload:ne({version:te,grantId:a,grant:o,canonical:s}),signing:ne({scheme:Ln,message:s,bytesHex:`0x${i.toString("hex")}`,byteLength:i.length,sha256:a}),render:qn(o,a)});return R(c)}var W=Object.freeze({ACTIVE:"active",EXPIRED:"expired",REVOKED:"revoked",INVALID:"invalid"});function gt(e){if(e==null)return[];if(Array.isArray(e))return e;if(e instanceof Map)return[...e.values()];if(typeof e[Symbol.iterator]=="function")return[...e];throw new TypeError("grant store must be an array, Map, or iterable of grant records")}function Dn(e){return e&&typeof e=="object"&&!Array.isArray(e)&&e.grant!=null?{grant:e.grant,revoked:e.revoked===!0||e.revokedAt!=null}:{grant:e,revoked:!1}}function Ee(e){let t=Number(typeof e=="string"?e.trim():e);if(!Number.isSafeInteger(t)||t<0)throw new TypeError("an explicit unix-seconds `now` is required (deterministic liveness, no wall-clock fallback)");return t}function Fn(e,t,r){if(e==null)return!1;if(typeof e=="function")return e(t,r)===!0;let n=[t,r.revocationKey];return e instanceof Set?n.some(o=>e.has(o)):Array.isArray(e)?n.some(o=>e.includes(o)):typeof e.has=="function"?n.some(o=>e.has(o)):!1}function wt(e,{now:t,revoked:r}={}){let n=Ee(t),{grant:o,revoked:s}=Dn(e),{ok:a,grant:i}=ve(o);if(!a)return{status:W.INVALID,id:null,grant:null};let c=ie(i);return s||Fn(r,c,i)?{status:W.REVOKED,id:c,grant:i}:lt(i,n)?{status:W.EXPIRED,id:c,grant:i}:{status:W.ACTIVE,id:c,grant:i}}function St(e,{now:t,revoked:r,agentAddress:n,accountAddress:o,chainId:s}={}){let a=Ee(t),i=n!=null?String(n).trim().toLowerCase():null,c=o!=null?String(o).trim().toLowerCase():null,l=s!=null?Number(s):null,f=[];for(let d of gt(e)){let{status:h,id:u,grant:w}=wt(d,{now:a,revoked:r});h===W.ACTIVE&&(i!=null&&w.agentAddress!==i||c!=null&&w.accountAddress!==c||l!=null&&w.chainId!==l||f.push(Object.freeze({id:u,grant:w})))}return f.sort((d,h)=>d.id<h.id?-1:d.id>h.id?1:0),R(Object.freeze(f))}function vt(e,t,{now:r,revoked:n}={}){let o=Ee(r),s=String(t??"").trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(s))return null;for(let a of gt(e)){let i=wt(a,{now:o,revoked:n});if(i.status!==W.INVALID&&i.id===s)return R(Object.freeze({id:i.id,status:i.status,grant:i.grant}))}return null}import{Interface as Ut,getAddress as ir,id as Bt}from"ethers";import{createHash as Hn}from"node:crypto";var Vn=new Set([408,425,429,500,502,503,504]),At=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),zn=2,xt=4e3,_t=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Kn=new Set([301,302,303,307,308]),Et=3;function jn(e){let t=String(e||"").toLowerCase();return _t.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function Wn(e){let t={};for(let[r,n]of Object.entries(e||{}))jn(r)||(t[r]=n);return t}function Gn(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 Yn(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var _e=new Map;function Jn(e,t,r){let n={};for(let[c,l]of Object.entries(r||{}))n[c.toLowerCase()]=l;let o=Object.keys(n).filter(c=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(c)),a=[...new Set([..._t,...o])].sort().map(c=>`${c}=${n[c]??""}`).join(`
4
+ `),i=Hn("sha256").update(a).digest("hex").slice(0,32);return`${e} ${t} ${i}`}function Xn(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,xt):Math.min(250*2**e,xt)+Math.floor(Math.random()*100)}var Qn=e=>new Promise(t=>setTimeout(t,e));async function Zn(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:s}){let a=new AbortController,i=setTimeout(()=>a.abort(),s);try{let c=String(e),l={...n||{}};for(let f=0;f<=Et;f+=1){let d=await t(c,{method:r,headers:l,body:o,signal:a.signal,redirect:"manual"}),h=await d.text(),u=null;if(h)try{u=JSON.parse(h)}catch{u=null}if(Kn.has(d.status)){if(r!=="GET"&&r!=="HEAD"){let A=new Error(`HTTP ${d.status} ${r} ${c} redirected non-idempotent request`);throw A.status=d.status,A.body=u??h.slice(0,300),A}if(f===Et)throw new Error(`HTTP redirect loop for ${e}`);let w=Gn(d.headers?.get?.("location"),c);Yn(w,c)||(l=Wn(l)),c=w;continue}if(!d.ok){let w=new Error(`HTTP ${d.status} ${r} ${c}`);throw w.status=d.status,w.retryAfter=d.headers?.get?.("retry-after")??null,w.body=u??h.slice(0,300),w}return u??h}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(i)}}async function N(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),s={Accept:"application/json",...t.headers||{}},a=t.body;a!=null&&typeof a!="string"&&(s["Content-Type"]=s["Content-Type"]||"application/json",a=JSON.stringify(a));let i=Number.isInteger(t.retries)?Math.max(t.retries,0):zn,c=async()=>{let u;for(let w=0;w<=i;w++)try{return await Zn(e,{fetchImpl:r,method:o,headers:s,body:a,timeoutMs:n})}catch(A){u=A;let v=A?.status,_=A?.name==="AbortError",k=new Set([408,425,429]),q=v!=null?k.has(v)||Vn.has(v)&&At.has(o):!_&&At.has(o);if(w===i||!q)throw A;await Qn(Xn(w,A?.retryAfter))}throw u};if(!(t.dedupe!==!1&&o==="GET"&&a==null))return c();let f=Jn(o,e,s),d=_e.get(f);if(d)return d;let h=c().finally(()=>_e.delete(f));return _e.set(f,h),h}async function I(e){let t=Date.now();try{let r=await e();return{ok:!0,ms:Date.now()-t,data:r}}catch(r){return{ok:!1,ms:Date.now()-t,error:String(r.message||r),status:r.status??null}}}async function H(e,t,r){let n=Array.from(e),o=Math.max(1,Math.min(Number(t)||1,n.length||1)),s=new Array(n.length),a=0;return await Promise.all(Array.from({length:o},async()=>{for(;a<n.length;){let i=a++;s[i]=await r(n[i],i)}})),s}var It={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}},er=new Map(Object.values(It).map(e=>[e.chainId,e]));function kt(e){return er.get(Number(e))||null}function Nt(e,t=process.env){let r=kt(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 tr,getAddress as nr}from"ethers";var Ct=new tr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Ie(e,t){try{return nr(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}var rr={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 or(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Nt(e,r);return n||rr[Number(e)]||null}var sr=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ar(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!sr.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}async function M(e,t,r=[],n={}){let o=String(t||"");ar(o);let s=or(e,n);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let i=await N(s,{method:"POST",body:{jsonrpc:"2.0",id:1,method:t,params:r},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(i?.error){let c=new Error(i.error.message||JSON.stringify(i.error));throw c.code=i.error.code,c}return i.result}async function ke(e,t={}){let r=await M(e,"eth_blockNumber",[],t);return parseInt(r,16)}async function Ne(e,t,r={}){if(!t)throw new Error("rpcGetBalance requires address");let n=await M(e,"eth_getBalance",[t,"latest"],r);return{chainId:Number(e),address:t,balanceWei:BigInt(n).toString(),balanceHex:n}}async function Tt(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Ie(e.token||e.tokenAddress,"token"),o=Ie(e.owner,"owner"),s=Ie(e.spender,"spender"),a=Ct.encodeFunctionData("allowance",[o,s]),i=await M(r,"eth_call",[{to:n,data:a},e.blockTag||"latest"],t),c=Ct.decodeFunctionResult("allowance",i),l=BigInt(c[0]);return{chainId:r,token:n,owner:o,spender:s,allowance:l.toString(),allowanceHex:`0x${l.toString(16)}`,blockTag:e.blockTag||"latest"}}var Cs=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),Ce=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),Te=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var ce=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);var Pt=new Ut(["function decimals() view returns (uint8)","function symbol() view returns (string)"]),Rt=new Ut(["function isApprovedForAll(address owner, address operator) view returns (bool)","function name() view returns (string)"]),cr=Bt("Approval(address,address,uint256)"),na=Bt("ApprovalForAll(address,address,bool)"),lr=1e4,ur=2e5,dr=Object.freeze({"0x1111111254eeb25477b68fb85ed929f73a960582":"1inch v5 Router","0x111111125421ca6dc452d289314280a0f8842a65":"1inch v6 Router","0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45":"Uniswap Universal Router","0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad":"Uniswap Universal Router","0x000000000022d473030f116ddee9f6b43ac78ba3":"Permit2","0xe592427a0aece92de3edee1f18e0157c05861564":"Uniswap v3 Router","0x7a250d5630b4cf539739df2c5dacb4c659f2488d":"Uniswap v2 Router","0xdef1c0ded9bec7f1a1670819833240f027b25eff":"0x Exchange Proxy","0x2626664c2603336e57b271c5c0b26f421741e481":"Uniswap SwapRouter02 (Base)","0x6131b5fae19ea4f9d964eac0408e4408b66337b5":"KyberSwap Meta Aggregator","0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC (token contract)"}),pr=Object.freeze([{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"},{address:"0x1111111254eeb25477b68fb85ed929f73a960582",label:"1inch v5 Router"},{address:"0x111111125421ca6dc452d289314280a0f8842a65",label:"1inch v6 Router"},{address:"0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45",label:"Uniswap Universal Router"},{address:"0xe592427a0aece92de3edee1f18e0157c05861564",label:"Uniswap v3 Router"},{address:"0x7a250d5630b4cf539739df2c5dacb4c659f2488d",label:"Uniswap v2 Router"},{address:"0xdef1c0ded9bec7f1a1670819833240f027b25eff",label:"0x Exchange Proxy"},{address:"0x2626664c2603336e57b271c5c0b26f421741e481",label:"Uniswap SwapRouter02"}]),fr=Object.freeze([{address:"0x1e0049783f008a0085193e00003d00cd54003c71",label:"OpenSea Seaport Conduit"},{address:"0x00000000000000adc04c56bf30ac9d3c0aaf14dc",label:"Seaport 1.5"},{address:"0x0000000000000068f116a894984e2db1123eb395",label:"Seaport 1.6"},{address:"0x00000000000001ad428e4906ae43d8f9852d0dd6",label:"Seaport 1.4"},{address:"0x000000000000ad05ccc4f10045630fb830b95127",label:"Blur Marketplace"},{address:"0x00000000000000000000000000000000000000a5",label:"Blur Execution Delegate"},{address:"0xf42aa99f011a1fa7cda90e5e98b277e306bca83e",label:"Rarible Transfer Proxy"},{address:"0x000000000022d473030f116ddee9f6b43ac78ba3",label:"Permit2"}]),mr=Object.freeze({1:[{address:"0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",name:"Bored Ape Yacht Club"},{address:"0x60e4d786628fea6478f785a6d7e704777c86a7c6",name:"Mutant Ape Yacht Club"},{address:"0xed5af388653567af2f388e6224dc7c4b3241c544",name:"Azuki"},{address:"0x8a90cab2b38dba80c64b7734e58ee1db38b8992e",name:"Doodles"},{address:"0x49cf6f5d44e70224e2e23fdcdd2c053f30ada28b",name:"CloneX"},{address:"0x23581767a106ae21c074b2276d25e5c3e136a68b",name:"Moonbirds"}]}),hr=Object.freeze({1:[{address:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",symbol:"USDC",decimals:6},{address:"0xdac17f958d2ee523a2206206994597c13d831ec7",symbol:"USDT",decimals:6},{address:"0x6b175474e89094c44da98b954eedeac495271d0f",symbol:"DAI",decimals:18},{address:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",symbol:"WETH",decimals:18},{address:"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",symbol:"WBTC",decimals:8}],8453:[{address:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],42161:[{address:"0xaf88d065e77c8cc2239327c5edb3a432268e5831",symbol:"USDC",decimals:6},{address:"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9",symbol:"USDT",decimals:6},{address:"0x82af49447d8a07e3bd95bd0d56f35241523fbab1",symbol:"WETH",decimals:18}],10:[{address:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",symbol:"USDC",decimals:6},{address:"0x4200000000000000000000000000000000000006",symbol:"WETH",decimals:18}],137:[{address:"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",symbol:"USDC",decimals:6},{address:"0xc2132d05d31c914a87c6611c10748aeb04b58e8f",symbol:"USDT",decimals:6}]}),br=(1n<<256n)-1n,yr=br/2n,gr=4320*60*60*1e3,wr=360*60*1e3,Sr=600*1e3,vr=45*1e3,Ar=512,xr=128,Ot=new Map,Pe=new Map,Lt=new Map;function G(e){return e?.cache===!1?!1:!e?.fetchImpl||e.cache===!0}function Oe(e,t,r){let n=e.get(t);return n?Date.now()-n.at>r?(e.delete(t),null):n:null}function le(e,t,r,n){for(e.delete(t),e.set(t,{at:Date.now(),value:r});e.size>n;){let o=e.keys().next();if(o.done)break;e.delete(o.value)}}function Er(e,t){try{return ir(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function _r(e){return`0x${e.slice(2).toLowerCase().padStart(64,"0")}`}function $t(e){return`0x${String(e).slice(-40).toLowerCase()}`}function Ir({unlimited:e,spenderLabel:t,lastActivityAt:r}){if(e)return"unlimited";if(!t)return"unknown-spender";if(r){let n=Date.parse(r);if(Number.isFinite(n)&&Date.now()-n>gr)return"stale"}return"scoped"}function kr(e,t,r){if(r)return"UNLIMITED";if(t==null)return e.toString();let n=10n**BigInt(t),o=e/n,s=e%n;if(s===0n)return o.toLocaleString("en-US");let a=s.toString().padStart(t,"0").replace(/0+$/,"").slice(0,6);return`${o.toLocaleString("en-US")}${a?`.${a}`:""}`}async function Nr(e,t,r,n){let o=`${e}:${t}`,s=n?.get(o);if(s)return s;if(G(r)){let i=Oe(Ot,o,wr);if(i)return i.value}let a=(async()=>{let i=async d=>{try{let h=Pt.encodeFunctionData(d,[]),u=await M(e,"eth_call",[{to:t,data:h},"latest"],r);return!u||u==="0x"?null:Pt.decodeFunctionResult(d,u)[0]}catch{return null}},[c,l]=await Promise.all([i("decimals"),i("symbol")]),f={decimals:c==null?null:Number(c),symbol:l==null?null:String(l).slice(0,24)};return G(r)&&le(Ot,o,f,Ar),f})();return n?.set(o,a),a}async function Cr(e,t,r){let n=Math.min(Math.max(Number(r.lookbackBlocks)||lr,1),ur),o=await ke(e,r);if(!Number.isFinite(o))throw new Error("chain head unavailable");let s=Math.max(0,o-n),a=await M(e,"eth_getLogs",[{fromBlock:`0x${s.toString(16)}`,toBlock:"latest",topics:[cr,_r(t)]}],r);if(!Array.isArray(a))throw new Error("log scan returned no array");let i=new Map;for(let c of a){let l=String(c?.address||"").toLowerCase(),f=c?.topics?.[2];!l||!f||i.set(`${l}:${$t(f)}`,{token:l,spender:$t(f)})}return{pairs:[...i.values()],fromBlock:s,toBlock:o}}function Tr(e){return(hr[e]||[]).flatMap(r=>pr.map(n=>({token:r.address,spender:n.address,symbol:r.symbol,decimals:r.decimals})))}async function Pr(e,t,r={}){let n=[],o="direct-probe",s=null,a=Tr(e),i=Re(e),c=G(r)&&Oe(Pe,e,Sr)?.value===!1;if(a.length===0&&i.length===0&&c)return{scan:{chainId:e,status:"unconfigured",method:o,error:"no Approval log access and no candidate token or collection set for this chain"},approvals:[]};try{let l=await Cr(e,t,r);n=l.pairs,o="log-scan",s={fromBlock:l.fromBlock,toBlock:l.toBlock},G(r)&&le(Pe,e,!0,64)}catch{if(G(r)&&le(Pe,e,!1,64),n=a,n.length===0&&i.length===0)return{scan:{chainId:e,status:"unconfigured",method:o,error:"no Approval log access and no candidate token or collection set for this chain"},approvals:[]}}try{let l=new Map,d=(await H(n,r.concurrency||4,async u=>{try{let w=await Tt({chainId:e,token:u.token,owner:t,spender:u.spender},r),A=BigInt(w.allowance);if(A<=0n)return null;let v=u.symbol?{symbol:u.symbol,decimals:u.decimals??null}:await Nr(e,u.token,r,l),_=A>=yr,k=dr[u.spender]||null;return{id:`${e}:${u.token}:${u.spender}`,chainId:e,standard:"erc20",token:u.token,tokenSymbol:v.symbol,decimals:v.decimals,spender:u.spender,spenderLabel:k,allowance:A.toString(),allowanceDisplay:kr(A,v.decimals,_),unlimited:_,lastActivityAt:null,risk:Ir({unlimited:_,spenderLabel:k,lastActivityAt:null})}}catch{return null}})).filter(Boolean),h=await Or(e,t,r);return{scan:{chainId:e,status:"ok",method:o,pairsProbed:n.length,collectionsProbed:Re(e).length,...s||{}},approvals:[...d,...h]}}catch(l){return{scan:{chainId:e,status:"unavailable",method:o,error:String(l?.message||l).slice(0,200)},approvals:[]}}}async function Rr(e,t,r,n,o){try{let s=Rt.encodeFunctionData("isApprovedForAll",[r,n]),a=await M(e,"eth_call",[{to:t,data:s},"latest"],o);return!a||a==="0x"?null:!!Rt.decodeFunctionResult("isApprovedForAll",a)[0]}catch{return null}}function Re(e){return(mr[e]||[]).flatMap(r=>fr.map(n=>({collection:r.address,collectionName:r.name,operator:n.address,operatorLabel:n.label})))}async function Or(e,t,r){let n=Re(e);return n.length===0?[]:(await H(n,r.concurrency||4,async s=>await Rr(e,s.collection,t,s.operator,r)!==!0?null:{id:`${e}:${s.collection}:${s.operator}:all`,chainId:e,standard:"erc721",token:s.collection,tokenSymbol:s.collectionName,decimals:null,spender:s.operator,spenderLabel:s.operatorLabel,allowance:null,allowanceDisplay:"ALL ITEMS",unlimited:!0,lastActivityAt:null,risk:"operator-all"})).filter(Boolean)}async function Mt(e={},t={}){let r=Er(e.owner||e.address,"owner"),n=new Map(ce.map(u=>[u.chainId,u])),o=Array.isArray(e.chainIds)&&e.chainIds.length?[...new Set(e.chainIds.map(Number))].filter(u=>n.has(u)):[...n.keys()],s=`${r}:${[...o].sort((u,w)=>u-w).join(",")}:${e.lookbackBlocks??""}`,a=G(t)&&!e.refresh;if(a){let u=Oe(Lt,s,vr);if(u)return{...u.value,cached:!0,cachedAgeMs:Date.now()-u.at}}let i=await H(o,e.concurrency||3,u=>Pr(u,r,{...t,lookbackBlocks:e.lookbackBlocks})),c=i.flatMap(u=>u.approvals),l=i.map(u=>u.scan),f=l.find(u=>u.method==="log-scan"&&u.toBlock),d=l.some(u=>u.method==="direct-probe"&&u.status==="ok"),h={provider:"approvals",operation:"scan",readOnly:!0,queriedAt:new Date().toISOString(),owner:r,scannedRange:f?`last ${f.toBlock-f.fromBlock} blocks`:d?"known routers, live allowance probe":null,approvals:c,scans:l,warnings:["Approval discovery is scoped. Log scanning is used where the endpoint permits it; otherwise a curated router set is probed directly. An empty result means nothing was found in that scope, not that the wallet is safe.","NFT operator approval (setApprovalForAll) is checked against a curated collection and marketplace set on supported chains only. A collection outside that set is not checked."]};return a&&le(Lt,s,h,xr),{...h,cached:!1,cachedAgeMs:0}}import{getAddress as Zr}from"ethers";var qt="mainnet-beta",Lr="https://api.mainnet-beta.solana.com",Le="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";function $r(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||Lr).trim()}function z(e,t="address"){let r=String(e||"").trim();if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(r))throw new Error(`solana-rpc: ${t} must be a base58 public key`);return r}function Ur(e,t){return t?[...e,{commitment:t}]:e}async function Dt(e,t=[],r={}){let n=String(e||"");if(n==="sendTransaction"||n==="sendRawTransaction"||n==="requestAirdrop"||n==="requestAirDrop"||/airdrop/i.test(n)||/^send/i.test(n))throw new Error(`solana-rpc: ${n} refused \u2014 @oracle-agent/oracle is prepare-only (no broadcast/airdrop)`);let o=await N($r(r),{method:"POST",body:{jsonrpc:"2.0",id:r.id||1,method:e,params:t},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3});if(o?.error)throw new Error(`solana-rpc ${e}: ${o.error.message||JSON.stringify(o.error)}`);return o?.result}async function Ft(e={},t={}){let r=z(e.address||e.owner,"address"),n=await Dt("getBalance",Ur([r],e.commitment),t);return{provider:"solana-rpc",cluster:qt,address:r,lamports:String(n?.value??0),slot:n?.context?.slot??null,raw:n}}function Br(e={}){let t=e.account?.data?.parsed?.info||{},r=t.tokenAmount||{};return{pubkey:e.pubkey,mint:t.mint||null,owner:t.owner||null,amount:String(r.amount??"0"),decimals:r.decimals??null,uiAmount:r.uiAmount??null,uiAmountString:r.uiAmountString??null,raw:e}}async function $e(e={},t={}){let r=z(e.owner||e.address,"owner"),n=e.mint?{mint:z(e.mint,"mint")}:{programId:z(e.programId||Le,"token program")},o={encoding:"jsonParsed"};e.commitment&&(o.commitment=e.commitment);let s=await Dt("getTokenAccountsByOwner",[r,n,o],t),a=Array.isArray(s?.value)?s.value.map(Br):[];return{provider:"solana-rpc",cluster:qt,owner:r,filter:n,slot:s?.context?.slot??null,accounts:a,raw:s}}var Mr="mainnet",qr="https://mempool.space/api",Dr="https://mempool.space/testnet/api";function Ht(e={}){return String(e.network||process.env.BTC_NETWORK||Mr).trim().toLowerCase()==="testnet"?"testnet":"mainnet"}function Fr(e={}){return e.baseUrl?String(e.baseUrl).replace(/\/$/,""):process.env.BTC_ESPLORA_URL?String(process.env.BTC_ESPLORA_URL).replace(/\/$/,""):Ht(e)==="testnet"?Dr:qr}function V(e,t="address"){let r=String(e||"").trim();if(!/^(bc1|tb1|bcrt1)[a-z0-9]{20,90}$/i.test(r)&&!/^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(r))throw new Error(`bitcoin-esplora: ${t} must look like a Bitcoin address`);return r}async function Hr(e,t={}){let r=`${Fr(t)}${e.startsWith("/")?e:`/${e}`}`,o=await(t.fetchImpl||fetch)(r,{method:"GET",headers:{accept:"application/json,text/plain;q=0.9,*/*;q=0.8"},signal:AbortSignal.timeout(t.timeoutMs??12e3)}),s=await o.text();if(!o.ok)throw new Error(`bitcoin-esplora GET ${e}: HTTP ${o.status} ${s.slice(0,160)}`);return s}async function Vr(e,t={}){let r=await Hr(e,t);try{return JSON.parse(r)}catch{return r}}async function Vt(e={},t={}){let r=V(e.address||e.addr,"address"),n=await Vr(`/address/${r}`,t),o=n.chain_stats||{},s=n.mempool_stats||{},a=Number(o.funded_txo_sum||0)+Number(s.funded_txo_sum||0),i=Number(o.spent_txo_sum||0)+Number(s.spent_txo_sum||0);return{provider:"bitcoin-esplora",network:Ht(t),address:r,balanceSats:String(a-i),chainStats:o,mempoolStats:s,raw:n}}var zt="ORACLE_ALLOW_CUSTOM_PROVIDER_URL";function Y({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:Kt(t)};let i;try{i=new URL(a)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=i.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([Kt(t),...r]).has(c)){let f=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return i.protocol==="http:"&&!f?{baseUrl:a,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:a,trusted:!0,host:c}}if(String(process.env[zt]||"")==="1")return{baseUrl:a,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${zt}=1 to permit it)`);return{baseUrl:a,trusted:!1,host:c}}function Kt(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function K(e,t,r){let n={...e};if(!r)return n;for(let[o,s]of Object.entries(t||{}))s&&(n[o]=s);return n}function Ue(e={}){return String(e.baseUrl||process.env.BTC_META_API_URL||process.env.UNISAT_API_URL||"").trim().replace(/\/$/,"")}var zr=["open-api.unisat.io","open-api-testnet.unisat.io","api.bestinslot.xyz","api.hiro.so"];function Kr(e={}){let t=e.apiKey||process.env.UNISAT_API_KEY||process.env.BESTINSLOT_API_KEY||process.env.BTC_META_API_KEY||"",r=!1;try{let n=Ue(e);if(n){let o=new URL(n).host,s=new URL(n).protocol,a=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(o);r=zr.includes(o)&&(s==="https:"||a)}}catch{r=!1}return K({accept:"application/json","user-agent":"oracle-btc-meta/0.1"},{authorization:t?`Bearer ${t}`:"","x-api-key":t},r)}async function jt(e,t={}){let n=await(t.fetchImpl||fetch)(e,{method:"GET",headers:Kr(t),signal:AbortSignal.timeout(t.timeoutMs??12e3)}),o=await n.text(),s;try{s=JSON.parse(o)}catch{s=o}if(!n.ok)throw new Error(`bitcoin-meta GET ${e}: HTTP ${n.status} ${String(o).slice(0,160)}`);return s}async function Wt(e={},t={}){let r=V(e.address||e.addr,"address"),n=Ue(t);if(!n)return{provider:"bitcoin-meta",address:r,ok:!1,balances:[],error:"no indexer configured (set BTC_META_API_URL or vendor API key env)"};let o=[`${n}/v1/indexer/address/${r}/runes/balance-list?start=0&limit=100`,`${n}/v1/runes/address/${r}`,`${n}/runes/balance/${r}`,`${n}/address/${r}/runes`],s=null;for(let a of o)try{let i=await jt(a,t),c=jr(i);return{provider:"bitcoin-meta",address:r,ok:!0,count:c.length,balances:c,source:a}}catch(i){s=i}return{provider:"bitcoin-meta",address:r,ok:!1,balances:[],error:String(s?.message||s||"all indexer paths failed")}}function jr(e){let t=e?.data?.detail||e?.data?.list||e?.data||e?.balances||e?.results||e?.runes||(Array.isArray(e)?e:[]);return(Array.isArray(t)?t:[]).map(n=>({rune:n.rune||n.runeid||n.runeId||n.spacedRune||n.name||n.ticker||null,runeId:n.runeid||n.runeId||n.id||null,amount:String(n.amount??n.balance??n.total??n.qty??"0"),symbol:n.symbol||null,divisibility:n.divisibility??n.div??null,raw:n}))}async function ue(e={},t={}){let r=V(e.address||e.addr,"address"),n=Ue(t);if(!n)return{provider:"bitcoin-meta",address:r,ok:!1,inscriptions:[],error:"no indexer configured \u2014 address-indexed lookups need a keyed indexer (BTC_META_API_URL + UNISAT_API_KEY / BESTINSLOT_API_KEY). ordinals.com recursive is keyless but has no address index.",unknownNotEmpty:!0,keylessAlternatives:["btc_inscription_info (by inscription id)","btc_meta_health"]};let o=Math.min(Number(e.limit||50),200),s=[`${n}/v1/indexer/address/${r}/inscription-data?cursor=0&size=${o}`,`${n}/v1/inscriptions/address/${r}?limit=${o}`,`${n}/address/${r}/inscriptions?limit=${o}`],a=null;for(let i of s)try{let c=await jt(i,t),l=Wr(c);return{provider:"bitcoin-meta",address:r,ok:!0,count:l.length,inscriptions:l,source:i}}catch(c){a=c}return{provider:"bitcoin-meta",address:r,ok:!1,inscriptions:[],error:String(a?.message||a||"all indexer paths failed")}}function Wr(e){let t=e?.data?.inscription||e?.data?.detail||e?.data?.list||e?.data||e?.inscriptions||e?.results||(Array.isArray(e)?e:[]);return(Array.isArray(t)?t:[]).map(n=>({id:n.inscriptionId||n.id||n.inscription_id||null,number:n.inscriptionNumber??n.number??null,sat:n.sat||n.satoshi||null,contentType:n.contentType||n.content_type||null,utxo:n.utxo||n.output||(n.txid!=null?`${n.txid}:${n.vout??n.n}`:null),raw:n}))}var Gr="https://api.hyperliquid.xyz/info",Yr="https://api.hyperliquid-testnet.xyz/info";function Jr({testnet:e,baseUrl:t}={}){if(t)return t.replace(/\/$/,"").endsWith("/info")?t:`${t.replace(/\/$/,"")}/info`;if(process.env.HL_INFO_URL)return process.env.HL_INFO_URL;if(process.env.HL_API_URL){let r=process.env.HL_API_URL.replace(/\/$/,"");return r.endsWith("/info")?r:`${r}/info`}return e||process.env.HL_TESTNET==="1"?Yr:Gr}async function Be(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let r=Jr(t);return N(r,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function Gt(e={}){return Be({type:"allMids"},e)}async function Yt(e,t={}){if(!e)throw new Error("hlClearinghouse requires user address");return Be({type:"spotClearinghouseState",user:e},t)}async function Jt(e,t={}){if(!e)throw new Error("hlUserState requires user");return Be({type:"clearinghouseState",user:e},t)}var Xr="https://coins.llama.fi";function Qr(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||Xr).replace(/\/$/,"")}async function Xt(e,t={}){if(!Array.isArray(e)||!e.length)throw new Error("llamaPrices requires coins[]");let r=e.map(encodeURIComponent).join(",");return N(`${Qr(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}var eo="TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",Zt=Object.freeze({ETH:"coingecko:ethereum",POL:"coingecko:polygon-ecosystem-token",BNB:"coingecko:binancecoin",AVAX:"coingecko:avalanche-2",HYPE:"coingecko:hyperliquid",USDT0:"coingecko:tether",SOL:"coingecko:solana",BTC:"coingecko:bitcoin"});function J(e={},t){return{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,env:e.env,...e[t]||{}}}function de(e,...t){for(let r of t){let n=String(e?.[r]||"").trim();if(n)return n}return null}function Qt(e){if(!e)return null;try{return Zr(String(e).trim().toLowerCase())}catch{throw new Error("portfolio: EVM address must be a valid 20-byte address")}}function Fe(e={},t=process.env){let r=e.addresses||{},n=Qt(r.evm||e.evmAddress||de(t,"ORACLE_EVM_ADDRESS","ORACLE_DEFAULT_ADDRESS","MAD_OPERATOR_ADDRESS")),o=r.solana||e.solanaAddress||de(t,"ORACLE_SOLANA_ADDRESS"),s=r.bitcoin||e.bitcoinAddress||de(t,"ORACLE_BITCOIN_ADDRESS"),a=Qt(r.hyperliquid||e.hyperliquidAddress||de(t,"ORACLE_HYPERLIQUID_ADDRESS")||n);return{evm:n,solana:o?z(o,"portfolio Solana address"):null,bitcoin:s?V(s,"portfolio Bitcoin address"):null,hyperliquid:a}}function pe(e,t){let r=BigInt(String(e||"0")),n=Number(t);if(!Number.isInteger(n)||n<0||n>36)throw new Error("portfolio: decimals must be an integer from 0 to 36");if(n===0)return r.toString();let o=r<0n,s=o?-r:r,a=10n**BigInt(n),i=s/a,c=String(s%a).padStart(n,"0").replace(/0+$/,"");return`${o?"-":""}${i}${c?`.${c}`:""}`}function re(e){let t=Number(e);return Number.isFinite(t)?t:null}function De(e){return Number.isFinite(e)?Number(e.toFixed(2)):null}function X(e){let t=Number(e);return Number.isFinite(t)&&t!==0}function en(e,t){let r=Zt[t],n=r?e?.coins?.[r]:null,o=Number(n?.price);return{key:r||null,priceUsd:Number.isFinite(o)?o:null,timestamp:n?.timestamp??null,confidence:n?.confidence??null}}function to(e){let t=new Map;for(let r of e)if(r?.ok)for(let n of r.data?.accounts||[]){let o=BigInt(String(n.amount||"0"));if(o===0n||!n.mint)continue;let s=`${n.mint}:${n.decimals??"unknown"}`,a=t.get(s)||{mint:n.mint,amountRaw:0n,decimals:n.decimals??null,programs:new Set,accounts:0};a.amountRaw+=o,a.accounts+=1,r.program&&a.programs.add(r.program),t.set(s,a)}return[...t.values()].map(r=>{let n=r.amountRaw.toString(),o=r.decimals==null?null:pe(n,r.decimals),s=r.decimals===0&&r.amountRaw===1n;return{mint:r.mint,amountRaw:n,amount:o,decimals:r.decimals,tokenPrograms:[...r.programs],accountCount:r.accounts,verification:"unverified",classification:s?"collectible-candidate":"fungible-or-unclassified",priceUsd:null,usdValue:null}})}function Me(e,t){return{family:e,status:"unsupported",reason:t}}function qe(e,t){if(!e||e.status!=="ok")return e;let r=en(t,e.symbol),n=re(e.amount),o=n!=null&&r.priceUsd!=null?De(n*r.priceUsd):null;return{...e,price:r,usdValue:o}}async function tn(e={},t={}){let r=new Date().toISOString(),n=Fe(e,t.env||process.env),o=e.includePrices!==!1,s=e.includeTokens!==!1,a=e.includeCollectibles!==!1,i=new Map(ce.map(m=>[m.chainId,m])),c=Array.isArray(e.evmChainIds)&&e.evmChainIds.length?[...new Set(e.evmChainIds.map(Number))]:[...i.keys()],l=[...new Set(Object.values(Zt))],f=o?I(()=>Xt(l,J(t,"prices"))):Promise.resolve({ok:!1,ms:0,error:"price lookup disabled"}),d=H(c,e.concurrency||5,async m=>{let g=i.get(m);if(!g)return{family:"evm",chainId:m,name:null,address:n.evm,status:"unsupported",error:"chainId is not in Oracle's configured EVM registry"};if(!n.evm)return{family:"evm",chainId:m,name:g.name,address:null,status:"not-configured",error:"set ORACLE_EVM_ADDRESS or pass addresses.evm"};let S={...J(t,"evm"),rpcUrl:e.rpcUrls?.[m]||t.evm?.rpcUrls?.[m]},E=await I(()=>Ne(m,n.evm,S));if(!E.ok)return{family:"evm",chainId:m,name:g.name,address:n.evm,status:"unavailable",latencyMs:E.ms,error:E.error};let U=g.nativeCurrency?.decimals??18,O=g.nativeCurrency?.symbol||"NATIVE",b=E.data.balanceWei;return{family:"evm",chainId:m,name:g.name,address:n.evm,status:"ok",latencyMs:E.ms,native:{status:"ok",symbol:O,amountRaw:b,decimals:U,amount:pe(b,U)},fungibleTokens:{status:s?"unavailable":"not-requested",assets:[],reason:s?"EVM JSON-RPC cannot enumerate wallet tokens without an address indexer":"token discovery disabled"},collectibles:{status:a?"unavailable":"not-requested",assets:[],reason:a?"EVM JSON-RPC cannot enumerate wallet NFTs without an address indexer":"collectible discovery disabled"},source:"evm-rpc"}}),h=(async()=>{if(!n.solana)return{family:"solana",name:"Solana Mainnet",address:null,status:"not-configured",error:"set ORACLE_SOLANA_ADDRESS or pass addresses.solana"};let m=J(t,"solana"),g=await I(()=>Ft({address:n.solana},m)),S=s||a?await Promise.all([I(()=>$e({owner:n.solana,programId:Le},m)).then(P=>({...P,program:"spl-token"})),I(()=>$e({owner:n.solana,programId:eo},m)).then(P=>({...P,program:"token-2022"}))]):[],E=to(S),U=E.filter(P=>P.classification==="collectible-candidate"),O=E.filter(P=>P.classification!=="collectible-candidate"),b=S.filter(P=>!P.ok).map(P=>P.error);return{family:"solana",name:"Solana Mainnet",address:n.solana,status:g.ok||S.some(P=>P.ok)?"ok":"unavailable",native:g.ok?{status:"ok",symbol:"SOL",amountRaw:g.data.lamports,decimals:9,amount:pe(g.data.lamports,9),slot:g.data.slot}:{status:"unavailable",symbol:"SOL",error:g.error},fungibleTokens:{status:s?b.length===S.length?"unavailable":b.length?"partial":"ok":"not-requested",assets:s?O:[],errors:b,note:"SPL accounts are unverified until a metadata/indexer source confirms symbol and spam status"},collectibles:{status:a?b.length===S.length?"unavailable":"partial":"not-requested",assets:a?U:[],errors:b,note:"decimals=0 and amount=1 is only a collectible candidate, not verified NFT metadata"},source:"solana-rpc"}})(),u=(async()=>{if(!n.bitcoin)return{family:"bitcoin",name:"Bitcoin Mainnet",address:null,status:"not-configured",error:"set ORACLE_BITCOIN_ADDRESS or pass addresses.bitcoin"};let m=J(t,"bitcoin"),g=J(t,"bitcoinMeta"),[S,E,U]=await Promise.all([I(()=>Vt({address:n.bitcoin},m)),s?I(()=>Wt({address:n.bitcoin},g)):Promise.resolve({ok:!1,ms:0,error:"token discovery disabled"}),a?I(()=>ue({address:n.bitcoin},g)):Promise.resolve({ok:!1,ms:0,error:"collectible discovery disabled"})]),O=E.ok?E.data:null,b=U.ok?U.data:null;return{family:"bitcoin",name:"Bitcoin Mainnet",address:n.bitcoin,status:S.ok||O?.ok||b?.ok?"ok":"unavailable",native:S.ok?{status:"ok",symbol:"BTC",amountRaw:S.data.balanceSats,decimals:8,amount:pe(S.data.balanceSats,8)}:{status:"unavailable",symbol:"BTC",error:S.error},fungibleTokens:{status:s?O?.ok?"ok":"unavailable":"not-requested",assets:O?.balances||[],error:O?.ok?null:O?.error||E.error,verification:"indexer-reported"},collectibles:{status:a?b?.ok?"ok":"unavailable":"not-requested",assets:b?.inscriptions||[],error:b?.ok?null:b?.error||U.error,unknownNotEmpty:!!b?.unknownNotEmpty,verification:"indexer-reported"},source:"bitcoin-esplora+bitcoin-meta"}})(),w=(async()=>{if(!n.hyperliquid)return{family:"hyperliquid",name:"Hyperliquid HyperCore",address:null,status:"not-configured",error:"set ORACLE_HYPERLIQUID_ADDRESS or pass addresses.hyperliquid"};let m=J(t,"hyperliquid"),[g,S,E]=await Promise.all([I(()=>Yt(n.hyperliquid,m)),I(()=>Jt(n.hyperliquid,m)),I(()=>Gt(m))]),U=(g.ok&&Array.isArray(g.data?.balances)?g.data.balances:[]).filter(b=>X(b.total)||X(b.hold)).map(b=>({coin:b.coin||null,total:String(b.total??"0"),hold:String(b.hold??"0"),priceUsd:null,usdValue:null})),O=(S.ok&&Array.isArray(S.data?.assetPositions)?S.data.assetPositions:[]).map(b=>b.position||b).filter(b=>X(b.szi)).map(b=>({coin:b.coin||null,size:String(b.szi??"0"),entryPrice:b.entryPx??null,positionValueUsd:b.positionValue??null,unrealizedPnlUsd:b.unrealizedPnl??null,liquidationPrice:b.liquidationPx??null}));return{family:"hyperliquid",name:"Hyperliquid HyperCore",address:n.hyperliquid,status:g.ok||S.ok?"ok":"unavailable",spot:{status:g.ok?"ok":"unavailable",balances:U,error:g.ok?null:g.error},perps:{status:S.ok?"ok":"unavailable",accountValueUsd:S.data?.marginSummary?.accountValue??null,withdrawableUsd:S.data?.withdrawable??null,positions:O,error:S.ok?null:S.error},mids:E.ok?E.data:{},source:"hyperliquid-info"}})(),[A,v,_,k,q]=await Promise.all([d,h,u,w,f]),p=q.ok?q.data:null,y=A.map(m=>m.native?{...m,native:qe(m.native,p)}:m);v.native&&(v.native=qe(v.native,p)),_.native&&(_.native=qe(_.native,p));let x=0,$=0,Z=0;for(let m of[...y,v,_])m.native?.status!=="ok"||!X(m.native.amount)||(m.native.usdValue!=null?(x+=m.native.usdValue,$+=1):Z+=1);let An=en(p,"HYPE");for(let m of k.spot?.balances||[]){let g=String(m.coin||"").toUpperCase(),S=g==="USDC"||g==="USDT"||g==="USDT0"?1:g==="HYPE"?An.priceUsd||re(k.mids?.HYPE):re(k.mids?.[m.coin]),E=re(m.total);m.priceUsd=S,m.usdValue=E!=null&&S!=null?De(E*S):null,X(m.total)&&(m.usdValue!=null?(x+=m.usdValue,$+=1):Z+=1)}let ye=re(k.perps?.accountValueUsd);ye!=null&&ye!==0&&(x+=ye,$+=1);let xn=[...v.fungibleTokens?.assets||[],...v.collectibles?.assets||[]].filter(m=>X(m.amount)).length,En=(_.fungibleTokens?.assets||[]).length+(_.collectibles?.assets||[]).length;Z+=xn+En;let ge=[...y,v,_,k],j=m=>ge.filter(g=>g.status===m).length,ee=[];y.some(m=>m.fungibleTokens?.status==="unavailable")&&ee.push("EVM token and NFT discovery is unavailable without a configured address indexer; native balances are still live."),(v.fungibleTokens?.assets?.length||v.collectibles?.assets?.length)&&ee.push("Solana token accounts are unverified and may include spam; collectible candidates are not confirmed NFTs."),_.collectibles?.unknownNotEmpty&&ee.push("Bitcoin inscription holdings are unknown, not zero, because no address indexer is configured."),q.ok||ee.push(`Price provider unavailable: ${q.error}`);let we=[Me("cosmos","requires a chain-specific bech32 address and LCD/RPC adapter"),Me("sui","Sui balance adapter is not installed"),Me("aptos","Aptos balance adapter is not installed")],_n=ge.some(m=>["unavailable","partial","not-configured"].includes(m.fungibleTokens?.status)||["unavailable","partial","not-configured"].includes(m.collectibles?.status));return{provider:"portfolio",operation:"balances",readOnly:!0,queriedAt:r,addresses:n,coverage:{requestedSurfaces:ge.length,ok:j("ok"),unavailable:j("unavailable"),notConfigured:j("not-configured"),unsupported:j("unsupported")+we.length,evmChainsRequested:c.length,evmChainsOk:y.filter(m=>m.status==="ok").length},valuation:{knownUsd:De(x),label:"known priced value, not a complete portfolio total",pricedItems:$,unpricedNonzeroItems:Z,complete:Z===0&&!_n&&j("unavailable")===0&&j("not-configured")===0&&we.length===0,priceSource:o?"DefiLlama":null,priceStatus:q.ok?"ok":"unavailable",priceQueriedAt:r},chains:[...y,v,_,k],unsupportedFamilies:we,warnings:ee}}import{readFileSync as no,existsSync as ro}from"node:fs";import{getAddress as oo}from"ethers";var Ia=300*1e3,ka=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();var so="https://api.opensea.io/api/v2",ao=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"]),io=new Set(ao),co=new Set(["solana","flow"]);function lo(){let e=process.env.OPENSEA_ENV_FILE||`${process.env.HOME||""}/.config/locals-only/opensea.env`;if(!ro(e))return"";try{for(let t of no(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 He(e={}){return e.apiKey||process.env.OPENSEA_API_KEY||process.env.OPEN_SEA_API_KEY||lo()}function on(e={}){return Y({provider:"opensea",defaultUrl:so,hosts:["api.opensea.io","testnets-api.opensea.io"],url:e.baseUrl||process.env.OPENSEA_API_URL})}function sn(e={}){return on(e).baseUrl}function an(e={}){return K({accept:"application/json"},{"x-api-key":He(e)},on(e).trusted)}function uo(e){let t=String(e||"ethereum").trim().toLowerCase();if(!io.has(t))throw new Error(`opensea: unsupported account chain ${t}`);return t}function nn(e,t="address"){try{return oo(String(e||"").trim().toLowerCase())}catch{throw new Error(`opensea: invalid ${t}`)}}function cn(e,t=null){let r=String(e||"").trim();if(!r)throw new Error("opensea: account address required");if(t&&!co.has(t)||!t&&/^0x[0-9a-fA-F]{40}$/.test(r))return nn(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 po(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,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||e.is_nsfw===!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"}}}async function Ve(e={},t={}){if(!He(t))throw new Error("OPENSEA_API_KEY required");let r=uo(e.chain),n=cn(e.address||e.owner,r),o=Math.min(Math.max(Number(e.pageSize??e.limit??200)||200,1),200),s=Math.min(Math.max(Number(e.maxPages??5)||5,1),25),a=[],i=e.next?String(e.next):null,c=0;do{let l=new URL(`${sn(t)}/chain/${encodeURIComponent(r)}/account/${encodeURIComponent(n)}/nfts`);l.searchParams.set("limit",String(o)),e.collection&&l.searchParams.set("collection",String(e.collection)),i&&l.searchParams.set("next",i);let f=await N(l.toString(),{headers:an(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});for(let d of Array.isArray(f?.nfts)?f.nfts:[])a.push(po(d,r,n));i=f?.next?String(f.next):null,c+=1}while(i&&c<s);return{provider:"opensea-nft",source:"opensea-account-inventory",chain:r,owner:n,count:a.length,pages:c,complete:!i,next:i,nfts:a,exec:!1,readOnly:!0}}async function ln(e={},t={}){if(!He(t))throw new Error("OPENSEA_API_KEY required");let r=cn(e.address||e.owner),n=await N(`${sn(t)}/account/${encodeURIComponent(r)}/pnl`,{headers:an(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}}var mo="https://api.satflow.com/v1";function un(e={}){return Y({provider:"satflow",defaultUrl:mo,hosts:["api.satflow.com"],url:e.baseUrl||process.env.SATFLOW_API_URL})}function ho(e={}){return un(e).baseUrl}function dn(e={}){return String(e.apiKey||process.env.SATFLOW_API_KEY||process.env.BTC_SATFLOW_API_KEY||"").trim()}function bo(e={}){return K({accept:"application/json","content-type":"application/json","user-agent":"oracle-btc-satflow/0.1"},{"x-api-key":dn(e)},un(e).trusted)}async function yo(e,{method:t="GET",body:r,opts:n={}}={}){if(!dn(n))throw new Error("satflow: SATFLOW_API_KEY not set (request key via Satflow docs form)");let s=`${ho(n)}${e.startsWith("/")?e:`/${e}`}`,i=await(n.fetchImpl||fetch)(s,{method:t,headers:bo(n),body:r!=null?JSON.stringify(r):void 0,signal:AbortSignal.timeout(n.timeoutMs??2e4)}),c=await i.text(),l;try{l=JSON.parse(c)}catch{l=c}if(!i.ok)throw new Error(`satflow ${t} ${e}: HTTP ${i.status} ${String(c).slice(0,200)}`);return l}async function pn(e={},t={}){let r=V(e.address||e.addr,"address"),n=new URLSearchParams({address:r});e.type&&n.set("type",e.type),e.limit!=null&&n.set("limit",String(e.limit)),e.offset!=null&&n.set("offset",String(e.offset));let o=await yo(`/address/wallet-contents?${n}`,{opts:t});return{provider:"satflow",address:r,contents:o}}var Ga=Object.freeze(["i.seadn.io","openseauserdata.com","arweave.net","ipfs.io","nftstorage.link","dweb.link","cloudflare-ipfs.com","ordinals.com","ordinals.g.com","cdn.helius-rpc.com","shdw-drive.genesysgo.net"]);var go=Object.freeze([{chain:"ethereum",chainId:1,family:"evm"},{chain:"optimism",chainId:10,family:"evm"},{chain:"polygon",chainId:137,family:"evm"},{chain:"stablechain",chainId:988,family:"evm"},{chain:"hyperevm",chainId:999,family:"evm"},{chain:"abstract",chainId:2741,family:"evm"},{chain:"robinhood",chainId:4663,family:"evm"},{chain:"base",chainId:8453,family:"evm"},{chain:"arbitrum",chainId:42161,family:"evm"},{chain:"avalanche",chainId:43114,family:"evm"},{chain:"hyperliquid",chainId:null,family:"hyperliquid"}]),wo=Object.freeze([{family:"evm",chain:"bsc",chainId:56,reason:"OpenSea account inventory does not support BSC"},{family:"cosmos",reason:"requires a chain-specific bech32 address and NFT indexer"},{family:"sui",reason:"owner inventory adapter not installed"},{family:"aptos",reason:"owner inventory adapter not installed"}]);function ze(e={},t){return{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,...e[t]||{}}}async function oe(e,t){let r=await I(t);return r.ok?{ok:!0,data:r.data}:{ok:!1,error:`${e}: ${r.error}`.slice(0,300)}}function So(e){if(Array.isArray(e))return e;for(let t of["items","results","ordinals","inscriptions","data"])if(Array.isArray(e?.[t]))return e[t];return[]}function vo(e={},t){let r=e.inscription_id||e.inscriptionId||e.id||e.inscription||null;return{chain:"bitcoin",family:"bitcoin",owner:t,contract:null,tokenId:r==null?null:String(r),tokenStandard:"ordinal",collection:e.collection_slug||e.collectionSlug||e.collection?.slug||e.collection||null,name:e.name||e.meta?.name||(r?`Inscription ${r}`:"Bitcoin inscription"),description:e.description||e.meta?.description||null,imageUrl:e.image_url||e.imageUrl||e.content_url||e.contentUrl||e.thumbnail||null,originalImageUrl:e.content_url||e.contentUrl||e.image_url||e.imageUrl||null,animationUrl:null,metadataUrl:e.metadata_url||e.metadataUrl||null,marketplaceUrl:e.marketplace_url||e.marketplaceUrl||null,estimatedValueUsd:e.estimated_value_usd!=null&&Number.isFinite(Number(e.estimated_value_usd))?Number(e.estimated_value_usd):null,estimatedValueSats:(e.floor_price_sats??e.price_sats)!=null&&Number.isFinite(Number(e.floor_price_sats??e.price_sats))?Number(e.floor_price_sats??e.price_sats):null,spam:!1,disabled:!1,nsfw:!1,listed:e.listed===!0||e.is_listed===!0,listingId:e.listing_id||e.listingId||null,traits:Array.isArray(e.traits)?e.traits:[],updatedAt:e.updated_at||e.updatedAt||null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"Satflow wallet inventory does not expose trustworthy acquisition cost"},listingAdapter:"satflow",source:"satflow-wallet-contents"}}function Ao(e,t){return{chain:"bitcoin",family:"bitcoin",owner:t,contract:null,tokenId:String(e),tokenStandard:"ordinal",collection:null,name:`Inscription ${e}`,description:null,imageUrl:null,originalImageUrl:null,animationUrl:null,metadataUrl:null,marketplaceUrl:null,estimatedValueUsd:null,spam:!1,disabled:!1,nsfw:!1,traits:[],updatedAt:null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"address indexer returned no acquisition or valuation data"},listingAdapter:"satflow",source:"bitcoin-meta-address-indexer"}}function fn(e={}){return[e.chain||"unknown",e.contract||"native",e.tokenId||"unknown"].join(":").toLowerCase()}function xo(e){let t=new Map;if(Array.isArray(e)){for(let r of e)r?.assetKey&&t.set(String(r.assetKey).toLowerCase(),r);return t}if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))t.set(r.toLowerCase(),n);return t}function Eo(e,t){let r=fn(e),n=t.get(r),o=e.estimatedValueUsd==null?null:Number(e.estimatedValueUsd);if(!n)return{...e,assetKey:r};let s=Number(n.costUsd),a=Number(n.feesUsd??0);if(!Number.isFinite(s)||s<0||!Number.isFinite(a)||a<0)return{...e,assetKey:r,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"invalid user-supplied cost basis"}};let i=Math.round((s+a)*100)/100;return Number.isFinite(o)?{...e,assetKey:r,acquisitionCost:{costUsd:s,feesUsd:a,totalCostUsd:i,acquiredAt:n.acquiredAt||null,source:n.source||"user-supplied"},itemPnl:{status:"estimated",methodology:"provider estimated current value minus supplied USD acquisition cost and fees",unrealizedUsd:Math.round((o-i)*100)/100,currentValueUsd:o,totalCostUsd:i,realizedUsd:null}}:{...e,assetKey:r,acquisitionCost:{costUsd:s,feesUsd:a,totalCostUsd:i,acquiredAt:n.acquiredAt||null,source:n.source||"user-supplied"},itemPnl:{status:"unavailable",reason:"current NFT valuation is unavailable"}}}function _o(e){let t=new Map;for(let r of e){let n=fn(r);t.has(n)||t.set(n,r)}return[...t.values()]}function Io(e,t){let r=e.filter(s=>s.itemPnl?.status==="estimated"),n=e.length-r.length,o=Math.round(r.reduce((s,a)=>s+Number(a.itemPnl.unrealizedUsd||0),0)*100)/100;return{nftItemPnl:{status:n===0&&e.length?"estimated-complete-for-held-items":r.length?"partial":"unavailable",methodology:"Only items with explicit acquisition cost and provider estimated current value are included",knownUnrealizedUsd:o,knownItems:r.length,unknownItems:n,realizedUsd:null,warning:"Transfers, gifts, airdrops, mints, bridges, gas, royalties, and off-market sales can make cost basis unavailable or incomplete."},providerAccountPnl:t}}async function mn(e={},t={}){let r=new Date().toISOString(),n=Fe(e,t.env||process.env),o=Array.isArray(e.chains)&&e.chains.length?new Set(e.chains.map(p=>String(p).toLowerCase())):null,s=go.filter(p=>!o||o.has(p.chain)),a=[],i=[],c=ze(t,"opensea"),l=n.evm?s.filter(p=>p.family!=="solana"):[],f=await H(l,4,async p=>({row:p,result:await oe(`opensea-${p.chain}`,()=>Ve({chain:p.chain,address:n.evm,pageSize:e.pageSize,maxPages:e.maxPages},c),t.timeoutMs??35e3)}));for(let{row:p,result:y}of f)if(y.ok){let x=y.data.nfts.map($=>({...$,family:p.family,chainId:p.chainId,listingAdapter:"opensea",source:"opensea-account-inventory"}));i.push(...x),a.push({family:p.family,chain:p.chain,chainId:p.chainId,status:y.data.complete?"ok":"partial",count:x.length,complete:y.data.complete,next:y.data.next,source:"opensea"})}else a.push({family:p.family,chain:p.chain,chainId:p.chainId,status:"unavailable",error:y.error,source:"opensea"});if(!n.evm)for(let p of s.filter(y=>y.family!=="solana"))a.push({family:p.family,chain:p.chain,chainId:p.chainId,status:"not-configured",reason:"EVM address missing"});if(n.solana&&(!o||o.has("solana"))){let p=await oe("opensea-solana",()=>Ve({chain:"solana",address:n.solana,pageSize:e.pageSize,maxPages:e.maxPages},c),t.timeoutMs??35e3);if(p.ok){let y=p.data.nfts.map(x=>({...x,family:"solana",chainId:null,listingAdapter:null,source:"opensea-account-inventory"}));i.push(...y),a.push({family:"solana",chain:"solana",status:p.data.complete?"ok":"partial",count:y.length,complete:p.data.complete,next:p.data.next,source:"opensea"})}else a.push({family:"solana",chain:"solana",status:"unavailable",error:p.error,source:"opensea"})}else(!o||o.has("solana"))&&a.push({family:"solana",chain:"solana",status:"not-configured",reason:"Solana address missing"});if(n.bitcoin&&(!o||o.has("bitcoin"))){let p=await oe("satflow-wallet-contents",()=>pn({address:n.bitcoin,type:"ordinals",limit:e.bitcoinLimit??100,offset:0},ze(t,"satflow")),t.timeoutMs??35e3);if(p.ok){let y=So(p.data.contents).map($=>vo($,n.bitcoin));i.push(...y);let x=y.length<Number(e.bitcoinLimit??100);a.push({family:"bitcoin",chain:"bitcoin",status:x?"ok":"partial",count:y.length,complete:x,source:"satflow"})}else{let y=await oe("bitcoin-meta-inscriptions",()=>ue({address:n.bitcoin},ze(t,"bitcoinMeta")),t.timeoutMs??35e3),x=y.ok&&y.data?.ok&&Array.isArray(y.data.inscriptions)?y.data.inscriptions:[];i.push(...x.map($=>Ao($,n.bitcoin))),a.push({family:"bitcoin",chain:"bitcoin",status:x.length?"partial":"unavailable",count:x.length,complete:!1,source:x.length?"bitcoin-meta":"satflow",error:x.length?"Satflow unavailable; fallback has IDs only":p.error})}}else(!o||o.has("bitcoin"))&&a.push({family:"bitcoin",chain:"bitcoin",status:"not-configured",reason:"Bitcoin address missing"});let d=[];if(e.includePnl!==!1)for(let p of[...new Set([n.evm,n.solana].filter(Boolean))]){let y=await oe(`opensea-pnl-${p}`,()=>ln({address:p},c),t.timeoutMs??35e3);d.push(y.ok?{status:"ok",...y.data}:{status:"unavailable",address:p,source:"opensea-indexed-account-pnl",error:y.error})}let h=xo(e.costBasis),u=_o(i).map(p=>Eo(p,h)),w=u.filter(p=>!p.spam),A=u.filter(p=>p.spam),v=w.filter(p=>p.estimatedValueUsd!=null&&Number.isFinite(Number(p.estimatedValueUsd))),_=Math.round(v.reduce((p,y)=>p+Number(y.estimatedValueUsd),0)*100)/100,k=w.length-v.length,q=a.filter(p=>p.status!=="ok"||p.complete===!1);return{provider:"nft-portfolio",operation:"inventory",readOnly:!0,generatedAt:r,addresses:n,coverage:a,unsupported:wo,inventory:{count:u.length,visibleCount:w.length,flaggedCount:A.length,items:u,visibleItems:w,flaggedItems:A},valuation:{estimatedCurrentValueUsd:_,valuedItems:v.length,unvaluedItems:k,complete:k===0&&q.length===0,methodology:"Sum of provider estimated_value_usd for non-flagged items. It is not an executable bid."},pnl:Io(w,d),listingCoverage:{opensea:"EVM listing actions available with OPENSEA_API_KEY, explicit price/currency/expiry, and user confirmation",satflow:"Bitcoin unsigned listing PSBT available with SATFLOW_API_KEY, explicit price/expiry, and user confirmation",solana:"Magic Eden unsigned list transaction available with MAGICEDEN_API_KEY, explicit SOL price/expiry, and user confirmation",unsupported:"Sui, Aptos, Cosmos, BSC, and unknown marketplaces fail closed"},metadataSafety:{imagesAreUntrusted:!0,animationAndHtmlNotRendered:!0,galleryRasterOnly:!0,missingImagesUsePlaceholders:!0}}}import{homedir as Ke}from"node:os";import{join as je}from"node:path";var hn=process.env.ORACLE_PUBLIC_DESKTOP==="1",ko=hn?process.env.ORACLE_CONFIG_DIR||je(Ke(),".config","oracle"):je(Ke(),".config","oracle"),ui=hn?ko:je(Ke(),".config","mad-desk");function We(e,t,r=""){let n=process.env[e];if(n!=null&&String(n).trim()!=="")return n;let o=t?process.env[t]:void 0;return o!=null&&String(o).trim()!==""?o:r}var Lo=JSON.parse(wn(new URL("../../package.json",import.meta.url),"utf8")),Q="public",$o="127.0.0.1",Uo=8799,me=Lo.version,Bo=new Set(["127.0.0.1","localhost","::1"]),Mo=Ye(To(Oo(import.meta.url)),"../.."),Ge=Ye(Mo,"public","oracle-console"),bn=Object.freeze({"/":{file:"index.html",type:"text/html; charset=utf-8"},"/index.html":{file:"index.html",type:"text/html; charset=utf-8"},"/app.js":{file:"app.js",type:"application/javascript; charset=utf-8"},"/styles.css":{file:"styles.css",type:"text/css; charset=utf-8"},"/oracle-console":{file:"index.html",type:"text/html; charset=utf-8"},"/oracle-console/":{file:"index.html",type:"text/html; charset=utf-8"},"/oracle-console/index.html":{file:"index.html",type:"text/html; charset=utf-8"},"/oracle-console/app.js":{file:"app.js",type:"application/javascript; charset=utf-8"},"/oracle-console/styles.css":{file:"styles.css",type:"text/css; charset=utf-8"}}),qo=1e6,T=class extends Error{constructor(t,r,n){super(n||r),this.status=t,this.code=r}};function D(e,t,r){let n=t,o;try{R(r),o=ft(r)}catch{n=500,o=JSON.stringify({error:"secret-leak-blocked"})}e.writeHead(n,{"content-type":"application/json; charset=utf-8","cache-control":"no-store","x-oracle-plane":Q,"x-oracle-unsigned":"true"}),e.end(o)}function Do(e){return new Promise((t,r)=>{let n=[],o=0;e.on("data",s=>{if(o+=s.length,o>qo){r(new T(413,"payload-too-large","request body too large")),e.destroy();return}n.push(s)}),e.on("end",()=>{let s=Buffer.concat(n).toString("utf8").trim();if(s==="")return t({});try{t(JSON.parse(s))}catch{r(new T(400,"invalid-json","request body must be valid JSON"))}}),e.on("error",()=>r(new T(400,"bad-request","request stream error")))})}function C(e,t){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))throw new T(400,t,`${t} must be a JSON object`);return e}function Fo(e){return String(e||"").trim().toLowerCase().replace(/^\[|\]$/g,"")}function Ho(e){let t=Fo(e);if(!Bo.has(t))throw new TypeError(`oracle-public only binds loopback hosts; got ${String(e)}`);return t==="::1"?"::1":String(e).trim()}function Vo(){return{status:200,body:{ok:!0,plane:Q,version:me}}}function he(e){return{...e,allowWildcardActions:!1,now:Math.floor(Date.now()/1e3)}}function zo(e){let t=C(e,"body"),r=t.input!==void 0?C(t.input,"input"):t,n=he(C(t.opts,"opts")),o=r===t?(({opts:s,...a})=>a)(t):r;return{status:200,body:bt(o,n)}}function Ko(e){let t=C(e,"body"),r=t.request!==void 0?C(t.request,"request"):t.input!==void 0?C(t.input,"input"):t,n=he(C(t.opts,"opts")),o=r===t?(({opts:s,...a})=>a)(t):r;return{status:200,body:yt(o,n)}}function jo(e){let t=C(e,"body"),r=he(C(t.opts,"opts")),n=St(t.store??[],r);return{status:200,body:{ok:!0,count:n.length,grants:n}}}function Wo(e){let t=C(e,"body"),r=he(C(t.opts,"opts")),n=vt(t.store??[],t.id,r);return n==null?{status:404,body:{error:"grant-not-found"}}:{status:200,body:n}}function Go(){let e=(process.env.ORACLE_PRIVY_APP_ID||process.env.PRIVY_APP_ID||"").trim(),t=e.length>0,r=!0,n=[];return t&&n.push("privy"),r&&n.push("injected"),{status:200,body:{ok:!0,plane:Q,version:me,custody:{selfCustodial:!0,signer:"user-wallet",privyEnabled:t,injectedEnabled:r,modes:n},privy:{appId:e||null}}}}var fe=12;async function Yo(e){let t=C(e,"body"),r=typeof t.owner=="string"?t.owner:null;if(!r)throw new T(400,"owner-required","owner must be an EVM address");let n=Array.isArray(t.chainIds)?t.chainIds.map(Number).filter(Number.isFinite):void 0;if(n&&n.length>fe)throw new T(400,"too-many-chains",`at most ${fe} chainIds per request`);let s=await Mt({owner:r,chainIds:n},{});return{status:200,body:{ok:!0,owner:s.owner,scannedRange:s.scannedRange,approvals:s.approvals,scans:s.scans,warnings:s.warnings}}}var Jo=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/,Xo=/^([13][1-9A-HJ-NP-Za-km-z]{25,34}|bc1[ac-hj-np-z02-9]{11,71})$/i;function Qo(e){if(typeof e!="string")return null;let t=e.trim();return Jo.test(t)?t:null}function Zo(e){if(typeof e!="string")return null;let t=e.trim();return Xo.test(t)?t:null}function Sn(e){if(typeof e=="string")return e.trim()===""?null:e;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e.evm;if(typeof t=="string"&&t.trim()!=="")return t}return null}async function es(e){let t=C(e,"body"),r=Sn(t.owner),n=Qo(t.solana),o=Zo(t.bitcoin);if(!r&&!n&&!o)throw new T(400,"owner-required","owner must be an EVM address (or pass solana/bitcoin)");let s=Array.isArray(t.chainIds)?t.chainIds.map(Number).filter(Number.isFinite):void 0;if(s&&s.length>fe)throw new T(400,"too-many-chains",`at most ${fe} chainIds per request`);let a=await tn({addresses:{evm:r,solana:n,bitcoin:o},evmChainIds:s,includePrices:!0,includeTokens:!0,includeCollectibles:!1},{env:{}}),i=[],c=[];for(let l of a.chains||[]){if(!["evm","solana","bitcoin"].includes(l.family))continue;c.push({chainId:l.chainId,family:l.family,name:l.name,status:l.status,error:l.error??null,tokenDiscovery:l.fungibleTokens?.status??"unavailable",tokenDiscoveryReason:l.fungibleTokens?.reason??null});let f=l.native;l.status!=="ok"||!f||f.status!=="ok"||!f.amountRaw||f.amountRaw==="0"||f.amountRaw==="0x0"||i.push({chainId:l.chainId,family:l.family,chain:l.name,symbol:f.symbol,decimals:f.decimals,amount:String(f.amountRaw),amountRaw:String(f.amountRaw),amountFormatted:f.amount,kind:"native"})}return{status:200,body:{ok:!0,owner:a.addresses?.evm??r,queriedAt:a.queriedAt,portfolio:{rows:i,chains:c,coverage:a.coverage,complete:!1,incompleteReason:"EVM JSON-RPC returns native balances only; token enumeration requires an address indexer"},warnings:a.warnings}}}async function ts(e){let t=C(e,"body"),r=Sn(t.owner);if(!r)throw new T(400,"owner-required","owner must be an EVM address");let n=await mn({addresses:{evm:r}},{env:{}});return{status:200,body:{ok:!0,owner:r,queriedAt:n.queriedAt??new Date().toISOString(),nfts:{items:Array.isArray(n.items)?n.items:[],chains:n.chains??[],coverage:{operational:n.ok!==!1,complete:n.complete===!0,hasGaps:n.complete!==!0}},warnings:n.warnings}}}var ns=6e4,rs=120,os=10,yn=Object.freeze(new Set(["/public/approvals","/public/portfolio","/public/nfts"])),ss=4096,se=new Map;function as(e){if(process.env.ORACLE_TRUST_PROXY==="1"){let t=e.headers["x-forwarded-for"];if(typeof t=="string"&&t.length>0){let r=t.split(",")[0].trim();if(r)return r.slice(0,64)}}return e.socket?.remoteAddress||"unknown"}function is(e,t){let r=yn.has(t)?os:rs,n=Date.now(),o=`${as(e)}:${yn.has(t)?"amp":"std"}`,s=se.get(o);if(!s||n>=s.resetAt){for(se.set(o,{count:1,resetAt:n+ns});se.size>ss;){let a=se.keys().next();if(a.done)break;se.delete(a.value)}return{allowed:!0,limit:r,remaining:r-1,retryAfterSec:0}}return s.count+=1,s.count>r?{allowed:!1,limit:r,remaining:0,retryAfterSec:Math.max(1,Math.ceil((s.resetAt-n)/1e3))}:{allowed:!0,limit:r,remaining:r-s.count,retryAfterSec:0}}var gn=Object.freeze({"GET /public/health":Vo,"GET /public/config":Go,"POST /public/connect/request":zo,"POST /public/connect/assemble":Ko,"POST /public/grants/active":jo,"POST /public/grants/get":Wo,"POST /public/approvals":Yo,"POST /public/portfolio":es,"POST /public/nfts":ts});function Je(e={}){return{"cache-control":"no-store","x-oracle-plane":Q,"x-oracle-unsigned":"true",...e}}function cs(e,t,r,n){e.writeHead(t,Je({"content-type":r})),e.end(n)}function ls(e,t,r){if(e.method!=="GET"&&e.method!=="HEAD")return!1;let n=r===""?"/":r,o=bn[n]||bn[n.replace(/\/+$/,"")||"/"];if(!o)return!1;let s=Po(Ye(Ge,o.file));if(!s.startsWith(Ge+Ro)&&s!==Ge)return D(t,404,{error:"not-found",message:"unknown static path"}),!0;if(!Co(s))return D(t,404,{error:"not-found",message:`missing static file ${o.file}`}),!0;let a=wn(s);return e.method==="HEAD"?(t.writeHead(200,Je({"content-type":o.type,"content-length":String(a.length)})),t.end(),!0):(cs(t,200,o.type,a),!0)}async function us(e,t){let n=new URL(e.url,"http://localhost").pathname||"/";n.length>1&&n.endsWith("/")&&n!=="/oracle-console/"&&(n=n.replace(/\/+$/,"")),n===""&&(n="/");let o=n.replace(/\/+$/,"")||"/",s=`${e.method} ${o}`,a=gn[s];try{if(!a){if(ls(e,t,n))return;throw Object.keys(gn).some(d=>d.endsWith(` ${o}`))?new T(405,"method-not-allowed",`unsupported method for ${o}`):new T(404,"not-found",`unknown route ${o}`)}let i=is(e,o);if(!i.allowed){t.writeHead(429,Je({"content-type":"application/json","retry-after":String(i.retryAfterSec),"x-ratelimit-limit":String(i.limit),"x-ratelimit-remaining":"0"})),t.end(JSON.stringify({error:"rate-limited",message:`too many requests for ${o}; retry in ${i.retryAfterSec}s`}));return}let c=e.method==="GET"||e.method==="HEAD"?void 0:await Do(e),l=await a(c);D(t,l.status,l.body)}catch(i){if(i instanceof L){D(t,500,{error:"secret-leak-blocked"});return}if(i instanceof B){D(t,400,{error:"invalid-grant",errors:i.errors.map(c=>({field:c.field,message:c.message}))});return}if(i instanceof T){D(t,i.status,{error:i.code,message:i.message});return}if(i instanceof TypeError){D(t,400,{error:"bad-request",message:i.message});return}D(t,500,{error:"internal-error"})}}function ds(){return No((e,t)=>{us(e,t).catch(()=>{try{D(t,500,{error:"internal-error"})}catch{}})})}function Xe({host:e,port:t}={}){let r=Ho(e??We("ORACLE_PUBLIC_HOST","MAD_PUBLIC_HOST",$o)),n=t??We("ORACLE_PUBLIC_PORT","MAD_PUBLIC_PORT",String(Uo)),o=Number(n);if(!Number.isInteger(o)||o<0||o>65535)throw new TypeError(`invalid public port: ${String(n)}`);return{host:r,port:o}}function vn(e={}){let{host:t,port:r}=Xe(e),n=ds();return n.listen(r,t),n}var Qe=Xe(),be=vn(Qe);be.on("listening",()=>{let e=be.address(),t=typeof e=="object"&&e?e.address:Qe.host,r=typeof e=="object"&&e?e.port:Qe.port;console.log(`oracle-public-server listening on http://${t}:${r} (plane=${Q}, version=${me}, unsigned-only)`)});be.on("error",e=>{console.error(`oracle-public-server failed to bind: ${e.code||e.message}`),process.exit(1)});for(let e of["SIGINT","SIGTERM"])process.on(e,()=>{be.close(()=>process.exit(0)),setTimeout(()=>process.exit(0),1e3).unref()});