@dodoex/wallet-web3 0.6.4 → 0.6.5

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 (215) hide show
  1. package/dist/PhArrowCircleDown-4a08ae8e.js +14 -0
  2. package/dist/PhArrowClockwise-401ea1c0.js +14 -0
  3. package/dist/PhArrowDown-789ae7d2.js +14 -0
  4. package/dist/PhArrowLeft-2e6d4940.js +14 -0
  5. package/dist/PhArrowRight-2928b0dc.js +14 -0
  6. package/dist/PhArrowSquareOut-17d61d08.js +14 -0
  7. package/dist/PhArrowUp-1cfcf9df.js +14 -0
  8. package/dist/PhArrowUpRight-552c41cb.js +14 -0
  9. package/dist/PhArrowsClockwise-92a70162.js +14 -0
  10. package/dist/PhArrowsDownUp-ce27c8a7.js +14 -0
  11. package/dist/PhArrowsLeftRight-ed549dc7.js +14 -0
  12. package/dist/PhBank-92a1a1df.js +14 -0
  13. package/dist/PhBrowser-495dc3ce.js +14 -0
  14. package/dist/PhCaretDown-610f20fc.js +14 -0
  15. package/dist/PhCaretLeft-2a86ee53.js +14 -0
  16. package/dist/PhCaretRight-f3057f58.js +14 -0
  17. package/dist/PhCaretUp-7b74b8cb.js +14 -0
  18. package/dist/PhCheck-c514f32c.js +14 -0
  19. package/dist/PhCircleHalf-3bfd24c9.js +14 -0
  20. package/dist/PhClock-29284ead.js +14 -0
  21. package/dist/PhCompass-101d3241.js +14 -0
  22. package/dist/PhCopy-d92dcd27.js +14 -0
  23. package/dist/PhCreditCard-d8d77fc2.js +14 -0
  24. package/dist/PhCurrencyDollar-6553df79.js +14 -0
  25. package/dist/PhDesktop-91653c8e.js +14 -0
  26. package/dist/PhDeviceMobile-0f3d8fa2.js +14 -0
  27. package/dist/PhDotsThree-67debca2.js +14 -0
  28. package/dist/PhEnvelope-f83faab2.js +14 -0
  29. package/dist/PhFunnelSimple-5058af43.js +14 -0
  30. package/dist/PhGlobe-c4653621.js +14 -0
  31. package/dist/PhIdentificationCard-848bf9a1.js +14 -0
  32. package/dist/PhImage-de71fc6b.js +14 -0
  33. package/dist/PhInfo-9614a766.js +14 -0
  34. package/dist/PhLightbulb-7d582ae7.js +14 -0
  35. package/dist/PhMagnifyingGlass-c926bd63.js +14 -0
  36. package/dist/PhPaperPlaneRight-76b25832.js +14 -0
  37. package/dist/PhPlus-767ddc55.js +14 -0
  38. package/dist/PhPower-95f188dd.js +14 -0
  39. package/dist/PhPuzzlePiece-f016afe5.js +14 -0
  40. package/dist/PhQrCode-e9b7ab93.js +14 -0
  41. package/dist/PhQuestion-ea0e639d.js +14 -0
  42. package/dist/PhQuestionMark-13d6338e.js +14 -0
  43. package/dist/PhSealCheck-45bb7b9c.js +14 -0
  44. package/dist/PhSignOut-6b91c59c.js +14 -0
  45. package/dist/PhSpinner-eb9b7ac1.js +14 -0
  46. package/dist/PhTrash-758cc3b3.js +14 -0
  47. package/dist/PhUser-0834861d.js +14 -0
  48. package/dist/PhVault-e4d6f9af.js +14 -0
  49. package/dist/PhWallet-5e257abe.js +14 -0
  50. package/dist/PhWarning-6af3740e.js +14 -0
  51. package/dist/PhWarningCircle-a78fd8e8.js +14 -0
  52. package/dist/PhX-60c46532.js +14 -0
  53. package/dist/{__tslib-83c7dd77.js → __tslib-6d6a586c.js} +1 -1
  54. package/dist/{alchemy-provider-5870b6fa-ef26112b.js → alchemy-provider-5870b6fa-a9fe5aa5.js} +1 -1
  55. package/dist/{alchemy-websocket-provider-213da986-2d698146.js → alchemy-websocket-provider-213da986-16164c2e.js} +1 -1
  56. package/dist/basic-77fe1b96.js +1320 -0
  57. package/dist/{blocto-05d7faf5.js → blocto-ab8ba330.js} +1 -1
  58. package/dist/{ccip-ea7099a8.js → ccip-e246f9cf.js} +1 -1
  59. package/dist/cjs/PhArrowCircleDown-df23d036.cjs +14 -0
  60. package/dist/cjs/PhArrowClockwise-440d23dc.cjs +14 -0
  61. package/dist/cjs/PhArrowDown-252590ed.cjs +14 -0
  62. package/dist/cjs/PhArrowLeft-d480faa4.cjs +14 -0
  63. package/dist/cjs/PhArrowRight-969dbdd8.cjs +14 -0
  64. package/dist/cjs/PhArrowSquareOut-eabfdecb.cjs +14 -0
  65. package/dist/cjs/PhArrowUp-66bd5f15.cjs +14 -0
  66. package/dist/cjs/PhArrowUpRight-6df3b31b.cjs +14 -0
  67. package/dist/cjs/PhArrowsClockwise-3a9d2dc6.cjs +14 -0
  68. package/dist/cjs/PhArrowsDownUp-47a7788f.cjs +14 -0
  69. package/dist/cjs/PhArrowsLeftRight-f90368dd.cjs +14 -0
  70. package/dist/cjs/PhBank-670a2708.cjs +14 -0
  71. package/dist/cjs/PhBrowser-b9c35fd1.cjs +14 -0
  72. package/dist/cjs/PhCaretDown-11a46455.cjs +14 -0
  73. package/dist/cjs/PhCaretLeft-04f11ca7.cjs +14 -0
  74. package/dist/cjs/PhCaretRight-391111c1.cjs +14 -0
  75. package/dist/cjs/PhCaretUp-b17dccf6.cjs +14 -0
  76. package/dist/cjs/PhCheck-08bf36b0.cjs +14 -0
  77. package/dist/cjs/PhCircleHalf-0a9eac35.cjs +14 -0
  78. package/dist/cjs/PhClock-cf1cc2cb.cjs +14 -0
  79. package/dist/cjs/PhCompass-e9671b30.cjs +14 -0
  80. package/dist/cjs/PhCopy-9132cbc5.cjs +14 -0
  81. package/dist/cjs/PhCreditCard-853e1556.cjs +14 -0
  82. package/dist/cjs/PhCurrencyDollar-34eea829.cjs +14 -0
  83. package/dist/cjs/PhDesktop-c02b883b.cjs +14 -0
  84. package/dist/cjs/PhDeviceMobile-93c2088c.cjs +14 -0
  85. package/dist/cjs/PhDotsThree-69beaba7.cjs +14 -0
  86. package/dist/cjs/PhEnvelope-86ee730e.cjs +14 -0
  87. package/dist/cjs/PhFunnelSimple-056c2f76.cjs +14 -0
  88. package/dist/cjs/PhGlobe-64c4ee8e.cjs +14 -0
  89. package/dist/cjs/PhIdentificationCard-ec7a98e0.cjs +14 -0
  90. package/dist/cjs/PhImage-07904cbb.cjs +14 -0
  91. package/dist/cjs/PhInfo-34eeeace.cjs +14 -0
  92. package/dist/cjs/PhLightbulb-39ebe854.cjs +14 -0
  93. package/dist/cjs/PhMagnifyingGlass-2fbe4400.cjs +14 -0
  94. package/dist/cjs/PhPaperPlaneRight-e06c210f.cjs +14 -0
  95. package/dist/cjs/PhPlus-03a04ed3.cjs +14 -0
  96. package/dist/cjs/PhPower-4cc2ecb8.cjs +14 -0
  97. package/dist/cjs/PhPuzzlePiece-035d561e.cjs +14 -0
  98. package/dist/cjs/PhQrCode-37e23b36.cjs +14 -0
  99. package/dist/cjs/PhQuestion-bfba435e.cjs +14 -0
  100. package/dist/cjs/PhQuestionMark-8ef38ecf.cjs +14 -0
  101. package/dist/cjs/PhSealCheck-5458de15.cjs +14 -0
  102. package/dist/cjs/PhSignOut-2d177ea1.cjs +14 -0
  103. package/dist/cjs/PhSpinner-e7c590df.cjs +14 -0
  104. package/dist/cjs/PhTrash-1920f5dc.cjs +14 -0
  105. package/dist/cjs/PhUser-84a1a685.cjs +14 -0
  106. package/dist/cjs/PhVault-1493c03f.cjs +14 -0
  107. package/dist/cjs/PhWallet-f0502f03.cjs +14 -0
  108. package/dist/cjs/PhWarning-1bf637ba.cjs +14 -0
  109. package/dist/cjs/PhWarningCircle-b1747661.cjs +14 -0
  110. package/dist/cjs/PhX-f864d86c.cjs +14 -0
  111. package/dist/cjs/{__tslib-12e41834.cjs → __tslib-a9f27ba6.cjs} +1 -1
  112. package/dist/cjs/{alchemy-provider-5870b6fa-683a7f2e.cjs → alchemy-provider-5870b6fa-bb1c607e.cjs} +1 -1
  113. package/dist/cjs/{alchemy-websocket-provider-213da986-5c9807c6.cjs → alchemy-websocket-provider-213da986-521569b5.cjs} +1 -1
  114. package/dist/cjs/basic-b777d2b1.cjs +1320 -0
  115. package/dist/cjs/{blocto-4db38a28.cjs → blocto-09e0d574.cjs} +1 -1
  116. package/dist/cjs/{ccip-82e883e4.cjs → ccip-6ebee1cf.cjs} +1 -1
  117. package/dist/cjs/core-78a709db.cjs +210 -0
  118. package/dist/cjs/{draggabilly-308ac2a9.cjs → draggabilly-76af6217.cjs} +1 -1
  119. package/dist/cjs/features-fa5c5622.cjs +1 -0
  120. package/dist/cjs/id-c0538166.cjs +1 -0
  121. package/dist/cjs/{index-2c097978.cjs → index-07e81389.cjs} +1 -1
  122. package/dist/cjs/{index-eae76bd0.cjs → index-093cef5a.cjs} +2 -2
  123. package/dist/cjs/{index-362be9fb.cjs → index-208df3f3.cjs} +1 -1
  124. package/dist/cjs/{index-c8fa7932.cjs → index-253e7cce.cjs} +1 -1
  125. package/dist/cjs/index-2e8e7a50.cjs +4 -0
  126. package/dist/cjs/index-395b933d.cjs +2 -0
  127. package/dist/cjs/{index-281d00df.cjs → index-54d7fc75.cjs} +1 -1
  128. package/dist/cjs/{index-3714da35.cjs → index-5d28acf4.cjs} +2 -2
  129. package/dist/cjs/{index-85a2526e.cjs → index-5dac528b.cjs} +7 -7
  130. package/dist/cjs/index-702e8f89.cjs +15 -0
  131. package/dist/cjs/{index-ceda42fb.cjs → index-823e17e6.cjs} +1 -1
  132. package/dist/cjs/{index-9325806f.cjs → index-916994aa.cjs} +1 -1
  133. package/dist/cjs/{index-00b0ab99.cjs → index-a2b665f4.cjs} +1 -1
  134. package/dist/cjs/{index-c6b53b3f.cjs → index-b099293c.cjs} +1 -1
  135. package/dist/cjs/index-d72ddbc1.cjs +17 -0
  136. package/dist/cjs/index-ef4ef0cc.cjs +1449 -0
  137. package/dist/cjs/index.cjs +1 -1
  138. package/dist/cjs/{interface-10b0ba33.cjs → interface-4947cfa6.cjs} +1 -1
  139. package/dist/cjs/{lib-typedarrays-012f607a.cjs → lib-typedarrays-a9baf142.cjs} +1 -1
  140. package/dist/cjs/native-55bb141d.cjs +1 -0
  141. package/dist/cjs/{portis-2144bb98.cjs → portis-08d9d731.cjs} +1 -1
  142. package/dist/cjs/property-29e6f732.cjs +29 -0
  143. package/dist/cjs/providers/connector/safeGnosis/query.d.ts +2 -1
  144. package/dist/cjs/providers/connector/types.d.ts +1 -1
  145. package/dist/cjs/providers/wallets/index.d.ts +1 -0
  146. package/dist/cjs/rainbow-6e84bcfa.cjs +1 -0
  147. package/dist/cjs/sha224-b46bc3e6.cjs +1 -0
  148. package/dist/cjs/sha256-ccd47519.cjs +1 -0
  149. package/dist/cjs/{typed-data-e878587d.cjs → typed-data-5176b792.cjs} +1 -1
  150. package/dist/cjs/uAuth-b29d2670.cjs +1 -0
  151. package/dist/cjs/w3m-modal-70bcf6d8.cjs +2380 -0
  152. package/dist/cjs/walletConnect-20d477a9.cjs +1 -0
  153. package/dist/cjs/{walletLink-8e49b6d5.cjs → walletLink-08b8da20.cjs} +2 -2
  154. package/dist/core-4d7ad6f2.js +210 -0
  155. package/dist/{draggabilly-c6f65920.js → draggabilly-daf3b444.js} +1 -1
  156. package/dist/features-d8d1c9ce.js +1 -0
  157. package/dist/id-d4d22b29.js +1 -0
  158. package/dist/{index-227927b5.js → index-09298bd0.js} +7 -7
  159. package/dist/{index-f360d801.js → index-244a8189.js} +1 -1
  160. package/dist/{index-f4727f94.js → index-2ad0fb2a.js} +1 -1
  161. package/dist/index-35d87b79.js +17 -0
  162. package/dist/{index-eb473b84.js → index-587ff998.js} +1 -1
  163. package/dist/{index-a6b10e09.js → index-750a7dfe.js} +1 -1
  164. package/dist/{index-abb4eaf1.js → index-8bd12de1.js} +1 -1
  165. package/dist/{index-1e0435b6.js → index-938686fb.js} +1 -1
  166. package/dist/{index-1db47472.js → index-9d7fee1e.js} +2 -2
  167. package/dist/{index-af823ebd.js → index-aa744ca0.js} +1 -1
  168. package/dist/{index-cfa6ef57.js → index-b7d25e8a.js} +2 -2
  169. package/dist/index-bb1a0019.js +15 -0
  170. package/dist/index-c5ca8a4e.js +4 -0
  171. package/dist/{index-1cf97dd7.js → index-cddbc8e8.js} +1 -1
  172. package/dist/index-f095c09e.js +2 -0
  173. package/dist/index-ffdf981b.js +1449 -0
  174. package/dist/index.js +1 -1
  175. package/dist/{interface-ec064b7d.js → interface-0c535796.js} +1 -1
  176. package/dist/{lib-typedarrays-ecebfb2c.js → lib-typedarrays-979d2723.js} +1 -1
  177. package/dist/native-029c50f7.js +1 -0
  178. package/dist/{portis-e3d3d420.js → portis-9602ac9f.js} +1 -1
  179. package/dist/property-8eb37909.js +35 -0
  180. package/dist/providers/connector/safeGnosis/query.d.ts +2 -1
  181. package/dist/providers/connector/types.d.ts +1 -1
  182. package/dist/providers/wallets/index.d.ts +1 -0
  183. package/dist/rainbow-ccab7a95.js +1 -0
  184. package/dist/sha224-fe98e1bf.js +1 -0
  185. package/dist/sha256-5a24dfd5.js +1 -0
  186. package/dist/{typed-data-0f706378.js → typed-data-3a3d44dc.js} +1 -1
  187. package/dist/uAuth-27f5728d.js +1 -0
  188. package/dist/w3m-modal-49add722.js +2380 -0
  189. package/dist/walletConnect-a541881e.js +1 -0
  190. package/dist/{walletLink-68441960.js → walletLink-67264328.js} +2 -2
  191. package/package.json +3 -3
  192. package/dist/_commonjs-dynamic-modules-7cfc9805.js +0 -1
  193. package/dist/cjs/_commonjs-dynamic-modules-f09a98c7.cjs +0 -1
  194. package/dist/cjs/id-ea22b6ce.cjs +0 -1
  195. package/dist/cjs/index-35edc6a0.cjs +0 -60
  196. package/dist/cjs/index-8a25465c.cjs +0 -6
  197. package/dist/cjs/index-9f2a69d5.cjs +0 -1
  198. package/dist/cjs/index-fdda1836.cjs +0 -17
  199. package/dist/cjs/index.es-80622213.cjs +0 -9
  200. package/dist/cjs/rainbow-18d05876.cjs +0 -1
  201. package/dist/cjs/sha224-1c092a15.cjs +0 -1
  202. package/dist/cjs/sha256-9e1680c1.cjs +0 -1
  203. package/dist/cjs/uAuth-b89f7081.cjs +0 -1
  204. package/dist/cjs/walletConnect-b79e1e97.cjs +0 -1
  205. package/dist/id-397f0303.js +0 -1
  206. package/dist/index-02e42cd2.js +0 -17
  207. package/dist/index-65d96278.js +0 -60
  208. package/dist/index-89717995.js +0 -6
  209. package/dist/index-f08d6a6b.js +0 -1
  210. package/dist/index.es-7adbb6c0.js +0 -9
  211. package/dist/rainbow-73b82cd7.js +0 -1
  212. package/dist/sha224-51e5e6a9.js +0 -1
  213. package/dist/sha256-549e482b.js +0 -1
  214. package/dist/uAuth-ce19d386.js +0 -1
  215. package/dist/walletConnect-b0b635de.js +0 -1
@@ -0,0 +1,210 @@
1
+ import e,{EventEmitter as t}from"events";import{c as s,I as n,s as r,a as i,g as o,f as a,t as c,b as l,d,e as h,h as u,i as p,r as f,j as g,k as m,l as y,m as w,n as b,o as v,p as E,q as C,u as N,v as A,w as I,x as S,y as _,z as O,A as T,B as k,C as P,D as x,E as R}from"./index-c5ca8a4e.js";import{r as U}from"./__tslib-6d6a586c.js";import{c as L,O as D}from"./index-09298bd0.js";const M={isLowerCaseMatch:(e,t)=>e?.toLowerCase()===t?.toLowerCase()},B={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",BASE_ACCOUNT:"baseAccount",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122",TON:"ton",TRON:"tron"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks",ton:"TON",tron:"TRON"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",TON:"ton",TRON:"tron"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},NATIVE_IMAGE_IDS_BY_NAMESPACE:{eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"3e8119e5-2a6f-4818-c50c-1937011d5900",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},TOKEN_SYMBOLS_BY_ADDRESS:{"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC","0x833589fcd6edb6e08f4c7c32d4f71b54bda02913":"USDC","0x0b2c639c533813f4aa9d7837caf62653d097ff85":"USDC","0xaf88d065e77c8cc2239327c5edb3a432268e5831":"USDC","0x3c499c542cef5e3811e1192ce70d8cc03d5c3359":"USDC","0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"USDC",EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:"USDC","0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT","0x94b008aa00579c1307b0ef2c499ad98a8ce58e58":"USDT","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9":"USDT","0xc2132d05d31c914a87c6611c10748aeb04b58e8f":"USDT",Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:"USDT"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:("undefined"!=typeof process&&void 0!==process.env?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}},HEADLESS_NOT_ENABLED:{DEFAULT:{displayMessage:"",debugMessage:"Headless support is not enabled. Please enable it with the features.headless option in the AppKit configuration and make sure your current plan supports it."}}},IS_DEVELOPMENT:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"],METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH"},j={caipNetworkIdToNumber:e=>e?Number(e.split(":")[1]):void 0,parseEvmChainId(e){return"string"==typeof e?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace:(e,t)=>e?.filter((e=>e.chainNamespace===t))||[],getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){if(!t)return;const s=e.find((e=>e.caipNetworkId===t));if(s)return s.name;const[n]=t.split(":");return B.CHAIN_NAME_MAP?.[n]||void 0}},$=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var F=1e6,q=1e6,W="[big.js] ",H=W+"Invalid ",z=H+"decimal places",V=H+"rounding mode",K=W+"Division by zero",G={},J=void 0,Y=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function X(e,t,s,n){var r=e.c;if(s===J&&(s=e.constructor.RM),0!==s&&1!==s&&2!==s&&3!==s)throw Error(V);if(t<1)n=3===s&&(n||!!r[0])||0===t&&(1===s&&r[0]>=5||2===s&&(r[0]>5||5===r[0]&&(n||r[1]!==J))),r.length=1,n?(e.e=e.e-t+1,r[0]=1):r[0]=e.e=0;else if(t<r.length){if(n=1===s&&r[t]>=5||2===s&&(r[t]>5||5===r[t]&&(n||r[t+1]!==J||1&r[t-1]))||3===s&&(n||!!r[0]),r.length=t,n)for(;++r[--t]>9;)if(r[t]=0,0===t){++e.e,r.unshift(1);break}for(t=r.length;!r[--t];)r.pop()}return e}function Z(e,t,s){var n=e.e,r=e.c.join(""),i=r.length;if(t)r=r.charAt(0)+(i>1?"."+r.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)r="0"+r;r="0."+r}else if(n>0)if(++n>i)for(n-=i;n--;)r+="0";else n<i&&(r=r.slice(0,n)+"."+r.slice(n));else i>1&&(r=r.charAt(0)+"."+r.slice(1));return e.s<0&&s?"-"+r:r}G.abs=function(){var e=new this.constructor(this);return e.s=1,e},G.cmp=function(e){var t,s=this,n=s.c,r=(e=new s.constructor(e)).c,i=s.s,o=e.s,a=s.e,c=e.e;if(!n[0]||!r[0])return n[0]?i:r[0]?-o:0;if(i!=o)return i;if(t=i<0,a!=c)return a>c^t?1:-1;for(o=(a=n.length)<(c=r.length)?a:c,i=-1;++i<o;)if(n[i]!=r[i])return n[i]>r[i]^t?1:-1;return a==c?0:a>c^t?1:-1},G.div=function(e){var t=this,s=t.constructor,n=t.c,r=(e=new s(e)).c,i=t.s==e.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>F)throw Error(z);if(!r[0])throw Error(K);if(!n[0])return e.s=i,e.c=[e.e=0],e;var a,c,l,d,h,u=r.slice(),p=a=r.length,f=n.length,g=n.slice(0,a),m=g.length,y=e,w=y.c=[],b=0,v=o+(y.e=t.e-e.e)+1;for(y.s=i,i=v<0?0:v,u.unshift(0);m++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(m=g.length))d=a>m?1:-1;else for(h=-1,d=0;++h<a;)if(r[h]!=g[h]){d=r[h]>g[h]?1:-1;break}if(!(d<0))break;for(c=m==a?r:u;m;){if(g[--m]<c[m]){for(h=m;h&&!g[--h];)g[h]=9;--g[h],g[m]+=10}g[m]-=c[m]}for(;!g[0];)g.shift()}w[b++]=d?l:++l,g[0]&&d?g[m]=n[p]||0:g=[n[p]]}while((p++<f||g[0]!==J)&&i--);return w[0]||1==b||(w.shift(),y.e--,v--),b>v&&X(y,v,s.RM,g[0]!==J),y},G.eq=function(e){return 0===this.cmp(e)},G.gt=function(e){return this.cmp(e)>0},G.gte=function(e){return this.cmp(e)>-1},G.lt=function(e){return this.cmp(e)<0},G.lte=function(e){return this.cmp(e)<1},G.minus=G.sub=function(e){var t,s,n,r,i=this,o=i.constructor,a=i.s,c=(e=new o(e)).s;if(a!=c)return e.s=-c,i.plus(e);var l=i.c.slice(),d=i.e,h=e.c,u=e.e;if(!l[0]||!h[0])return h[0]?e.s=-c:l[0]?e=new o(i):e.s=1,e;if(a=d-u){for((r=a<0)?(a=-a,n=l):(u=d,n=h),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(s=((r=l.length<h.length)?l:h).length,a=c=0;c<s;c++)if(l[c]!=h[c]){r=l[c]<h[c];break}if(r&&(n=l,l=h,h=n,e.s=-e.s),(c=(s=h.length)-(t=l.length))>0)for(;c--;)l[t++]=0;for(c=t;s>a;){if(l[--s]<h[s]){for(t=s;t&&!l[--t];)l[t]=9;--l[t],l[s]+=10}l[s]-=h[s]}for(;0===l[--c];)l.pop();for(;0===l[0];)l.shift(),--u;return l[0]||(e.s=1,l=[u=0]),e.c=l,e.e=u,e},G.mod=function(e){var t,s=this,n=s.constructor,r=s.s,i=(e=new n(e)).s;if(!e.c[0])throw Error(K);return s.s=e.s=1,t=1==e.cmp(s),s.s=r,e.s=i,t?new n(s):(r=n.DP,i=n.RM,n.DP=n.RM=0,s=s.div(e),n.DP=r,n.RM=i,this.minus(s.times(e)))},G.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},G.plus=G.add=function(e){var t,s,n,r=this,i=r.constructor;if(e=new i(e),r.s!=e.s)return e.s=-e.s,r.minus(e);var o=r.e,a=r.c,c=e.e,l=e.c;if(!a[0]||!l[0])return l[0]||(a[0]?e=new i(r):e.s=r.s),e;if(a=a.slice(),t=o-c){for(t>0?(c=o,n=l):(t=-t,n=a),n.reverse();t--;)n.push(0);n.reverse()}for(a.length-l.length<0&&(n=l,l=a,a=n),t=l.length,s=0;t;a[t]%=10)s=(a[--t]=a[t]+l[t]+s)/10|0;for(s&&(a.unshift(s),++c),t=a.length;0===a[--t];)a.pop();return e.c=a,e.e=c,e},G.pow=function(e){var t=this,s=new t.constructor("1"),n=s,r=e<0;if(e!==~~e||e<-1e6||e>q)throw Error(H+"exponent");for(r&&(e=-e);1&e&&(n=n.times(t)),e>>=1;)t=t.times(t);return r?s.div(n):n},G.prec=function(e,t){if(e!==~~e||e<1||e>F)throw Error(H+"precision");return X(new this.constructor(this),e,t)},G.round=function(e,t){if(e===J)e=0;else if(e!==~~e||e<-F||e>F)throw Error(z);return X(new this.constructor(this),e+this.e+1,t)},G.sqrt=function(){var e,t,s,n=this,r=n.constructor,i=n.s,o=n.e,a=new r("0.5");if(!n.c[0])return new r(n);if(i<0)throw Error(W+"No square root");0===(i=Math.sqrt(+Z(n,!0,!0)))||i===1/0?((t=n.c.join("")).length+o&1||(t+="0"),o=((o+1)/2|0)-(o<0||1&o),e=new r(((i=Math.sqrt(t))==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):e=new r(i+""),o=e.e+(r.DP+=4);do{s=e,e=a.times(s.plus(n.div(s)))}while(s.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return X(e,(r.DP-=4)+e.e+1,r.RM)},G.times=G.mul=function(e){var t,s=this,n=s.constructor,r=s.c,i=(e=new n(e)).c,o=r.length,a=i.length,c=s.e,l=e.e;if(e.s=s.s==e.s?1:-1,!r[0]||!i[0])return e.c=[e.e=0],e;for(e.e=c+l,o<a&&(t=r,r=i,i=t,l=o,o=a,a=l),t=new Array(l=o+a);l--;)t[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=t[l]+i[c]*r[l-c-1]+a,t[l--]=a%10,a=a/10|0;t[l]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e},G.toExponential=function(e,t){var s=this,n=s.c[0];if(e!==J){if(e!==~~e||e<0||e>F)throw Error(z);for(s=X(new s.constructor(s),++e,t);s.c.length<e;)s.c.push(0)}return Z(s,!0,!!n)},G.toFixed=function(e,t){var s=this,n=s.c[0];if(e!==J){if(e!==~~e||e<0||e>F)throw Error(z);for(e=e+(s=X(new s.constructor(s),e+s.e+1,t)).e+1;s.c.length<e;)s.c.push(0)}return Z(s,!1,!!n)},G[Symbol.for("nodejs.util.inspect.custom")]=G.toJSON=G.toString=function(){var e=this,t=e.constructor;return Z(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},G.toNumber=function(){var e=+Z(this,!0,!0);if(!0===this.constructor.strict&&!this.eq(e.toString()))throw Error(W+"Imprecise conversion");return e},G.toPrecision=function(e,t){var s=this,n=s.constructor,r=s.c[0];if(e!==J){if(e!==~~e||e<1||e>F)throw Error(H+"precision");for(s=X(new n(s),e,t);s.c.length<e;)s.c.push(0)}return Z(s,e<=s.e||s.e<=n.NE||s.e>=n.PE,!!r)},G.valueOf=function(){var e=this,t=e.constructor;if(!0===t.strict)throw Error(W+"valueOf disallowed");return Z(e,e.e<=t.NE||e.e>=t.PE,!0)};var Q=function e(){function t(s){var n=this;if(!(n instanceof t))return s===J?e():new t(s);if(s instanceof t)n.s=s.s,n.e=s.e,n.c=s.c.slice();else{if("string"!=typeof s){if(!0===t.strict&&"bigint"!=typeof s)throw TypeError(H+"value");s=0===s&&1/s<0?"-0":String(s)}!function(e,t){var s,n,r;if(!Y.test(t))throw Error(H+"number");e.s="-"==t.charAt(0)?(t=t.slice(1),-1):1,(s=t.indexOf("."))>-1&&(t=t.replace(".",""));(n=t.search(/e/i))>0?(s<0&&(s=n),s+=+t.slice(n+1),t=t.substring(0,n)):s<0&&(s=t.length);for(r=t.length,n=0;n<r&&"0"==t.charAt(n);)++n;if(n==r)e.c=[e.e=0];else{for(;r>0&&"0"==t.charAt(--r););for(e.e=s-n-1,e.c=[],s=0;n<=r;)e.c[s++]=+t.charAt(n++)}}(n,s)}n.constructor=t}return t.prototype=G,t.DP=20,t.RM=1,t.NE=-7,t.PE=21,t.strict=false,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}();const ee={bigNumber(e,t={safe:!1}){try{return new Q(e?e:0)}catch(e){if(t.safe)return new Q(0);throw e}},formatNumber(e,t){const{decimals:s,round:n=8,safe:r=!0}=t;return ee.bigNumber(e,{safe:r}).div(new Q(10).pow(s)).round(n)},multiply(e,t){if(void 0===e||void 0===t)return new Q(0);const s=new Q(e),n=new Q(t);return s.times(n)},toFixed:(e,t=2)=>void 0===e||""===e?new Q(0).toFixed(t):new Q(e).toFixed(t),formatNumberToLocalString:(e,t=2)=>void 0===e||""===e?"0.00":"number"==typeof e?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t,roundingMode:"floor"}),parseLocalStringToNumber(e){if(void 0===e||""===e)return 0;const t=e.replace(/,/gu,"");return new Q(t).toNumber()}},te=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],se=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],ne=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],re={getERC20Abi:e=>B.USDT_CONTRACT_ADDRESSES.includes(e)?ne:te,getSwapAbi:()=>se},ie={ConnectorExplorerIds:{[B.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[B.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[B.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[B.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[B.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[B.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[B.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[B.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[B.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[B.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[B.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[B.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[B.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[B.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[B.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[B.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[B.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[B.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[B.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600","0x2b6653dc":"3502bb86-cc4e-420f-a387-59ea63a28b00","0x94a9059e":"3502bb86-cc4e-420f-a387-59ea63a28b00","0xcd8690dc":"3502bb86-cc4e-420f-a387-59ea63a28b00"},ConnectorImageIds:{[B.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[B.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[B.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[B.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[B.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[B.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[B.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[B.CONNECTOR_ID.INJECTED]:"Browser Wallet",[B.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[B.CONNECTOR_ID.COINBASE]:"Coinbase",[B.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[B.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[B.CONNECTOR_ID.LEDGER]:"Ledger",[B.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[B.CONNECTOR_ID.INJECTED]:"INJECTED",[B.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[B.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[B.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},oe={validateCaipAddress(e){if(3!==e.split(":")?.length)throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){const t=e.split(":");if(3!==t.length)throw new Error(`Invalid CAIP-10 address: ${e}`);const[s,n,r]=t;if(!s||!n||!r)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:s,chainId:n,address:r}},parseCaipNetworkId(e){const t=e.split(":");if(2!==t.length)throw new Error(`Invalid CAIP-2 network id: ${e}`);const[s,n]=t;if(!s||!n)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:s,chainId:n}}},ae={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3,SEND_TRANSACTION_ERROR:5001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError",SEND_TRANSACTION_ERROR:"SendTransactionError"},isRpcProviderError(e){try{if("object"==typeof e&&null!==e){const t=e,s="string"==typeof t.message,n="number"==typeof t.code;return s&&n}return!1}catch{return!1}},isUserRejectedMessage:e=>e.toLowerCase().includes("user rejected")||e.toLowerCase().includes("user cancelled")||e.toLowerCase().includes("user canceled"),isUserRejectedRequestError(e){if(ae.isRpcProviderError(e)){const t=e.code===ae.RPC_ERROR_CODE.USER_REJECTED_REQUEST,s=e.code===ae.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||s||ae.isUserRejectedMessage(e.message)}return e instanceof Error&&ae.isUserRejectedMessage(e.message)}};class ce extends Error{constructor(e,t){super(t.message,{cause:e}),this.name=ae.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=t.code}}class le extends ce{constructor(e){super(e,{code:ae.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=ae.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const de={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version",TON_WALLETS_CACHE:"@appkit/ton_wallets_cache"};function he(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const ue={setItem(e,t){pe()&&void 0!==t&&localStorage.setItem(e,t)},getItem(e){if(pe())return localStorage.getItem(e)||void 0},removeItem(e){pe()&&localStorage.removeItem(e)},clear(){pe()&&localStorage.clear()}};function pe(){return"undefined"!=typeof window&&"undefined"!=typeof localStorage}function fe(e,t){const s=e?.["--apkt-accent"]??e?.["--w3m-accent"];return"light"===t?{"--w3m-accent":s||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":s||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const ge=Symbol(),me=Object.getPrototypeOf,ye=new WeakMap,we=e=>(e=>e&&(ye.has(e)?ye.get(e):me(e)===Object.prototype||me(e)===Array.prototype))(e)&&e[ge]||null,be=(e,t=!0)=>{ye.set(e,t)},ve=e=>"object"==typeof e&&null!==e,Ee=(e,t)=>{const s=Ae.get(e);if((null==s?void 0:s[0])===t)return s[1];const n=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return be(n,!0),Ae.set(e,[t,n]),Reflect.ownKeys(e).forEach((t=>{if(Object.getOwnPropertyDescriptor(n,t))return;const s=Reflect.get(e,t),{enumerable:r}=Reflect.getOwnPropertyDescriptor(e,t),i={value:s,enumerable:r,configurable:!0};if(Ne.has(s))be(s,!1);else if(Ce.has(s)){const[e,t]=Ce.get(s);i.value=Ee(e,t())}Object.defineProperty(n,t,i)})),Object.preventExtensions(n)},Ce=new WeakMap,Ne=new WeakSet,Ae=new WeakMap,Ie=[1],Se=new WeakMap;let _e=Object.is,Oe=(e,t)=>new Proxy(e,t),Te=e=>ve(e)&&!Ne.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer)&&!(e instanceof Promise),ke=Ee,Pe=(e,t,s,n)=>({deleteProperty(e,t){const r=Reflect.get(e,t);s(t);const i=Reflect.deleteProperty(e,t);return i&&n(["delete",[t],r]),i},set(r,i,o,a){const c=!e()&&Reflect.has(r,i),l=Reflect.get(r,i,a);if(c&&(_e(l,o)||Se.has(o)&&_e(l,Se.get(o))))return!0;s(i),ve(o)&&(o=we(o)||o);const d=!Ce.has(o)&&Te(o)?xe(o):o;return t(i,d),Reflect.set(r,i,d,a),n(["set",[i],o,l]),!0}});function xe(e={}){if(!ve(e))throw new Error("object required");const t=Se.get(e);if(t)return t;let s=Ie[0];const n=new Set,r=(e,t=++Ie[0])=>{s!==t&&(i=s=t,n.forEach((s=>s(e,t))))};let i=s;const o=e=>(t,s)=>{const n=[...t];n[1]=[e,...n[1]],r(n,s)},a=new Map;let c=!0;const l=Pe((()=>c),((e,t)=>{const s=!Ne.has(t)&&Ce.get(t);if(s){if("production"!==(import.meta.env?import.meta.env.MODE:void 0)&&a.has(e))throw new Error("prop listener already exists");if(n.size){const t=s[2](o(e));a.set(e,[s,t])}else a.set(e,[s])}}),(e=>{var t;const s=a.get(e);s&&(a.delete(e),null==(t=s[1])||t.call(s))}),r),d=Oe(e,l);Se.set(e,d);const h=[e,(e=Ie[0])=>(i!==e&&(i=e,a.forEach((([t])=>{const n=t[1](e);n>s&&(s=n)}))),s),e=>{n.add(e),1===n.size&&a.forEach((([e,t],s)=>{if("production"!==(import.meta.env?import.meta.env.MODE:void 0)&&t)throw new Error("remove already exists");const n=e[2](o(s));a.set(s,[e,n])}));return()=>{n.delete(e),0===n.size&&a.forEach((([e,t],s)=>{t&&(t(),a.set(s,[e]))}))}}];return Ce.set(d,h),Reflect.ownKeys(e).forEach((t=>{const s=Object.getOwnPropertyDescriptor(e,t);"value"in s&&s.writable&&(d[t]=e[t])})),c=!1,d}function Re(e,t,s){const n=Ce.get(e);let r;"production"===(import.meta.env?import.meta.env.MODE:void 0)||n||console.warn("Please use proxy object");const i=[],o=n[2];let a=!1;const c=o((e=>{i.push(e),s?t(i.splice(0)):r||(r=Promise.resolve().then((()=>{r=void 0,a&&t(i.splice(0))})))}));return a=!0,()=>{a=!1,c()}}function Ue(e){const t=Ce.get(e);"production"===(import.meta.env?import.meta.env.MODE:void 0)||t||console.warn("Please use proxy object");const[s,n]=t;return ke(s,n())}function Le(e){return Ne.add(e),e}function De(e,t,s,n){let r=e[t];return Re(e,(()=>{const n=e[t];Object.is(r,n)||s(r=n)}),n)}const{proxyStateMap:Me,snapCache:Be}={proxyStateMap:Ce,refSet:Ne,snapCache:Ae,versionHolder:Ie,proxyCache:Se},je=e=>Me.has(e);const $e=("undefined"!=typeof process&&void 0!==process.env?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Fe=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],qe={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:$e,SECURE_SITE_DASHBOARD:`${$e}/dashboard`,SECURE_SITE_FAVICON:`${$e}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD₮0"]},BALANCE_SUPPORTED_CHAINS:[B.CHAIN.EVM,B.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[B.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[B.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[B.CHAIN.EVM,B.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[B.CHAIN.EVM,B.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[B.CHAIN.EVM,B.CHAIN.TON],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x",ton:"0x",tron:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[B.CHAIN.EVM,B.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1,headless:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1,headless:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1,headless:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa",ton:"eoa",tron:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0},MANDATORY_WALLET_IDS_ON_MOBILE:[ie.ConnectorExplorerIds[B.CONNECTOR_ID.COINBASE],ie.ConnectorExplorerIds[B.CONNECTOR_ID.COINBASE_SDK],ie.ConnectorExplorerIds[B.CONNECTOR_ID.BASE_ACCOUNT],ie.ConnectorExplorerIds[B.SOLFLARE_CONNECTOR_NAME],ie.ConnectorExplorerIds[B.PHANTOM_CONNECTOR_NAME],ie.ConnectorExplorerIds[B.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]},We={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5,tonWallets:864e5},isCacheExpired:(e,t)=>Date.now()-e>t,getActiveNetworkProps(){const e=We.getActiveNamespace(),t=We.getActiveCaipNetworkId(),s=t?t.split(":")[1]:void 0;return{namespace:e,caipNetworkId:t,chainId:s?isNaN(Number(s))?s:Number(s):void 0}},setWalletConnectDeepLink({name:e,href:t}){try{ue.setItem(de.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=ue.getItem(de.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{ue.removeItem(de.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{ue.setItem(de.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{ue.setItem(de.ACTIVE_CAIP_NETWORK_ID,e),We.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return ue.getItem(de.ACTIVE_CAIP_NETWORK_ID)}catch{return void console.info("Unable to get active caip network id")}},deleteActiveCaipNetworkId(){try{ue.removeItem(de.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=he(e);ue.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=We.getRecentWallets(),s=t.find((t=>t.id===e.id));s||(t.unshift(e),t.length>2&&t.pop(),ue.setItem(de.RECENT_WALLETS,JSON.stringify(t)),ue.setItem(de.RECENT_WALLET,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=ue.getItem(de.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const e=ue.getItem(de.RECENT_WALLET);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{ue.removeItem(de.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{const s=he(e);ue.setItem(s,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return ue.getItem(de.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=he(e);return ue.getItem(t)}catch(t){console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{ue.setItem(de.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return ue.getItem(de.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{ue.removeItem(de.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return ue.getItem(de.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){const e=ue.getItem(de.ACTIVE_CAIP_NETWORK_ID),t=e?.split(":")?.[1];return t},setConnectionStatus(e){try{ue.setItem(de.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return ue.getItem(de.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const e=ue.getItem(de.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));ue.setItem(de.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=We.getConnectedNamespaces();t.includes(e)||(t.push(e),We.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=We.getConnectedNamespaces(),s=t.indexOf(e);s>-1&&(t.splice(s,1),We.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return ue.getItem(de.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{ue.setItem(de.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{ue.removeItem(de.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=ue.getItem(de.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=We.getBalanceCache();ue.setItem(de.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const t=We.getBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;We.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=We.getBalanceCache();t[e.caipAddress]=e,ue.setItem(de.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=ue.getItem(de.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=We.getBalanceCache();ue.setItem(de.NATIVE_BALANCE_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getNativeBalanceCacheForCaipAddress(e){try{const t=We.getNativeBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",e),We.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=We.getNativeBalanceCache();t[e.caipAddress]=e,ue.setItem(de.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=ue.getItem(de.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const t=We.getEnsCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;We.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=We.getEnsCache();t[e.address]=e,ue.setItem(de.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=We.getEnsCache();ue.setItem(de.ENS_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove ens name from cache",e)}},getIdentityCache(){let e={};try{const t=ue.getItem(de.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const t=We.getIdentityCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;We.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=We.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},ue.setItem(de.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=We.getIdentityCache();ue.setItem(de.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},getTonWalletsCache(){try{const e=ue.getItem(de.TON_WALLETS_CACHE),t=e?JSON.parse(e):void 0;if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tonWallets))return t;We.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(e){try{const t=We.getTonWalletsCache()||{timestamp:0,wallets:[]};t.timestamp=(new Date).getTime(),t.wallets=e,ue.setItem(de.TON_WALLETS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ton wallets cache",e)}},removeTonWalletsCache(){try{ue.removeItem(de.TON_WALLETS_CACHE)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{ue.removeItem(de.PORTFOLIO_CACHE),ue.removeItem(de.NATIVE_BALANCE_CACHE),ue.removeItem(de.ENS_CACHE),ue.removeItem(de.IDENTITY_CACHE),ue.removeItem(de.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{ue.setItem(de.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=ue.getItem(de.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const s=We.getConnections(),n=s[t]??[],r=new Map;for(const e of n)r.set(e.connectorId,{...e});for(const t of e){const e=r.get(t.connectorId),s=t.connectorId===B.CONNECTOR_ID.AUTH;if(e&&!s){const s=new Set(e.accounts.map((e=>e.address.toLowerCase()))),n=t.accounts.filter((e=>!s.has(e.address.toLowerCase())));e.accounts.push(...n)}else r.set(t.connectorId,{...t})}const i={...s,[t]:Array.from(r.values())};ue.setItem(de.CONNECTIONS,JSON.stringify(i))}catch(e){console.error("Unable to sync connections to storage",e)}},getConnections(){try{const e=ue.getItem(de.CONNECTIONS);return e?JSON.parse(e):{}}catch(e){return console.error("Unable to get connections from storage",e),{}}},deleteAddressFromConnection({connectorId:e,address:t,namespace:s}){try{const n=We.getConnections(),r=n[s]??[],i=new Map(r.map((e=>[e.connectorId,e]))),o=i.get(e);if(o){0===o.accounts.filter((e=>e.address.toLowerCase()!==t.toLowerCase())).length?i.delete(e):i.set(e,{...o,accounts:o.accounts.filter((e=>e.address.toLowerCase()!==t.toLowerCase()))})}ue.setItem(de.CONNECTIONS,JSON.stringify({...n,[s]:Array.from(i.values())}))}catch{console.error(`Unable to remove address "${t}" from connector "${e}" in namespace "${s}"`)}},getDisconnectedConnectorIds(){try{const e=ue.getItem(de.DISCONNECTED_CONNECTOR_IDS);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{const s=We.getDisconnectedConnectorIds(),n=s[t]??[];n.push(e),ue.setItem(de.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[t]:Array.from(new Set(n))}))}catch{console.error(`Unable to set disconnected connector id "${e}" for namespace "${t}"`)}},removeDisconnectedConnectorId(e,t){try{const s=We.getDisconnectedConnectorIds();let n=s[t]??[];n=n.filter((t=>t.toLowerCase()!==e.toLowerCase())),ue.setItem(de.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[t]:Array.from(new Set(n))}))}catch{console.error(`Unable to remove disconnected connector id "${e}" for namespace "${t}"`)}},isConnectorDisconnected(e,t){try{const s=We.getDisconnectedConnectorIds();return(s[t]??[]).some((t=>t.toLowerCase()===e.toLowerCase()))}catch{console.info(`Unable to get disconnected connector id "${e}" for namespace "${t}"`)}return!1},getTransactionsCache(){try{const e=ue.getItem(de.HISTORY_TRANSACTIONS_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:e,chainId:t=""}){try{const s=We.getTransactionsCache(),n=s[e]?.[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.transactionsHistory))return n.transactions;We.removeTransactionsCache({address:e,chainId:t})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:e,chainId:t="",timestamp:s,transactions:n}){try{const r=We.getTransactionsCache();r[e]={...r[e],[t]:{timestamp:s,transactions:n}},ue.setItem(de.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(r))}catch{console.info("Unable to update transactions cache",{address:e,chainId:t,timestamp:s,transactions:n})}},removeTransactionsCache({address:e,chainId:t}){try{const s=We.getTransactionsCache(),n=s?.[e]||{},{[t]:r,...i}=n;ue.setItem(de.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...s,[e]:i}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{const e=ue.getItem(de.TOKEN_PRICE_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{const t=We.getTokenPriceCache()[e.join(",")];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tokenPrice))return t.tokenPrice;We.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{const t=We.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},ue.setItem(de.TOKEN_PRICE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{const t=We.getTokenPriceCache();ue.setItem(de.TOKEN_PRICE_CACHE,JSON.stringify({...t,[e.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",e)}},getLatestAppKitVersion(){try{const e=this.getLatestAppKitVersionCache(),t=e?.version;return t&&!this.isCacheExpired(e.timestamp,this.cacheExpiry.latestAppKitVersion)?t:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const e=ue.getItem(de.LATEST_APPKIT_VERSION);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{const t=We.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,ue.setItem(de.LATEST_APPKIT_VERSION,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}},He={getWindow(){if("undefined"!=typeof window)return window},isMobile(){return!!this.isClient()&&Boolean(window?.matchMedia&&"function"==typeof window.matchMedia&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent))},checkCaipNetwork:(e,t="")=>e?.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase()),isAndroid(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return He.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){if(!this.isClient())return!1;const e=window?.navigator.userAgent.toLowerCase();return e.includes("safari")},isClient:()=>"undefined"!=typeof window,isPairingExpired:e=>!e||e-Date.now()<=qe.TEN_SEC_MS,isAllowedRetry:(e,t=qe.ONE_SEC_MS)=>Date.now()-e>=t,copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return window?.self!==window?.top}catch(e){return!1}},isSafeApp(){if(He.isClient()&&window.self!==window.top)try{const e=window?.location?.ancestorOrigins?.[0],t="https://app.safe.global";if(e){const s=new URL(e),n=new URL(t);return s.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry:()=>Date.now()+qe.FOUR_MINUTES_MS,getNetworkId:e=>e?.split(":")[1],getPlainAddress:e=>e?.split(":")[2],wait:async e=>new Promise((t=>{setTimeout(t,e)})),debounce(e,t=500){let s;return(...n)=>{s&&clearTimeout(s),s=setTimeout((function(){e(...n)}),t)}},isHttpUrl:e=>e.startsWith("http://")||e.startsWith("https://"),formatNativeUrl(e,t,s=null){if(He.isHttpUrl(e))return this.formatUniversalUrl(e,t);let n=e,r=s;n.includes("://")||(n=e.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),r&&!r?.endsWith("/")&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const i=encodeURIComponent(t);return{redirect:`${n}wc?uri=${i}`,redirectUniversalLink:r?`${r}wc?uri=${i}`:void 0,href:n}},formatUniversalUrl(e,t){if(!He.isHttpUrl(e))return this.formatNativeUrl(e,t);let s=e;s.endsWith("/")||(s=`${s}/`);return{redirect:`${s}wc?uri=${encodeURIComponent(t)}`,href:s}},getOpenTargetForPlatform(e){return"popupWindow"===e?e:this.isTelegram()?We.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,s){window?.open(e,this.getOpenTargetForPlatform(t),s||"noreferrer noopener")},returnOpenHref(e,t,s){return window?.open(e,this.getOpenTargetForPlatform(t),s||"noreferrer noopener")},isTelegram:()=>"undefined"!=typeof window&&(Boolean(window.TelegramWebviewProxy)||Boolean(window.Telegram)||Boolean(window.TelegramWebviewProxyProto)),isPWA(){if("undefined"==typeof window)return!1;const e=!(!window?.matchMedia||"function"!=typeof window.matchMedia)&&window.matchMedia("(display-mode: standalone)")?.matches,t=window?.navigator?.standalone;return Boolean(e||t)},async preloadImage(e){const t=new Promise(((t,s)=>{const n=new Image;n.onload=t,n.onerror=s,n.crossOrigin="anonymous",n.src=e}));return Promise.race([t,He.wait(2e3)])},parseBalance(e,t){let s="0.000";if("string"==typeof e){const t=Number(e);if(!isNaN(t)){const e=(Math.floor(1e3*t)/1e3).toFixed(3);e&&(s=e)}}const[n,r]=s.split("."),i=n||"0",o=r||"000";return{formattedText:`${i}.${o}${t?` ${t}`:""}`,value:i,decimals:o,symbol:t}},getApiUrl:()=>B.W3M_API_URL,getBlockchainApiUrl:()=>B.BLOCKCHAIN_API_RPC_URL,getAnalyticsUrl:()=>B.PULSE_API_URL,getUUID:()=>crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),parseError:e=>"string"==typeof e?e:"string"==typeof e?.issues?.[0]?.message?e.issues[0].message:e instanceof Error?e.message:"Unknown error",sortRequestedNetworks(e,t=[]){const s={};return t&&e&&(e.forEach(((e,t)=>{s[e]=t})),t.sort(((e,t)=>{const n=s[e.id],r=s[t.id];return void 0!==n&&void 0!==r?n-r:void 0!==n?-1:void 0!==r?1:0}))),t},calculateBalance(e){let t=0;for(const s of e)t+=s.value??0;return t},formatTokenBalance(e){const t=e.toFixed(2),[s,n]=t.split(".");return{dollars:s,pennies:n}},isAddress(e,t="eip155"){switch(t){case"eip155":return!!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!(!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!/^(?:0x)?[0-9A-F]{40}$/iu.test(e));case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);case"bip122":{const t=/^[1][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),s=/^[3][a-km-zA-HJ-NP-Z1-9]{25,34}$/u.test(e),n=/^bc1[a-z0-9]{39,87}$/u.test(e),r=/^bc1p[a-z0-9]{58}$/u.test(e);return t||s||n||r}default:return!1}},uniqueBy(e,t){const s=new Set;return e.filter((e=>{const n=e[t];return!s.has(n)&&(s.add(n),!0)}))},generateSdkVersion:(e,t,s)=>`${t}-${0===e.length?qe.ADAPTER_TYPES.UNIVERSAL:e.map((e=>e.adapterType)).join(",")}-${s}`,createAccount(e){const{chainNamespace:t,chainId:s,address:n}=oe.parseCaipAddress(e.caipAddress);return{namespace:t,address:n,chainId:s,caipAddress:e.caipAddress,type:e.type,publicKey:e.publicKey,path:e.path}},isCaipAddress(e){if("string"!=typeof e)return!1;const t=e.split(":"),s=t[0];return 3===t.filter(Boolean).length&&s in B.CHAIN_NAME_MAP},getAccount:e=>e?"string"==typeof e?{address:e,chainId:void 0}:{address:e.address,chainId:e.chainId}:{address:void 0,chainId:void 0},isMac(){const e=window?.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){const t=`--${encodeURIComponent(window?.location.href)}`,s="state=";if("auth.magic.link"===new URL(e).host){const n="provider_authorization_url=",r=e.substring(e.indexOf(n)+n.length),i=this.injectIntoUrl(decodeURIComponent(r),s,t);return e.replace(r,encodeURIComponent(i))}return this.injectIntoUrl(e,s,t)},injectIntoUrl(e,t,s){const n=e.indexOf(t);if(-1===n)throw new Error(`${t} parameter not found in the URL: ${e}`);const r=e.indexOf("&",n),i=t.length,o=-1!==r?r:e.length;return e.substring(0,n+i)+(e.substring(n+i,o)+s)+e.substring(r)},isNumber:e=>("number"==typeof e||"string"==typeof e)&&!isNaN(Number(e)),appendPayToUri:(e,t)=>t?`${e}&pay=${encodeURIComponent(t)}`:e};"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL,"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL,"undefined"!=typeof process&&void 0!==process.env&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const ze="@appkit-wallet/",Ve="LAST_EMAIL_LOGIN_TIME",Ke="SMART_ACCOUNT_ENABLED_NETWORKS",Ge="RPC_RESPONSE_TRANSACTION_HASH",Je="RPC_RESPONSE_OBJECT",Ye={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},Xe=/^0x(?:[A-Fa-f0-9]{64})$/u,Ze=/^0x(?:[a-fA-F0-9]{62,})$/u,Qe={set(e,t){tt.isClient&&localStorage.setItem(`${ze}${e}`,t)},get:e=>tt.isClient?localStorage.getItem(`${ze}${e}`):null,delete(e,t){tt.isClient&&(t?localStorage.removeItem(e):localStorage.removeItem(`${ze}${e}`))}},et=3e4,tt={checkIfAllowedToTriggerEmail(){const e=Qe.get(Ve);if(e){const t=Date.now()-Number(e);if(t<et){const e=Math.ceil((et-t)/1e3);throw new Error(`Please try again after ${e} seconds`)}}},getTimeToNextEmailLogin(){const e=Qe.get(Ve);if(e){const t=Date.now()-Number(e);if(t<et)return Math.ceil((et-t)/1e3)}return 0},checkIfRequestExists:e=>Ye.NOT_SAFE_RPC_METHODS.includes(e.method)||Ye.SAFE_RPC_METHODS.includes(e.method),getResponseType:e=>"string"==typeof e&&(e?.match(Xe)||e?.match(Ze))?Ge:Je,checkIfRequestIsSafe:e=>Ye.SAFE_RPC_METHODS.includes(e.method),isClient:"undefined"!=typeof window},st={wei:0,gwei:9,szabo:12,finney:15,ether:18};function nt(e,t=0){if(!Number.isInteger(t)||t<0)throw new dt({decimals:t});let s=e.toString();const n=s.startsWith("-");n&&(s=s.slice(1)),s=s.padStart(t,"0");let[r,i]=[s.slice(0,s.length-t),s.slice(s.length-t)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${r||"0"}${i?`.${i}`:""}`}function rt(e,t="wei"){return nt(e,st.ether-st[t])}function it(e,t="wei"){return nt(e,st.gwei-st[t])}function ot(e,t=0){if(!Number.isInteger(t)||t<0)throw new dt({decimals:t});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(e))throw new lt({value:e});let[s="",n="0"]=e.split(".");const r=s.startsWith("-");if(r&&(s=s.slice(1)),""===s&&(s="0"),n=n.replace(/(0+)$/,""),0===t)n.length>0&&Number.parseInt(n[0],10)>=5&&(s=`${BigInt(s)+1n}`),n="";else if(n.length>t){const e=n.slice(0,t);if(Number.parseInt(n.slice(t,t+1),10)>=5){const r=function(e){const t=e.split("");let s=t.length-1;for(;s>=0;){const e=Number.parseInt(t[s],10)+1;if(e<10)return t[s]=String(e),t.join("");t[s]="0",s--}return`1${t.join("")}`}(e);r.length>t?(n=r.slice(1),s=`${BigInt(s)+1n}`):n=r}else n=e}else n=n.padEnd(t,"0");return BigInt(`${r?"-":""}${s}${n}`)}function at(e,t="wei"){return ot(e,st.ether-st[t])}function ct(e,t="wei"){return ot(e,st.gwei-st[t])}class lt extends Error{constructor({value:e}){super(`Value \`${e}\` is not a valid decimal number.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalNumberError"})}}class dt extends Error{constructor({decimals:e}){super(`\`decimals\` must be a non-negative integer. Got \`${e}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Value.InvalidDecimalsError"})}}const ht=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{name:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],ut=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],pt=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],ft=[...pt,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],gt=[...pt,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],mt=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],yt=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],wt=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],bt=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],vt=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Et=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"bytes32"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Ct=[{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC1155InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC1155InvalidApprover",type:"error"},{inputs:[{internalType:"uint256",name:"idsLength",type:"uint256"},{internalType:"uint256",name:"valuesLength",type:"uint256"}],name:"ERC1155InvalidArrayLength",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC1155InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC1155InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC1155InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC1155MissingApprovalForAll",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256[]",name:"ids",type:"uint256[]"},{indexed:!1,internalType:"uint256[]",name:"values",type:"uint256[]"}],name:"TransferBatch",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"id",type:"uint256"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"TransferSingle",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"value",type:"string"},{indexed:!0,internalType:"uint256",name:"id",type:"uint256"}],name:"URI",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"id",type:"uint256"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"accounts",type:"address[]"},{internalType:"uint256[]",name:"ids",type:"uint256[]"}],name:"balanceOfBatch",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"ids",type:"uint256[]"},{internalType:"uint256[]",name:"values",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeBatchTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"uri",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"}],Nt=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"event",name:"ApprovalForAll",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"operator",type:"address"},{indexed:!1,name:"approved",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!0,name:"tokenId",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"payable",inputs:[{name:"spender",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"getApproved",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"address"}]},{type:"function",name:"isApprovedForAll",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"operator",type:"address"}],outputs:[{type:"bool"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"owner",type:"address"}]},{type:"function",name:"safeTransferFrom",stateMutability:"payable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]},{type:"function",name:"safeTransferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"id",type:"uint256"},{name:"data",type:"bytes"}],outputs:[]},{type:"function",name:"setApprovalForAll",stateMutability:"nonpayable",inputs:[{name:"operator",type:"address"},{name:"approved",type:"bool"}],outputs:[]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"index",type:"uint256"}],outputs:[{type:"uint256"}]},{type:"function",name:"tokenByIndex",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"index",type:"uint256"}],outputs:[{name:"tokenId",type:"uint256"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transferFrom",stateMutability:"payable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"tokenId",type:"uint256"}],outputs:[]}],At=[{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"sender",type:"address"},{indexed:!0,name:"receiver",type:"address"},{indexed:!0,name:"owner",type:"address"},{indexed:!1,name:"assets",type:"uint256"},{indexed:!1,name:"shares",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],name:"allowance",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],name:"approve",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"asset",outputs:[{name:"assetTokenAddress",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"convertToAssets",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"convertToShares",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"}],name:"deposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxDeposit",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"caller",type:"address"}],name:"maxMint",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxRedeem",outputs:[{name:"maxShares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"maxWithdraw",outputs:[{name:"maxAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"}],name:"mint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewDeposit",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewMint",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"}],name:"previewRedeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"assets",type:"uint256"}],name:"previewWithdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"shares",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"redeem",outputs:[{name:"assets",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"totalAssets",outputs:[{name:"totalManagedAssets",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transfer",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transferFrom",outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"assets",type:"uint256"},{name:"receiver",type:"address"},{name:"owner",type:"address"}],name:"withdraw",outputs:[{name:"shares",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];function It(e,t){return nt(e,t)}async function St(...e){const t=await fetch(...e);if(!t.ok){throw new Error(`HTTP status code: ${t.status}`,{cause:t})}return t}class _t{constructor({baseUrl:e,clientId:t}){this.baseUrl=e,this.clientId=t}async get({headers:e,signal:t,cache:s,...n}){const r=this.createUrl(n);return(await St(r,{method:"GET",headers:e,signal:t,cache:s})).json()}async getBlob({headers:e,signal:t,...s}){const n=this.createUrl(s);return(await St(n,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:s,...n}){const r=this.createUrl(n);return(await St(r,{method:"POST",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}async put({body:e,headers:t,signal:s,...n}){const r=this.createUrl(n);return(await St(r,{method:"PUT",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}async delete({body:e,headers:t,signal:s,...n}){const r=this.createUrl(n);return(await St(r,{method:"DELETE",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}createUrl({path:e,params:t}){const s=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach((([e,t])=>{t&&s.searchParams.append(e,t)})),this.clientId&&s.searchParams.append("clientId",this.clientId),s}sendBeacon({body:e,...t}){const s=this.createUrl(t);return navigator.sendBeacon(s.toString(),e?JSON.stringify(e):void 0)}}const Ot={getFeatureValue(e,t){const s=t?.[e];return void 0===s?qe.DEFAULT_FEATURES[e]:s},filterSocialsByPlatform(e){if(!e||!e.length)return e;let t=e;return He.isTelegram()&&(He.isIos()&&(t=t.filter((e=>"google"!==e))),He.isMac()&&(t=t.filter((e=>"x"!==e))),He.isAndroid()&&(t=t.filter((e=>!["facebook","x"].includes(e))))),He.isMobile()&&(t=t.filter((e=>"facebook"!==e))),t},isSocialsEnabled:()=>Array.isArray(kt.state.features?.socials)&&kt.state.features?.socials.length>0||Array.isArray(kt.state.remoteFeatures?.socials)&&kt.state.remoteFeatures?.socials.length>0,isEmailEnabled:()=>Boolean(kt.state.features?.email||kt.state.remoteFeatures?.email)},Tt=xe({features:qe.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:qe.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),kt={state:Tt,subscribeKey:(e,t)=>De(Tt,e,t),setOptions(e){Object.assign(Tt,e)},setRemoteFeatures(e){if(!e)return;const t={...Tt.remoteFeatures,...e};Tt.remoteFeatures=t,Tt.remoteFeatures?.socials&&(Tt.remoteFeatures.socials=Ot.filterSocialsByPlatform(Tt.remoteFeatures.socials)),Tt.features?.pay&&(Tt.remoteFeatures.email=!1,Tt.remoteFeatures.socials=!1)},setFeatures(e){if(!e)return;Tt.features||(Tt.features=qe.DEFAULT_FEATURES);const t={...Tt.features,...e};Tt.features=t,Tt.features?.pay&&Tt.remoteFeatures&&(Tt.remoteFeatures.email=!1,Tt.remoteFeatures.socials=!1)},setProjectId(e){Tt.projectId=e},setCustomRpcUrls(e){Tt.customRpcUrls=e},setAllWallets(e){Tt.allWallets=e},setIncludeWalletIds(e){Tt.includeWalletIds=e},setExcludeWalletIds(e){Tt.excludeWalletIds=e},setFeaturedWalletIds(e){Tt.featuredWalletIds=e},setTokens(e){Tt.tokens=e},setTermsConditionsUrl(e){Tt.termsConditionsUrl=e},setPrivacyPolicyUrl(e){Tt.privacyPolicyUrl=e},setCustomWallets(e){Tt.customWallets=e},setIsSiweEnabled(e){Tt.isSiweEnabled=e},setIsUniversalProvider(e){Tt.isUniversalProvider=e},setSdkVersion(e){Tt.sdkVersion=e},setMetadata(e){Tt.metadata=e},setDisableAppend(e){Tt.disableAppend=e},setEIP6963Enabled(e){Tt.enableEIP6963=e},setEnableCoinbase(e){Tt.enableCoinbase=e},setDebug(e){Tt.debug=e},setEnableWalletGuide(e){Tt.enableWalletGuide=e},setEnableAuthLogger(e){Tt.enableAuthLogger=e},setEnableWallets(e){Tt.enableWallets=e},setPreferUniversalLinks(e){Tt.experimental_preferUniversalLinks=e},setSIWX(e){if(e)for(const[t,s]of Object.entries(qe.SIWX_DEFAULTS))e[t]??=s;Tt.siwx=e},setConnectMethodsOrder(e){Tt.features={...Tt.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){Tt.features={...Tt.features,walletFeaturesOrder:e}},setSocialsOrder(e){Tt.remoteFeatures={...Tt.remoteFeatures,socials:e}},setCollapseWallets(e){Tt.features={...Tt.features,collapseWallets:e}},setEnableEmbedded(e){Tt.enableEmbedded=e},setAllowUnsupportedChain(e){Tt.allowUnsupportedChain=e},setManualWCControl(e){Tt.manualWCControl=e},setEnableNetworkSwitch(e){Tt.enableNetworkSwitch=e},setEnableMobileFullScreen(e){Tt.enableMobileFullScreen=He.isMobile()&&e},setEnableReconnect(e){Tt.enableReconnect=e},setCoinbasePreference(e){Tt.coinbasePreference=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach((([e,t])=>{t&&(Tt.defaultAccountTypes[e]=t)}))},setUniversalProviderConfigOverride(e){Tt.universalProviderConfigOverride=e},getUniversalProviderConfigOverride:()=>Tt.universalProviderConfigOverride,getSnapshot:()=>Ue(Tt)},Pt=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),xt=xe({...Pt}),Rt={state:xt,subscribeKey:(e,t)=>De(xt,e,t),showLoading(e,t={}){this._showMessage({message:e,variant:"loading",...t})},showSuccess(e){this._showMessage({message:e,variant:"success"})},showSvg(e,t){this._showMessage({message:e,svg:t})},showError(e){const t=He.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){xt.message=Pt.message,xt.variant=Pt.variant,xt.svg=Pt.svg,xt.open=Pt.open,xt.autoClose=Pt.autoClose},_showMessage({message:e,svg:t,variant:s="success",autoClose:n=Pt.autoClose}){xt.open?(xt.open=!1,setTimeout((()=>{xt.message=e,xt.variant=s,xt.svg=t,xt.open=!0,xt.autoClose=n}),150)):(xt.message=e,xt.variant=s,xt.svg=t,xt.open=!0,xt.autoClose=n)}},Ut={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Lt=He.getBlockchainApiUrl(),Dt=xe({clientId:null,api:new _t({baseUrl:Lt,clientId:null}),supportedChains:{http:[],ws:[]}}),Mt={state:Dt,async get(e){const{st:t,sv:s}=Mt.getSdkProperties(),n=kt.state.projectId,r={...e.params||{},st:t,sv:s,projectId:n};return Dt.api.get({...e,params:r})},getSdkProperties(){const{sdkType:e,sdkVersion:t}=kt.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{Dt.supportedChains.http.length||await Mt.getSupportedNetworks()}catch(e){return!1}return Dt.supportedChains.http.includes(e)},async getSupportedNetworks(){try{const e=await Mt.get({path:"v1/supported-chains"});return Dt.supportedChains=e,e}catch{return Dt.supportedChains}},async fetchIdentity({address:e}){const t=We.getIdentityFromCacheForAddress(e);if(t)return t;const s=await Mt.get({path:`/v1/identity/${e}`,params:{sender:Qs.state.activeCaipAddress?He.getPlainAddress(Qs.state.activeCaipAddress):void 0}});return We.updateIdentityCache({address:e,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:e,cursor:t,signal:s,cache:n,chainId:r}){if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};const i=We.getTransactionsCacheForAddress({address:e,chainId:r});if(i)return i;const o=await Mt.get({path:`/v1/account/${e}/history`,params:{cursor:t,chainId:r},signal:s,cache:n});return We.updateTransactionsCache({address:e,chainId:r,timestamp:Date.now(),transactions:o}),o},fetchSwapQuote:async({amount:e,userAddress:t,from:s,to:n,gasPrice:r})=>await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId)?Mt.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:e,userAddress:t,from:s,to:n,gasPrice:r}}):{quotes:[]},fetchSwapTokens:async({chainId:e})=>await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId)?Mt.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]},getAddressBalance:async({caipNetworkId:e,address:t,method:s="getAddressBalance",params:n})=>Dt.api.post({path:`/v1?chainId=${e}&projectId=${kt.state.projectId}`,body:{id:"1",jsonrpc:"2.0",method:s,params:n??{address:t}}}).then((e=>e.result)),async fetchTokenPrice({addresses:e,caipNetworkId:t=Qs.state.activeCaipNetwork?.caipNetworkId}){if(!await Mt.isNetworkSupported(t))return{fungibles:[]};const s=We.getTokenPriceCacheForAddresses(e);if(s)return s;const n=await Dt.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:kt.state.projectId},headers:{"Content-Type":"application/json"}});return We.updateTokenPriceCache({addresses:e,timestamp:Date.now(),tokenPrice:n}),n},fetchSwapAllowance:async({tokenAddress:e,userAddress:t})=>await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId)?Mt.get({path:"/v1/convert/allowance",params:{tokenAddress:e,userAddress:t},headers:{"Content-Type":"application/json"}}):{allowance:"0"},async fetchGasPrice({chainId:e}){const{st:t,sv:s}=Mt.getSdkProperties();if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return Mt.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:e,st:t,sv:s}})},async generateSwapCalldata({amount:e,from:t,to:s,userAddress:n,disableEstimate:r}){if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return Dt.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:qe.CONVERT_SLIPPAGE_TOLERANCE},projectId:kt.state.projectId,from:t,to:s,userAddress:n,disableEstimate:r}})},async generateApproveCalldata({from:e,to:t,userAddress:s}){const{st:n,sv:r}=Mt.getSdkProperties();if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return Mt.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:e,to:t,st:n,sv:r}})},async getBalance(e,t,s){const{st:n,sv:r}=Mt.getSdkProperties();if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))return Rt.showError("Token Balance Unavailable"),{balances:[]};const i=`${t}:${e}`,o=We.getBalanceCacheForCaipAddress(i);if(o)return o;const a=await Mt.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:s,st:n,sv:r}});return We.updateBalanceCache({caipAddress:i,balance:a,timestamp:Date.now()}),a},lookupEnsName:async e=>await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId)?Mt.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]},async reverseLookupEnsName({address:e}){if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))return[];const t=Qs.getAccountData()?.address;return Mt.get({path:`/v1/profile/reverse/${e}`,params:{sender:t,apiVersion:"2"}})},getEnsNameSuggestions:async e=>await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId)?Mt.get({path:`/v1/profile/suggestions/${e}`,params:{zone:"reown.id"}}):{suggestions:[]},registerEnsName:async({coinType:e,address:t,message:s,signature:n})=>await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId)?Dt.api.post({path:"/v1/profile/account",body:{coin_type:e,address:t,message:s,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1},async generateOnRampURL({destinationWallets:e,partnerUserId:t,defaultNetwork:s,purchaseAmount:n,paymentAmount:r}){if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))return"";return(await Dt.api.post({path:"/v1/generators/onrampurl",params:{projectId:kt.state.projectId},body:{destinationWallets:e,defaultNetwork:s,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:r}})).url},async getOnrampOptions(){if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await Mt.get({path:"/v1/onramp/options"})}catch(e){return Ut}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:s,network:n}){try{if(!await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId))return null;return await Dt.api.post({path:"/v1/onramp/quote",params:{projectId:kt.state.projectId},body:{purchaseCurrency:e,paymentCurrency:t,amount:s,network:n}})}catch(e){return{networkFee:{amount:s,currency:t.id},paymentSubtotal:{amount:s,currency:t.id},paymentTotal:{amount:s,currency:t.id},purchaseAmount:{amount:s,currency:t.id},quoteId:"mocked-quote-id"}}},getSmartSessions:async e=>await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId)?Mt.get({path:`/v1/sessions/${e}`}):[],revokeSmartSession:async(e,t,s)=>await Mt.isNetworkSupported(Qs.state.activeCaipNetwork?.caipNetworkId)?Dt.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:kt.state.projectId},body:{pci:t,signature:s}}):{success:!1},setClientId(e){Dt.clientId=e,Dt.api=new _t({baseUrl:Lt,clientId:e})}},Bt=Object.freeze({enabled:!0,events:[]}),jt=new _t({baseUrl:He.getAnalyticsUrl(),clientId:null}),$t=xe({...Bt}),Ft={state:$t,subscribeKey:(e,t)=>De($t,e,t),async sendError(e,t){if(!$t.enabled)return;const s=Date.now();if($t.events.filter((e=>{const t=new Date(e.properties.timestamp||"").getTime();return s-t<6e4})).length>=5)return;const n={type:"error",event:t,properties:{errorType:e.name,errorMessage:e.message,stackTrace:e.stack,timestamp:(new Date).toISOString()}};$t.events.push(n);try{if("undefined"==typeof window)return;const{projectId:s,sdkType:n,sdkVersion:r}=kt.state;await jt.post({path:"/e",params:{projectId:s,st:n,sv:r||"html-wagmi-4.2.2"},body:{eventId:He.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:(new Date).toISOString(),props:{type:"error",event:t,errorType:e.name,errorMessage:e.message,stackTrace:e.stack}}})}catch{}},enable(){$t.enabled=!0},disable(){$t.enabled=!1},clearEvents(){$t.events=[]}};class qt extends Error{constructor(e,t,s){super(e),this.originalName="AppKitError",this.name="AppKitError",this.category=t,this.originalError=s,s&&s instanceof Error&&(this.originalName=s.name),Object.setPrototypeOf(this,qt.prototype);let n=!1;if(s instanceof Error&&"string"==typeof s.stack&&s.stack){const e=s.stack,t=e.indexOf("\n");if(t>-1){const s=e.substring(t+1);this.stack=`${this.name}: ${this.message}\n${s}`,n=!0}}n||(Error.captureStackTrace?Error.captureStackTrace(this,qt):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Wt(e,t){let s="";try{s=e instanceof Error?e.message:"string"==typeof e?e:"object"==typeof e&&null!==e?0===Object.keys(e).length?"Unknown error":e?.message||JSON.stringify(e):String(e)}catch(e){s="Unknown error",console.error("Error parsing error message",e)}const n=e instanceof qt?e:new qt(s,t,e);throw Ft.sendError(n,n.category),n}function Ht(e,t="INTERNAL_SDK_ERROR"){const s={};return Object.keys(e).forEach((n=>{const r=e[n];if("function"==typeof r){let e=r;e="AsyncFunction"===r.constructor.name?async(...e)=>{try{return await r(...e)}catch(e){return Wt(e,t)}}:(...e)=>{try{return r(...e)}catch(e){return Wt(e,t)}},s[n]=e}else s[n]=r})),s}const zt=xe({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Vt=Ht({state:zt,subscribeNetworkImages:e=>Re(zt.networkImages,(()=>e(zt.networkImages))),subscribeKey:(e,t)=>De(zt,e,t),subscribe:e=>Re(zt,(()=>e(zt))),setWalletImage(e,t){zt.walletImages[e]=t},setNetworkImage(e,t){zt.networkImages[e]=t},setChainImage(e,t){zt.chainImages[e]=t},setConnectorImage(e,t){zt.connectorImages={...zt.connectorImages,[e]:t}},setTokenImage(e,t){zt.tokenImages[e]=t},setCurrencyImage(e,t){zt.currencyImages[e]=t}}),Kt={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:"",ton:"20f673c0-095e-49b2-07cf-eb5049dcf600",tron:"3502bb86-cc4e-420f-a387-59ea63a28b00"},Gt=xe({networkImagePromises:{},tokenImagePromises:{}}),Jt={async fetchWalletImage(e){if(e)return await os._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;const t=this.getNetworkImageById(e);return t||(Gt.networkImagePromises[e]||(Gt.networkImagePromises[e]=os._fetchNetworkImage(e)),await Gt.networkImagePromises[e],this.getNetworkImageById(e))},async fetchTokenImage(e){if(e)return Gt.tokenImagePromises[e]||(Gt.tokenImagePromises[e]=os._fetchTokenImage(e)),await Gt.tokenImagePromises[e],this.getTokenImage(e)},getWalletImageById(e){if(e)return Vt.state.walletImages[e]},getWalletImage:e=>e?.image_url?e?.image_url:e?.image_id?Vt.state.walletImages[e.image_id]:void 0,getNetworkImage:e=>e?.assets?.imageUrl?e?.assets?.imageUrl:e?.assets?.imageId?Vt.state.networkImages[e.assets.imageId]:void 0,getNetworkImageById(e){if(e)return Vt.state.networkImages[e]},getConnectorImage:e=>e?.imageUrl?e.imageUrl:e?.info?.icon?e.info.icon:e?.imageId?Vt.state.connectorImages[e.imageId]:void 0,getChainImage:e=>Vt.state.networkImages[Kt[e]],getTokenImage(e){if(e)return Vt.state.tokenImages[e]},getWalletImageUrl(e){if(!e)return"";const{projectId:t,sdkType:s,sdkVersion:n}=kt.state,r=new URL(`${B.W3M_API_URL}/getWalletImage/${e}`);return r.searchParams.set("projectId",t),r.searchParams.set("st",s),r.searchParams.set("sv",n),r.toString()},getAssetImageUrl(e){if(!e)return"";const{projectId:t,sdkType:s,sdkVersion:n}=kt.state,r=new URL(`${B.W3M_API_URL}/public/getAssetImage/${e}`);return r.searchParams.set("projectId",t),r.searchParams.set("st",s),r.searchParams.set("sv",n),r.toString()},getChainNamespaceImageUrl(e){return this.getAssetImageUrl(Kt[e])},async getImageByToken(e,t){if("native"===e){const e=B.NATIVE_IMAGE_IDS_BY_NAMESPACE[t]??null;if(!e)return;return Jt.fetchNetworkImage(e)}const[,s]=Object.entries(B.TOKEN_SYMBOLS_BY_ADDRESS).find((([t])=>t.toLowerCase()===e.toLowerCase()))??[];if(s)return Jt.fetchTokenImage(s)}},Yt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app",androidPackage:"app.phantom"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com",evmDeeplink:"cbwallet://miniapp"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},Xt={isCustomDeeplinkWallet:(e,t)=>e===Yt.PHANTOM.id?t===B.CHAIN.SOLANA||t===B.CHAIN.EVM||t===B.CHAIN.BITCOIN:e===Yt.SOLFLARE.id?t===B.CHAIN.SOLANA:e===Yt.COINBASE.id?t===B.CHAIN.SOLANA||t===B.CHAIN.EVM:e===Yt.BINANCE.id&&t===B.CHAIN.BITCOIN,handleMobileDeeplinkRedirect(e,t,s){const n=window.location.href,r=encodeURIComponent(n),i=s?.isCoinbaseDisabled??!1;if(e===Yt.PHANTOM.id&&!("phantom"in window)){const e=n.startsWith("https")?"https":"http",t=n.split("/")[2],s=encodeURIComponent(`${e}://${t}`),i=`${Yt.PHANTOM.url}/ul/browse/${r}?ref=${s}`;if(He.isAndroid()){const e=`intent://browse/${r}?ref=${s}#Intent;scheme=phantom;package=${Yt.PHANTOM.androidPackage};end`;window.location.href=e}else window.location.href=i}if(e!==Yt.SOLFLARE.id||t!==B.CHAIN.SOLANA||"solflare"in window||(window.location.href=`${Yt.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),t===B.CHAIN.SOLANA&&(e!==Yt.COINBASE.id||!i&&"coinbaseSolana"in window||(window.location.href=`${Yt.COINBASE.url}/dapp?cb_url=${r}`)),t===B.CHAIN.EVM&&(e!==Yt.COINBASE.id||!i&&"coinbaseWalletExtension"in window||(window.location.href=`${Yt.COINBASE.evmDeeplink}?url=${r}`)),t===B.CHAIN.BITCOIN&&e===Yt.BINANCE.id&&!("binancew3w"in window)){const e=Qs.state.activeCaipNetwork,t=window.btoa("/pages/browser/index"),s=window.btoa(`url=${r}&defaultChainId=${e?.id??1}`),n=new URL(Yt.BINANCE.deeplink);n.searchParams.set("appId",Yt.BINANCE.appId),n.searchParams.set("startPagePath",t),n.searchParams.set("startPageQuery",s);const i=new URL(Yt.BINANCE.url);i.searchParams.set("_dp",window.btoa(n.toString())),window.location.href=i.toString()}}},Zt=He.getAnalyticsUrl(),Qt=new _t({baseUrl:Zt,clientId:null}),es=["MODAL_CREATED"],ts=xe({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),ss={state:ts,subscribe:e=>Re(ts,(()=>e(ts))),getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=kt.state;return{projectId:e,st:t,sv:s||"html-wagmi-4.2.2"}},shouldFlushEvents(){const e=JSON.stringify(ts.pendingEvents).length/1024>45,t=ts.lastFlush+1e4<Date.now();return e||t},_setPendingEvent(e){try{let t=Qs.getAccountData()?.address;if("address"in e.data&&e.data.address&&(t=e.data.address),es.includes(e.data.event)||"undefined"==typeof window)return;const s=Qs.getActiveCaipNetwork()?.caipNetworkId;this.state.pendingEvents.push({eventId:He.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:e.timestamp,props:{...e.data,address:t,properties:{..."properties"in e.data?e.data.properties:{},caipNetworkId:s}}}),ts.reportedErrors.FORBIDDEN=!1;ss.shouldFlushEvents()&&ss._submitPendingEvents()}catch(e){console.warn("_setPendingEvent",e)}},sendEvent(e){ts.timestamp=Date.now(),ts.data=e;(kt.state.features?.analytics||["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"].includes(e.event))&&ss._setPendingEvent(ts),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(e){ts.walletImpressions.push(e)},_transformPendingEventsForBatch(e){try{return e.filter((e=>"WALLET_IMPRESSION_V2"!==e.props.event))}catch{return e}},_submitPendingEvents(){if(ts.lastFlush=Date.now(),0!==ts.pendingEvents.length||0!==ts.walletImpressions.length)try{const e=ss._transformPendingEventsForBatch(ts.pendingEvents);ts.walletImpressions.length&&e.push({eventId:He.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...ts.walletImpressions]}}),Qt.sendBeacon({path:"/batch",params:ss.getSdkProperties(),body:e}),ts.reportedErrors.FORBIDDEN=!1,ts.pendingEvents=[],ts.walletImpressions=[]}catch(e){ts.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){ts.subscribedToVisibilityChange||"undefined"!=typeof document&&(ts.subscribedToVisibilityChange=!0,document?.addEventListener?.("visibilitychange",(()=>{"hidden"===document.visibilityState&&ss._submitPendingEvents()})),document?.addEventListener?.("freeze",(()=>{ss._submitPendingEvents()})),window?.addEventListener?.("pagehide",(()=>{ss._submitPendingEvents()})),setInterval((()=>{ss._submitPendingEvents()}),1e4))}},ns=He.getApiUrl(),rs=new _t({baseUrl:ns,clientId:null}),is=xe({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[],plan:{tier:"none",hasExceededUsageLimit:!1,limits:{isAboveRpcLimit:!1,isAboveMauLimit:!1}}}),os={state:is,subscribeKey:(e,t)=>De(is,e,t),_getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=kt.state;return{projectId:e,st:t||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions:e=>kt.state.isUniversalProvider?e.filter((e=>Boolean(e.mobile_link||e.desktop_link||e.webapp_link))):e,async _fetchWalletImage(e){const t=`${rs.baseUrl}/getWalletImage/${e}`,s=await rs.getBlob({path:t,params:os._getSdkProperties()});Vt.setWalletImage(e,URL.createObjectURL(s))},async _fetchNetworkImage(e){const t=`${rs.baseUrl}/public/getAssetImage/${e}`,s=await rs.getBlob({path:t,params:os._getSdkProperties()});Vt.setNetworkImage(e,URL.createObjectURL(s))},async _fetchConnectorImage(e){const t=`${rs.baseUrl}/public/getAssetImage/${e}`,s=await rs.getBlob({path:t,params:os._getSdkProperties()});Vt.setConnectorImage(e,URL.createObjectURL(s))},async _fetchCurrencyImage(e){const t=`${rs.baseUrl}/public/getCurrencyImage/${e}`,s=await rs.getBlob({path:t,params:os._getSdkProperties()});Vt.setCurrencyImage(e,URL.createObjectURL(s))},async _fetchTokenImage(e){const t=`${rs.baseUrl}/public/getTokenImage/${e}`,s=await rs.getBlob({path:t,params:os._getSdkProperties()});Vt.setTokenImage(e,URL.createObjectURL(s))},_filterWalletsByPlatform(e){const t=e.length,s=He.isMobile()?e?.filter((e=>{if(e.mobile_link||e.webapp_link)return!0;return Object.values(Yt).map((e=>e.id)).includes(e.id)})):e;return{filteredWallets:s,mobileFilteredOutWalletsLength:t-s.length}},fetchProjectConfig:async()=>(await rs.get({path:"/appkit/v1/config",params:os._getSdkProperties()})).features,async fetchUsage(){try{const e=await rs.get({path:"/appkit/v1/project-limits",params:os._getSdkProperties()}),{tier:t,isAboveMauLimit:s,isAboveRpcLimit:n}=e.planLimits,r="starter"===t,i=s||n;os.state.plan={tier:t,hasExceededUsageLimit:r&&i,limits:{isAboveRpcLimit:n,isAboveMauLimit:s}}}catch(e){console.warn("Failed to fetch usage",e)}},async fetchAllowedOrigins(){try{const{allowedOrigins:e}=await rs.get({path:"/projects/v1/origins",params:os._getSdkProperties()});return e}catch(e){if(e instanceof Error&&e.cause instanceof Response){const t=e.cause.status;if(t===B.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:e});if(t>=B.HTTP_STATUS_CODES.SERVER_ERROR&&t<600)throw new Error("SERVER_ERROR",{cause:e});return[]}return[]}},async fetchNetworkImages(){const e=Qs.getAllRequestedCaipNetworks(),t=e?.map((({assets:e})=>e?.imageId)).filter(Boolean).filter((e=>!Jt.getNetworkImageById(e)));t&&await Promise.allSettled(t.map((e=>os._fetchNetworkImage(e))))},async fetchConnectorImages(){const{connectors:e}=bs.state,t=e.map((({imageId:e})=>e)).filter(Boolean);await Promise.allSettled(t.map((e=>os._fetchConnectorImage(e))))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map((e=>os._fetchCurrencyImage(e))))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map((e=>os._fetchTokenImage(e))))},async fetchWallets(e){const t=e.exclude??[];os._getSdkProperties().sv.startsWith("html-core-")&&t.push(...Object.values(Yt).map((e=>e.id)));const s=await rs.get({path:"/getWallets",params:{...os._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:e.include?.join(","),exclude:t.join(",")}}),{filteredWallets:n,mobileFilteredOutWalletsLength:r}=os._filterWalletsByPlatform(s?.data);return{data:n||[],count:s?.count,mobileFilteredOutWalletsLength:r}},async prefetchWalletRanks(){const e=bs.state.connectors;if(!e?.length)return;const t={page:1,entries:20,badge:"certified"};if(t.names=e.map((e=>e.name)).join(","),Qs.state.activeChain===B.CHAIN.EVM){const s=[...e.flatMap((e=>e.connectors?.map((e=>e.info?.rdns))||[])),...e.map((e=>e.info?.rdns))].filter((e=>"string"==typeof e&&e.length>0));s.length&&(t.rdns=s.join(","))}const{data:s}=await os.fetchWallets(t);is.explorerWallets=s,bs.extendConnectorsWithExplorerWallets(s);const n=Qs.getRequestedCaipNetworkIds().join(",");is.explorerFilteredWallets=s.filter((e=>e.chains?.some((e=>n.includes(e)))))},async fetchFeaturedWallets(){const{featuredWalletIds:e}=kt.state;if(e?.length){const t={...os._getSdkProperties(),page:1,entries:e?.length??4,include:e},{data:s}=await os.fetchWallets(t),n=[...s].sort(((t,s)=>e.indexOf(t.id)-e.indexOf(s.id))),r=n.map((e=>e.image_id)).filter(Boolean);await Promise.allSettled(r.map((e=>os._fetchWalletImage(e)))),is.featured=n,is.allFeatured=n}},async fetchRecommendedWallets(){try{is.isFetchingRecommendedWallets=!0;const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:s}=kt.state,n=[...t??[],...s??[]].filter(Boolean),r={page:1,entries:4,include:e,exclude:n,chains:Qs.getRequestedCaipNetworkIds().join(",")},{data:i,count:o}=await os.fetchWallets(r),a=We.getRecentWallets(),c=i.map((e=>e.image_id)).filter(Boolean),l=a.map((e=>e.image_id)).filter(Boolean);await Promise.allSettled([...c,...l].map((e=>os._fetchWalletImage(e)))),is.recommended=i,is.allRecommended=i,is.count=o??0}catch{}finally{is.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e,entries:t,badge:s,include:n,exclude:r}){const{includeWalletIds:i,excludeWalletIds:o,featuredWalletIds:a}=kt.state,c=Qs.getRequestedCaipNetworkIds().join(","),l=[...is.recommended.map((({id:e})=>e)),...o??[],...a??[]].filter(Boolean),d={page:e,entries:t??40,include:n??i,exclude:r??l,badge_type:s,chains:c},{data:h,count:u,mobileFilteredOutWalletsLength:p}=await os.fetchWallets(d);is.mobileFilteredOutWalletsLength=p+(is.mobileFilteredOutWalletsLength??0);const f=h.slice(0,20).map((e=>e.image_id)).filter(Boolean);await Promise.allSettled(f.map((e=>os._fetchWalletImage(e)))),is.wallets=He.uniqueBy([...is.wallets,...os._filterOutExtensions(h)],"id").filter((e=>e.chains?.some((e=>c.includes(e))))),is.count=u>is.count?u:is.count,is.page=e},async initializeExcludedWallets({ids:e}){const t={page:1,entries:e.length,include:e},{data:s}=await os.fetchWallets(t);s&&s.forEach((e=>{is.excludedWallets.push({rdns:e.rdns,name:e.name})}))},async searchWallet({search:e,badge:t,entries:s,page:n,include:r,exclude:i}){const{includeWalletIds:o,excludeWalletIds:a}=kt.state,c=Qs.getRequestedCaipNetworkIds().join(",");is.search=[];const l={page:n??1,entries:s??100,search:e?.trim(),badge_type:t,include:r??o,exclude:i??a,chains:c},{data:d}=await os.fetchWallets(l);ss.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:t??"",search:e??""}});const h=d.map((e=>e.image_id)).filter(Boolean);await Promise.allSettled([...h.map((e=>os._fetchWalletImage(e))),He.wait(300)]),is.search=os._filterOutExtensions(d)},initPromise(e,t){const s=is.promises[e];return s||(is.promises[e]=t())},prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:n=!0,fetchWalletRanks:r=!0}={}){const i=[e&&os.initPromise("connectorImages",os.fetchConnectorImages),t&&os.initPromise("featuredWallets",os.fetchFeaturedWallets),s&&os.initPromise("recommendedWallets",os.fetchRecommendedWallets),n&&os.initPromise("networkImages",os.fetchNetworkImages),r&&os.initPromise("walletRanks",os.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){kt.state.features?.analytics&&os.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:e}=await rs.get({path:"/getAnalyticsConfig",params:os._getSdkProperties()});kt.setFeatures({analytics:e})}catch(e){kt.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!e?.length)return is.featured=is.allFeatured,void(is.recommended=is.allRecommended);const t=Qs.getRequestedCaipNetworkIds().join(",");is.featured=is.allFeatured.filter((e=>e.chains?.some((e=>t.includes(e))))),is.recommended=is.allRecommended.filter((e=>e.chains?.some((e=>t.includes(e))))),is.filteredWallets=is.wallets.filter((e=>e.chains?.some((e=>t.includes(e)))))},clearFilterByNamespaces(){is.filteredWallets=[]},setFilterByNamespace(e){if(!e)return is.featured=is.allFeatured,void(is.recommended=is.allRecommended);const t=Qs.getRequestedCaipNetworkIds().join(",");is.featured=is.allFeatured.filter((e=>e.chains?.some((e=>t.includes(e))))),is.recommended=is.allRecommended.filter((e=>e.chains?.some((e=>t.includes(e))))),is.filteredWallets=is.wallets.filter((e=>e.chains?.some((e=>t.includes(e)))))}},as={filterOutDuplicatesByRDNS(e){const t=kt.state.enableEIP6963?bs.state.connectors:[],s=We.getRecentWallets(),n=t.map((e=>e.info?.rdns)).filter(Boolean),r=s.map((e=>e.rdns)).filter(Boolean),i=n.concat(r);if(i.includes("io.metamask.mobile")&&He.isMobile()){const e=i.indexOf("io.metamask.mobile");i[e]="io.metamask"}return e.filter((e=>{if(e?.rdns&&i.includes(String(e.rdns)))return!1;if(!e?.rdns){if(t.some((t=>t.name===e.name)))return!1}return!0}))},filterOutDuplicatesByIds(e){const t=bs.state.connectors.filter((e=>"ANNOUNCED"===e.type||"INJECTED"===e.type||"MULTI_CHAIN"===e.type)),s=We.getRecentWallets(),n=t.map((e=>e.explorerId||e.explorerWallet?.id||e.id)),r=s.map((e=>e.id)),i=n.concat(r);return e.filter((e=>!i.includes(e?.id)))},filterOutDuplicateWallets(e){const t=this.filterOutDuplicatesByRDNS(e);return this.filterOutDuplicatesByIds(t)},markWalletsAsInstalled(e){const{connectors:t}=bs.state,{featuredWalletIds:s}=kt.state,n=t.filter((e=>"ANNOUNCED"===e.type)).reduce(((e,t)=>t.info?.rdns?(e[t.info.rdns]=!0,e):e),{});return e.map((e=>({...e,installed:Boolean(e.rdns)&&Boolean(n[e.rdns??""])}))).sort(((e,t)=>{const n=Number(t.installed)-Number(e.installed);if(0!==n)return n;if(s?.length){const n=s.indexOf(e.id),r=s.indexOf(t.id);if(-1!==n&&-1!==r)return n-r;if(-1!==n)return-1;if(-1!==r)return 1}return 0}))},getConnectOrderMethod(e,t){const s=e?.connectMethodsOrder||kt.state.features?.connectMethodsOrder,n=t||bs.state.connectors;if(s)return s;const{injected:r,announced:i}=cs.getConnectorsByType(n,os.state.recommended,os.state.featured),o=r.filter(cs.showConnector),a=i.filter(cs.showConnector);return o.length||a.length?["wallet","email","social"]:qe.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){const t=Boolean(e.rdns)&&os.state.excludedWallets.some((t=>t.rdns===e.rdns)),s=Boolean(e.name)&&os.state.excludedWallets.some((t=>M.isLowerCaseMatch(t.name,e.name)));return t||s},markWalletsWithDisplayIndex:e=>e.map(((e,t)=>({...e,display_index:t}))),filterWalletsByWcSupport:e=>Us.state.wcBasic?e.filter((e=>e.supports_wc)):He.isMobile()?e.filter((e=>e.supports_wc||qe.MANDATORY_WALLET_IDS_ON_MOBILE.includes(e.id))):e,getWalletConnectWallets(e){const t=[...os.state.featured,...os.state.recommended];os.state.filteredWallets?.length>0?t.push(...os.state.filteredWallets):t.push(...e);const s=He.uniqueBy(t,"id"),n=as.markWalletsAsInstalled(s),r=as.filterWalletsByWcSupport(n);return as.markWalletsWithDisplayIndex(r)}},cs={getConnectorsByType(e,t,s){const{customWallets:n}=kt.state,r=We.getRecentWallets(),i=as.filterOutDuplicateWallets(t),o=as.filterOutDuplicateWallets(s),a=e.filter((e=>"MULTI_CHAIN"===e.type)),c=e.filter((e=>"ANNOUNCED"===e.type)),l=e.filter((e=>"INJECTED"===e.type));return{custom:n,recent:r,external:e.filter((e=>"EXTERNAL"===e.type)),multiChain:a,announced:c,injected:l,recommended:i,featured:o}},showConnector(e){const t=e.info?.rdns,s=Boolean(t)&&os.state.excludedWallets.some((e=>Boolean(e.rdns)&&e.rdns===t)),n=Boolean(e.name)&&os.state.excludedWallets.some((t=>M.isLowerCaseMatch(t.name,e.name)));if("INJECTED"===e.type){if("Browser Wallet"===e.name){if(!He.isMobile())return!1;if(He.isMobile()&&!t&&!Us.checkInstalled())return!1}if(s||n)return!1}return"ANNOUNCED"!==e.type&&"EXTERNAL"!==e.type||!s&&!n},getIsConnectedWithWC(){const e=Array.from(Qs.state.chains.values()).some((e=>bs.getConnectorId(e.namespace)===B.CONNECTOR_ID.WALLET_CONNECT));return e},getConnectorTypeOrder({recommended:e,featured:t,custom:s,recent:n,announced:r,injected:i,multiChain:o,external:a,overriddenConnectors:c=kt.state.features?.connectorTypeOrder??[]}){const l=[{type:"walletConnect",isEnabled:!0},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...i,...r,...o].length>0},{type:"featured",isEnabled:t.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:e.length>0}].filter((e=>e.isEnabled)),d=new Set(l.map((e=>e.type))),h=c.filter((e=>d.has(e))).map((e=>({type:e,isEnabled:!0}))),u=l.filter((({type:e})=>!h.some((({type:t})=>t===e))));return Array.from(new Set([...h,...u].map((({type:e})=>e))))},sortConnectorsByExplorerWallet:e=>[...e].sort(((e,t)=>e.explorerWallet&&t.explorerWallet?(e.explorerWallet.order??0)-(t.explorerWallet.order??0):e.explorerWallet?-1:t.explorerWallet?1:0)),getPriority:e=>e.id===B.CONNECTOR_ID.BASE_ACCOUNT?0:e.id===B.CONNECTOR_ID.COINBASE||e.id===B.CONNECTOR_ID.COINBASE_SDK?1:2,sortConnectorsByPriority:e=>[...e].sort(((e,t)=>cs.getPriority(e)-cs.getPriority(t))),getAuthName:({email:e,socialUsername:t,socialProvider:s})=>t?s&&"discord"===s&&t.endsWith("0")?t.slice(0,-1):t:e.length>30?`${e.slice(0,-3)}...`:e,async fetchProviderData(e){try{if("Browser Wallet"===e.name&&!He.isMobile())return{accounts:[],chainId:void 0};if(e.id===B.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};const[t,s]=await Promise.all([e.provider?.request({method:"eth_accounts"}),e.provider?.request({method:"eth_chainId"}).then((e=>Number(e)))]);return{accounts:t,chainId:s}}catch(t){return console.warn(`Failed to fetch provider data for ${e.name}`,t),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(e){const t=We.getRecentWallets(),s=bs.state.connectors.map((e=>e.info?.rdns)).filter(Boolean),n=t.map((e=>e.rdns)).filter(Boolean),r=s.concat(n);if(r.includes("io.metamask.mobile")&&He.isMobile()){const e=r.indexOf("io.metamask.mobile");r[e]="io.metamask"}return e.filter((e=>!r.includes(String(e?.rdns))))},hasWalletConnector:e=>bs.state.connectors.some((t=>t.id===e.id||t.name===e.name)),isWalletCompatibleWithCurrentChain(e){const t=Qs.state.activeChain;return!t||!e.chains||e.chains.some((e=>{const s=e.split(":")[0];return t===s}))},getFilteredRecentWallets(){return We.getRecentWallets().filter((e=>!as.isExcluded(e))).filter((e=>!this.hasWalletConnector(e))).filter((e=>this.isWalletCompatibleWithCurrentChain(e)))},getCappedRecommendedWallets(e){const{connectors:t}=bs.state,{customWallets:s,featuredWalletIds:n}=kt.state,r=t.find((e=>"walletConnect"===e.id)),i=t.filter((e=>"INJECTED"===e.type||"ANNOUNCED"===e.type||"MULTI_CHAIN"===e.type));if(!r&&!i.length&&!s?.length)return[];const o=Ot.isEmailEnabled(),a=Ot.isSocialsEnabled(),c=i.filter((e=>"Browser Wallet"!==e.name&&"WalletConnect"!==e.name)),l=(n?.length||0)+(s?.length||0)+(c.length||0)+(o?1:0)+(a?1:0),d=Math.max(0,4-l);if(d<=0)return[];return as.filterOutDuplicateWallets(e).slice(0,d)},processConnectorsByType(e,t=!0){const s=cs.sortConnectorsByExplorerWallet([...e]);return t?s.filter(cs.showConnector):s},connectorList(){const e=cs.getConnectorsByType(bs.state.connectors,os.state.recommended,os.state.featured),t=this.processConnectorsByType(e.announced.filter((e=>"walletConnect"!==e.id))),s=this.processConnectorsByType(e.injected),n=this.processConnectorsByType(e.multiChain.filter((e=>"WalletConnect"!==e.name)),!1),r=e.custom,i=e.recent,o=this.processConnectorsByType(e.external.filter((e=>e.id!==B.CONNECTOR_ID.COINBASE_SDK&&e.id!==B.CONNECTOR_ID.BASE_ACCOUNT))),a=e.recommended,c=e.featured,l=cs.getConnectorTypeOrder({custom:r,recent:i,announced:t,injected:s,multiChain:n,recommended:a,featured:c,external:o}),d=bs.state.connectors.find((e=>"walletConnect"===e.id)),h=He.isMobile(),u=[];for(const e of l)switch(e){case"walletConnect":!h&&d&&u.push({kind:"connector",subtype:"walletConnect",connector:d});break;case"recent":cs.getFilteredRecentWallets().forEach((e=>u.push({kind:"wallet",subtype:"recent",wallet:e})));break;case"injected":n.forEach((e=>u.push({kind:"connector",subtype:"multiChain",connector:e}))),t.forEach((e=>u.push({kind:"connector",subtype:"announced",connector:e}))),s.forEach((e=>u.push({kind:"connector",subtype:"injected",connector:e})));break;case"featured":c.forEach((e=>u.push({kind:"wallet",subtype:"featured",wallet:e})));break;case"custom":cs.getFilteredCustomWallets(r??[]).forEach((e=>u.push({kind:"wallet",subtype:"custom",wallet:e})));break;case"external":o.forEach((e=>u.push({kind:"connector",subtype:"external",connector:e})));break;case"recommended":cs.getCappedRecommendedWallets(a).forEach((e=>u.push({kind:"wallet",subtype:"recommended",wallet:e})));break;default:console.warn(`Unknown connector type: ${e}`)}return u},hasInjectedConnectors:()=>bs.state.connectors.filter((e=>("INJECTED"===e.type||"ANNOUNCED"===e.type||"MULTI_CHAIN"===e.type)&&"Browser Wallet"!==e.name&&"WalletConnect"!==e.name)).length},ls=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],ds=xe({view:"Connect",history:["Connect"],transactionStack:[]}),hs=Ht({state:ds,subscribeKey:(e,t)=>De(ds,e,t),pushTransactionStack(e){ds.transactionStack.push(e)},popTransactionStack(e){const t=ds.transactionStack.pop();if(!t)return;const{onSuccess:s,onError:n,onCancel:r}=t;switch(e){case"success":s?.();break;case"error":n?.(),hs.goBack();break;case"cancel":r?.(),hs.goBack()}},push(e,t){let s=e,n=t;os.state.plan.hasExceededUsageLimit&&ls.includes(e)&&(s="UsageExceeded",n=void 0),s!==ds.view&&(ds.view=s,ds.history.push(s),ds.data=n)},reset(e,t){ds.view=e,ds.history=[e],ds.data=t},replace(e,t){ds.history.at(-1)===e||(ds.view=e,ds.history[ds.history.length-1]=e,ds.data=t)},goBack(){const e=Qs.state.activeCaipAddress,t="ConnectingFarcaster"===hs.state.view,s=!e&&t;if(ds.history.length>1){ds.history.pop();const[t]=ds.history.slice(-1);if(t){const s="Connect"===t;ds.view=e&&s?"Account":t}}else sn.close();ds.data?.wallet&&(ds.data.wallet=void 0),ds.data?.redirectView&&(ds.data.redirectView=void 0),setTimeout((()=>{if(s){Qs.setAccountProp("farcasterUrl",void 0,Qs.state.activeChain);const e=bs.getAuthConnector();e?.provider?.reload();const t=Ue(kt.state);e?.provider?.syncDappData?.({metadata:t.metadata,sdkVersion:t.sdkVersion,projectId:t.projectId,sdkType:t.sdkType})}}),100)},goBackToIndex(e){if(ds.history.length>1){ds.history=ds.history.slice(0,e+1);const[t]=ds.history.slice(-1);t&&(ds.view=t)}},goBackOrCloseModal(){hs.state.history.length>1?hs.goBack():sn.close()}}),us=xe({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),ps={state:us,subscribe:e=>Re(us,(()=>e(us))),setThemeMode(e){us.themeMode=e;try{const t=bs.getAuthConnector();if(t){const s=ps.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:s,w3mThemeVariables:fe(s,e)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(e){us.themeVariables={...us.themeVariables,...e};try{const e=bs.getAuthConnector();if(e){const t=ps.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:fe(us.themeVariables,us.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot:()=>Ue(us)},fs=Ht(ps),gs=Object.fromEntries($.map((e=>[e,void 0]))),ms=Object.fromEntries($.map((e=>[e,!0]))),ys=xe({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:gs,filterByNamespaceMap:ms}),ws={state:ys,subscribe:e=>Re(ys,(()=>{e(ys)})),subscribeKey:(e,t)=>De(ys,e,t),initialize(e){e.forEach((e=>{const t=We.getConnectedConnectorId(e);t&&bs.setConnectorId(t,e)}))},setActiveConnector(e){e&&(ys.activeConnector=Le(e))},setConnectors(e){e.filter((e=>!ys.allConnectors.some((t=>t.id===e.id&&bs.getConnectorName(t.name)===bs.getConnectorName(e.name)&&t.chain===e.chain)))).forEach((e=>{"MULTI_CHAIN"!==e.type&&ys.allConnectors.push(Le(e))}));const t=bs.getEnabledNamespaces(),s=bs.getEnabledConnectors(t);ys.connectors=bs.mergeMultiChainConnectors(s)},filterByNamespaces(e){Object.keys(ys.filterByNamespaceMap).forEach((e=>{ys.filterByNamespaceMap[e]=!1})),e.forEach((e=>{ys.filterByNamespaceMap[e]=!0})),bs.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){ys.filterByNamespaceMap[e]=t,bs.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const e=bs.getEnabledNamespaces(),t=bs.getEnabledConnectors(e),s=bs.areAllNamespacesEnabled();ys.connectors=bs.mergeMultiChainConnectors(t),s?os.clearFilterByNamespaces():os.filterByNamespaces(e)},getEnabledNamespaces:()=>Object.entries(ys.filterByNamespaceMap).filter((([e,t])=>t)).map((([e])=>e)),getEnabledConnectors:e=>ys.allConnectors.filter((t=>e.includes(t.chain))),areAllNamespacesEnabled:()=>Object.values(ys.filterByNamespaceMap).every((e=>e)),mergeMultiChainConnectors(e){const t=bs.generateConnectorMapByName(e),s=[];return t.forEach((e=>{const t=e[0],n=t?.id===B.CONNECTOR_ID.AUTH;e.length>1&&t?s.push({name:t.name,imageUrl:t.imageUrl,imageId:t.imageId,connectors:[...e],type:n?"AUTH":"MULTI_CHAIN",chain:"eip155",id:t?.id||""}):t&&s.push(t)})),s},generateConnectorMapByName(e){const t=new Map;return e.forEach((e=>{const{name:s}=e,n=bs.getConnectorName(s);if(!n)return;const r=t.get(n)||[],i=r.find((t=>t.chain===e.chain));i||r.push(e),t.set(n,r)})),t},getConnectorName(e){if(!e)return e;return{"Trust Wallet":"Trust"}[e]||e},getUniqueConnectorsByName(e){const t=[];return e.forEach((e=>{t.find((t=>t.chain===e.chain))||t.push(e)})),t},addConnector(e){if(e.id===B.CONNECTOR_ID.AUTH){const t=e,s=Ue(kt.state),n=fs.getSnapshot().themeMode,r=fs.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,projectId:s.projectId,sdkType:s.sdkType}),t?.provider?.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:fe(r,n)}),bs.setConnectors([e])}else bs.setConnectors([e])},getAuthConnector(e){const t=e||Qs.state.activeChain,s=ys.connectors.find((e=>e.id===B.CONNECTOR_ID.AUTH));if(s){if(s?.connectors?.length){const e=s.connectors.find((e=>e.chain===t));return e}return s}},getAnnouncedConnectorRdns:()=>ys.connectors.filter((e=>"ANNOUNCED"===e.type)).map((e=>e.info?.rdns)),getConnectorById:e=>cs.sortConnectorsByPriority(ys.allConnectors).find((t=>t.id===e)),getConnector({id:e,namespace:t}){const s=t||Qs.state.activeChain,n=ys.allConnectors.filter((e=>e.chain===s)),r=cs.sortConnectorsByPriority(n).find((t=>t.id===e||t.explorerId===e));return r},syncIfAuthConnector(e){if("AUTH"!==e.id)return;const t=e,s=Ue(kt.state),n=fs.getSnapshot().themeMode,r=fs.getSnapshot().themeVariables;t?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),t.provider.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:fe(r,n)})},getConnectorsByNamespace(e){const t=ys.allConnectors.filter((t=>t.chain===e));return bs.mergeMultiChainConnectors(t)},canSwitchToSmartAccount:e=>Qs.checkIfSmartAccountEnabled()&&Ns(e)===Ye.ACCOUNT_TYPES.EOA,selectWalletConnector(e){const t=hs.state.data?.redirectView,s=Qs.state.activeChain,n=s?bs.getConnector({id:e.id,namespace:s}):void 0;Xt.handleMobileDeeplinkRedirect(n?.explorerId||e.id,Qs.state.activeChain,{isCoinbaseDisabled:!1===kt.state.enableCoinbase}),n?hs.push("ConnectingExternal",{connector:n,wallet:e,redirectView:t}):hs.push("ConnectingWalletConnect",{wallet:e,redirectView:t})},getConnectors:e=>e?bs.getConnectorsByNamespace(e):bs.mergeMultiChainConnectors(ys.allConnectors),setFilterByNamespace(e){ys.filterByNamespace=e,ys.connectors=bs.getConnectors(e),os.setFilterByNamespace(e)},setConnectorId(e,t){e&&(ys.activeConnectorIds={...ys.activeConnectorIds,[t]:e},We.setConnectedConnectorId(t,e))},removeConnectorId(e){ys.activeConnectorIds={...ys.activeConnectorIds,[e]:void 0},We.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return ys.activeConnectorIds[e]},isConnected:e=>e?Boolean(ys.activeConnectorIds[e]):Object.values(ys.activeConnectorIds).some((e=>Boolean(e))),resetConnectorIds(){ys.activeConnectorIds={...gs}},extendConnectorsWithExplorerWallets(e){ys.allConnectors.forEach((t=>{const s=e.find((e=>e.id===t.id||e.rdns&&e.rdns===t.info?.rdns));s&&(t.explorerWallet=s)}));const t=bs.getEnabledNamespaces(),s=bs.getEnabledConnectors(t);ys.connectors=bs.mergeMultiChainConnectors(s)},async connect(e={}){const{namespace:t}=e;return bs.setFilterByNamespace(t),hs.push("Connect",{addWalletForNamespace:t}),new Promise(((e,s)=>{if(t){const n=Qs.subscribeChainProp("accountState",(t=>{t?.caipAddress&&(e({caipAddress:t?.caipAddress}),n())}),t),r=sn.subscribeKey("open",(e=>{e||(s(new Error("Modal closed")),r())}))}else{const t=Qs.subscribeKey("activeCaipAddress",(s=>{s&&(e({caipAddress:s}),t())})),n=sn.subscribeKey("open",(e=>{e||(s(new Error("Modal closed")),n())}))}}))}},bs=Ht(ws),vs={checkNamespaceConnectorId:(e,t)=>bs.getConnectorId(e)===t,isSocialProvider:e=>qe.DEFAULT_REMOTE_FEATURES.socials.includes(e),connectWalletConnect:({walletConnect:e,connector:t,closeModalOnConnect:s=!0,redirectViewOnModalClose:n="Connect",onOpen:r,onConnect:i})=>new Promise(((o,a)=>{if(e&&bs.setActiveConnector(t),r?.(He.isMobile()&&e),n){const e=sn.subscribeKey("open",(t=>{t||(hs.state.view!==n&&hs.replace(n),e(),a(new Error("Modal closed")))}))}const c=Qs.subscribeKey("activeCaipAddress",(e=>{e&&(i?.(),s&&sn.close(),c(),o(oe.parseCaipAddress(e)))}))})),connectExternal:e=>new Promise(((t,s)=>{const n=Qs.subscribeKey("activeCaipAddress",(e=>{e&&(sn.close(),n(),t(oe.parseCaipAddress(e)))}));Us.connectExternal(e,e.chain).catch((()=>{n(),s(new Error("Connection rejected"))}))})),connectSocial({social:e,namespace:t,closeModalOnConnect:s=!0,onOpenFarcaster:n,onConnect:r}){let i,o=!1,a=null;const c=t||Qs.state.activeChain,l=Qs.subscribeKey("activeCaipAddress",(e=>{e&&(s&&sn.close(),l())}));return new Promise(((t,s)=>{async function l(n){if(n.data?.resultUri)if(n.origin===B.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",l,!1);try{const r=bs.getAuthConnector(c);if(r&&!o){i&&i.close(),o=!0;const a=n.data.resultUri;ss.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:e}}),We.setConnectedSocialProvider(e),await Us.connectExternal({id:r.id,type:r.type,socialUri:a},r.chain);const c=Qs.state.activeCaipAddress;if(!c)return void s(new Error("Failed to connect"));t(oe.parseCaipAddress(c)),ss.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:e}})}}catch(t){ss.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:He.parseError(t)}}),s(new Error("Failed to connect"))}}else ss.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:"Untrusted Origin"}})}!async function(){if(ss.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:e}}),"farcaster"===e){n?.();const t=sn.subscribeKey("open",(n=>{n||"farcaster"!==e||(s(new Error("Popup closed")),r?.(),t())})),i=bs.getAuthConnector();if(i){const e=Qs.getAccountData(c);if(!e?.farcasterUrl)try{const{url:e}=await i.provider.getFarcasterUri();Qs.setAccountProp("farcasterUrl",e,c)}catch{s(new Error("Failed to connect to farcaster"))}}}else{const t=bs.getAuthConnector();a=He.returnOpenHref(`${B.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(t){const{uri:n}=await t.provider.getSocialRedirectUri({provider:e});if(a&&n){a.location.href=n,i=a;const e=setInterval((()=>{i?.closed&&!o&&(s(new Error("Popup closed")),clearInterval(e))}),1e3);window.addEventListener("message",l,!1)}else a?.close(),s(new Error("Failed to initiate social connection"))}}catch{s(new Error("Failed to initiate social connection")),a?.close()}}}()}))},connectEmail:({closeModalOnConnect:e=!0,redirectViewOnModalClose:t="Connect",onOpen:s,onConnect:n})=>new Promise(((r,i)=>{if(s?.(),t){const e=sn.subscribeKey("open",(s=>{s||(hs.state.view!==t&&hs.replace(t),e(),i(new Error("Modal closed")))}))}const o=Qs.subscribeKey("activeCaipAddress",(t=>{t&&(n?.(),e&&sn.close(),o(),r(oe.parseCaipAddress(t)))}))})),async updateEmail(){const e=We.getConnectedConnectorId(Qs.state.activeChain),t=bs.getAuthConnector();if(!t)throw new Error("No auth connector found");if(e!==B.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const s=t.provider.getEmail()??"";return await sn.open({view:"UpdateEmailWallet",data:{email:s,redirectView:void 0}}),new Promise(((e,n)=>{const r=setInterval((()=>{const n=t.provider.getEmail()??"";n!==s&&(sn.close(),clearInterval(r),i(),e({email:n}))}),1e3),i=sn.subscribeKey("open",(e=>{e||("Connect"!==hs.state.view&&hs.push("Connect"),clearInterval(r),i(),n(new Error("Modal closed")))}))}))},canSwitchToSmartAccount:e=>Qs.checkIfSmartAccountEnabled()&&Ns(e)===Ye.ACCOUNT_TYPES.EOA};function Es(){const e=Qs.state.activeCaipNetwork?.chainNamespace||"eip155";return`${e}:${Qs.state.activeCaipNetwork?.id||1}:${qe.NATIVE_TOKEN_ADDRESS[e]}`}function Cs(e){return qe.NATIVE_TOKEN_ADDRESS[e]}function Ns(e){const t=Qs.getAccountData(e)?.preferredAccountType;return t}function As(e){return e?Qs.state.chains.get(e)?.networkState?.caipNetwork:Qs.state.activeCaipNetwork}const Is={getConnectionStatus(e,t){const s=bs.state.activeConnectorIds[t],n=Us.getConnections(t);if(Boolean(s)&&e.connectorId===s)return"connected";const r=n.some((t=>t.connectorId.toLowerCase()===e.connectorId.toLowerCase()));return r?"active":"disconnected"},excludeConnectorAddressFromConnections:({connections:e,connectorId:t,addresses:s})=>e.map((e=>{if(!!t&&e.connectorId.toLowerCase()===t.toLowerCase()&&s){const t=e.accounts.filter((e=>!s.some((t=>t.toLowerCase()===e.address.toLowerCase()))));return{...e,accounts:t}}return e})),excludeExistingConnections(e,t){const s=new Set(e);return t.filter((e=>!s.has(e.connectorId)))},getConnectionsByConnectorId:(e,t)=>e.filter((e=>e.connectorId.toLowerCase()===t.toLowerCase())),getConnectionsData(e){const t=Boolean(kt.state.remoteFeatures?.multiWallet),s=bs.state.activeConnectorIds[e],n=Us.getConnections(e),r=(Us.state.recentConnections.get(e)??[]).filter((e=>bs.getConnectorById(e.connectorId))),i=Is.excludeExistingConnections([...n.map((e=>e.connectorId)),...s?[s]:[]],r);return t?{connections:n,recentConnections:i}:{connections:n.filter((e=>e.connectorId.toLowerCase()===s?.toLowerCase())),recentConnections:[]}},onConnectMobile(e,t){const s=Us.state.wcUri;if(e?.mobile_link&&s)try{Us.setWcError(!1);const{mobile_link:n,link_mode:r,name:i}=e,o=He.appendPayToUri(s,t),{redirect:a,redirectUniversalLink:c,href:l}=He.formatNativeUrl(n,o,r),d=a,h=c,u=He.isIframe()?"_top":"_self";Us.setWcLinking({name:i,href:l}),Us.setRecentWallet(e),kt.state.experimental_preferUniversalLinks&&h?He.openHref(h,u):He.openHref(d,u)}catch(t){ss.sendEvent({type:"track",event:"CONNECT_PROXY_ERROR",properties:{message:t instanceof Error?t.message:"Error parsing the deep link",uri:s,mobile_link:e.mobile_link,name:e.name}}),Us.setWcError(!0)}}},Ss=xe({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1,connectingWallet:void 0}),_s={state:Ss,subscribe:e=>Re(Ss,(()=>e(Ss))),subscribeOpen:e=>De(Ss,"open",e),set(e){Object.assign(Ss,{...Ss,...e})}},Os=xe({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Ts={state:Os,subscribe:e=>Re(Os,(()=>e(Os))),setLastNetworkInView(e){Os.lastNetworkInView=e},async fetchTransactions(e){if(!e)throw new Error("Transactions can't be fetched without an accountAddress");Os.loading=!0;try{const t=await Mt.fetchTransactions({account:e,cursor:Os.next,chainId:Qs.state.activeCaipNetwork?.caipNetworkId}),s=ks.filterSpamTransactions(t.data),n=ks.filterByConnectedChain(s),r=[...Os.transactions,...n];Os.loading=!1,Os.transactions=r,Os.transactionsByYear=ks.groupTransactionsByYearAndMonth(Os.transactionsByYear,n),Os.empty=0===r.length,Os.next=t.next?t.next:void 0}catch(t){const s=Qs.state.activeChain;ss.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:kt.state.projectId,cursor:Os.next,isSmartAccount:Ns(s)===Ye.ACCOUNT_TYPES.SMART_ACCOUNT}}),Rt.showError("Failed to fetch transactions"),Os.loading=!1,Os.empty=!0,Os.next=void 0}},groupTransactionsByYearAndMonth(e={},t=[]){const s=e;return t.forEach((e=>{const t=new Date(e.metadata.minedAt).getFullYear(),n=new Date(e.metadata.minedAt).getMonth(),r=s[t]??{},i=(r[n]??[]).filter((t=>t.id!==e.id));s[t]={...r,[n]:[...i,e].sort(((e,t)=>new Date(t.metadata.minedAt).getTime()-new Date(e.metadata.minedAt).getTime()))}})),s},filterSpamTransactions:e=>e.filter((e=>{const t=e.transfers?.every((e=>!0===e.nft_info?.flags.is_spam));return!t})),filterByConnectedChain(e){const t=Qs.state.activeCaipNetwork?.caipNetworkId;return e.filter((e=>e.metadata.chain===t))},clearCursor(){Os.next=void 0},resetTransactions(){Os.transactions=[],Os.transactionsByYear={},Os.lastNetworkInView=void 0,Os.loading=!1,Os.empty=!1,Os.next=void 0}},ks=Ht(Ts,"API_ERROR"),Ps=xe({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,wcFetchingUri:!1,buffering:!1,status:"disconnected"});let xs;const Rs={state:Ps,subscribe:e=>Re(Ps,(()=>e(Ps))),subscribeKey:(e,t)=>De(Ps,e,t),_getClient:()=>Ps._client,setClient(e){Ps._client=Le(e)},initialize(e){const t=e.filter((e=>Boolean(e.namespace))).map((e=>e.namespace));Us.syncStorageConnections(t)},syncStorageConnections(e){const t=We.getConnections(),s=e??Array.from(Qs.state.chains.keys());for(const e of s){const s=t[e]??[],n=new Map(Ps.recentConnections);n.set(e,s),Ps.recentConnections=n}},getConnections:e=>e?Ps.connections.get(e)??[]:[],hasAnyConnection(e){const t=Us.state.connections;return Array.from(t.values()).flatMap((e=>e)).some((({connectorId:t})=>t===e))},async connectWalletConnect({cache:e="auto"}={}){Ps.wcFetchingUri=!0;const t=He.isTelegram()||He.isSafari()&&He.isIos();try{if("always"===e||"auto"===e&&t){if(xs)return await xs,void(xs=void 0);if(!He.isPairingExpired(Ps?.wcPairingExpiry)){const e=Ps.wcUri;return void(Ps.wcUri=e)}xs=Us._getClient()?.connectWalletConnect?.(),Us.state.status="connecting",await xs,xs=void 0,Ps.wcPairingExpiry=void 0,Us.state.status="connected"}else await(Us._getClient()?.connectWalletConnect?.())}catch(e){throw Ps.wcError=!0,Ps.wcFetchingUri=!1,Ps.status="disconnected",xs=void 0,e}},async connectExternal(e,t,s=!0){const n=await(Us._getClient()?.connectExternal?.(e));s&&Qs.setActiveNamespace(t);const r=bs.state.allConnectors.find((t=>t.id===e?.id)),i="AUTH"===e.type?"email":"browser";return ss.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:i,name:r?.name||"Unknown",view:hs.state.view,walletRank:r?.explorerWallet?.order}}),n},async reconnectExternal(e){await(Us._getClient()?.reconnectExternal?.(e));const t=e.chain||Qs.state.activeChain;t&&bs.setConnectorId(e.id,t)},async setPreferredAccountType(e,t){if(!t)return;sn.setLoading(!0,Qs.state.activeChain);const s=bs.getAuthConnector();s&&(Qs.setAccountProp("preferredAccountType",e,t),await s.provider.setPreferredAccount(e),We.setPreferredAccountTypes(Object.entries(Qs.state.chains).reduce(((e,[t,s])=>{const n=t,r=Ns(n);return void 0!==r&&(e[n]=r),e}),{})),await Us.reconnectExternal(s),sn.setLoading(!1,Qs.state.activeChain),ss.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:Qs.state.activeCaipNetwork?.caipNetworkId||""}}))},signMessage:async e=>Us._getClient()?.signMessage(e),parseUnits:(e,t)=>Us._getClient()?.parseUnits(e,t),formatUnits:(e,t)=>Us._getClient()?.formatUnits(e,t),updateBalance:e=>Us._getClient()?.updateBalance(e),sendTransaction:async e=>Us._getClient()?.sendTransaction(e),getCapabilities:async e=>Us._getClient()?.getCapabilities(e),grantPermissions:async e=>Us._getClient()?.grantPermissions(e),walletGetAssets:async e=>Us._getClient()?.walletGetAssets(e)??{},estimateGas:async e=>Us._getClient()?.estimateGas(e),writeContract:async e=>Us._getClient()?.writeContract(e),writeSolanaTransaction:async e=>Us._getClient()?.writeSolanaTransaction(e),getEnsAddress:async e=>Us._getClient()?.getEnsAddress(e),getEnsAvatar:async e=>Us._getClient()?.getEnsAvatar(e),checkInstalled:e=>Us._getClient()?.checkInstalled?.(e)||!1,resetWcConnection(){Ps.wcUri=void 0,Ps.wcPairingExpiry=void 0,Ps.wcLinking=void 0,Ps.recentWallet=void 0,Ps.wcFetchingUri=!1,Ps.status="disconnected",ks.resetTransactions(),We.deleteWalletConnectDeepLink(),We.deleteRecentWallet(),_s.set({connectingWallet:void 0})},resetUri(){Ps.wcUri=void 0,Ps.wcPairingExpiry=void 0,xs=void 0,Ps.wcFetchingUri=!1,_s.set({connectingWallet:void 0})},finalizeWcConnection(e){const{wcLinking:t,recentWallet:s}=Us.state;t&&We.setWalletConnectDeepLink(t),s&&We.setAppKitRecent(s),e&&ss.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:t?"mobile":"qrcode",name:hs.state.data?.wallet?.name||"Unknown",view:hs.state.view,walletRank:s?.order}})},setWcBasic(e){Ps.wcBasic=e},setUri(e){Ps.wcUri=e,Ps.wcFetchingUri=!1,Ps.wcPairingExpiry=He.getPairingExpiry()},setWcLinking(e){Ps.wcLinking=e},setWcError(e){Ps.wcError=e,Ps.wcFetchingUri=!1,Ps.buffering=!1},setRecentWallet(e){Ps.recentWallet=e},setBuffering(e){Ps.buffering=e},setStatus(e){Ps.status=e},setIsSwitchingConnection(e){Ps.isSwitchingConnection=e},async disconnect({id:e,namespace:t,initialDisconnect:s}={}){try{await(Us._getClient()?.disconnect({id:e,chainNamespace:t,initialDisconnect:s}))}catch(e){throw new qt("Failed to disconnect","INTERNAL_SDK_ERROR",e)}},async disconnectConnector({id:e,namespace:t}){try{await(Us._getClient()?.disconnectConnector({id:e,namespace:t}))}catch(e){throw new qt("Failed to disconnect connector","INTERNAL_SDK_ERROR",e)}},setConnections(e,t){const s=new Map(Ps.connections);s.set(t,e),Ps.connections=s},async handleAuthAccountSwitch({address:e,namespace:t}){const s=Qs.getAccountData(t),n=s?.user?.accounts?.find((e=>"smartAccount"===e.type)),r=n&&n.address.toLowerCase()===e.toLowerCase()&&vs.canSwitchToSmartAccount(t)?"smartAccount":"eoa";await Us.setPreferredAccountType(r,t)},async handleActiveConnection({connection:e,namespace:t,address:s}){const n=bs.getConnectorById(e.connectorId),r=e.connectorId===B.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${e.connectorId}`);if(!r){const e=await Us.connectExternal({id:n.id,type:n.type,provider:n.provider,address:s,chain:t},t);return e?.address}return s&&await Us.handleAuthAccountSwitch({address:s,namespace:t}),s},async handleDisconnectedConnection({connection:e,namespace:t,address:s,closeModalOnConnect:n}){const r=bs.getConnectorById(e.connectorId),i=e.auth?.name?.toLowerCase(),o=e.connectorId===B.CONNECTOR_ID.AUTH,a=e.connectorId===B.CONNECTOR_ID.WALLET_CONNECT;if(!r)throw new Error(`No connector found for connection: ${e.connectorId}`);let c;if(o)if(i&&vs.isSocialProvider(i)){const{address:e}=await vs.connectSocial({social:i,closeModalOnConnect:n,onOpenFarcaster(){sn.open({view:"ConnectingFarcaster"})},onConnect(){hs.replace("ProfileWallets")}});c=e}else{const{address:e}=await vs.connectEmail({closeModalOnConnect:n,onOpen(){sn.open({view:"EmailLogin"})},onConnect(){hs.replace("ProfileWallets")}});c=e}else if(a){const{address:e}=await vs.connectWalletConnect({walletConnect:!0,connector:r,closeModalOnConnect:n,onOpen(e){const t=e?"AllWallets":"ConnectingWalletConnect";sn.state.open?hs.push(t):sn.open({view:t})},onConnect(){hs.replace("ProfileWallets")}});c=e}else{const e=await Us.connectExternal({id:r.id,type:r.type,provider:r.provider,chain:t},t);e&&(c=e.address)}return o&&s&&await Us.handleAuthAccountSwitch({address:s,namespace:t}),c},async switchConnection({connection:e,address:t,namespace:s,closeModalOnConnect:n,onChange:r}){let i;const o=Qs.getAccountData(s)?.caipAddress;if(o){const{address:e}=oe.parseCaipAddress(o);i=e}const a=Is.getConnectionStatus(e,s);switch(a){case"connected":case"active":{const n=await Us.handleActiveConnection({connection:e,namespace:s,address:t});if(i&&n){const e=n.toLowerCase()!==i.toLowerCase();r?.({address:n,namespace:s,hasSwitchedAccount:e,hasSwitchedWallet:"active"===a})}break}case"disconnected":{const i=await Us.handleDisconnectedConnection({connection:e,namespace:s,address:t,closeModalOnConnect:n});i&&r?.({address:i,namespace:s,hasSwitchedAccount:!0,hasSwitchedWallet:!0});break}default:throw new Error(`Invalid connection status: ${a}`)}}},Us=Ht(Rs),Ls={createBalance(e,t){const s={name:e.metadata.name||"",symbol:e.metadata.symbol||"",decimals:e.metadata.decimals||0,value:e.metadata.value||0,price:e.metadata.price||0,iconUrl:e.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:t,address:"native"===e.address?void 0:this.convertAddressToCAIP10Address(e.address,t),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:e.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance:({hex:e,decimals:t})=>It(BigInt(e),t),convertAddressToCAIP10Address:(e,t)=>`${t}:${e}`,createCAIP2ChainId:(e,t)=>`${t}:${parseInt(e,16)}`,getChainIdHexFromCAIP2ChainId(e){const t=e.split(":");if(t.length<2||!t[1])return"0x0";const s=t[1],n=parseInt(s,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(e){return"object"==typeof e&&null!==e&&Object.values(e).every((e=>Array.isArray(e)&&e.every((e=>this.isValidAsset(e)))))},isValidAsset:e=>"object"==typeof e&&null!==e&&"string"==typeof e.address&&"string"==typeof e.balance&&("ERC20"===e.type||"NATIVE"===e.type)&&"object"==typeof e.metadata&&null!==e.metadata&&"string"==typeof e.metadata.name&&"string"==typeof e.metadata.symbol&&"number"==typeof e.metadata.decimals&&"number"==typeof e.metadata.price&&"string"==typeof e.metadata.iconUrl};let Ds;async function Ms(){if(!Ds){const{createPublicClient:e,http:t,defineChain:s}=await import("./index-f095c09e.js");Ds={createPublicClient:e,http:t,defineChain:s}}return Ds}const Bs={getBlockchainApiRpcUrl(e,t){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",e),s.searchParams.set("projectId",t),s.toString()},async getViemChain(e){const{defineChain:t}=await Ms(),{chainId:s}=oe.parseCaipNetworkId(e.caipNetworkId);return t({...e,id:Number(s)})},async createViemPublicClient(e){const{createPublicClient:t,http:s}=await Ms(),n=kt.state.projectId,r=await Bs.getViemChain(e);if(!r)throw new Error(`Chain ${e.caipNetworkId} not found in viem/chains`);return t({chain:r,transport:s(Bs.getBlockchainApiRpcUrl(e.caipNetworkId,n))})}},js={async getMyTokensWithBalance(e={forceUpdate:void 0,caipNetwork:Qs.state.activeCaipNetwork,address:Qs.getAccountData()?.address}){const{forceUpdate:t,caipNetwork:s,address:n}=e,r=bs.getConnectorId("eip155")===B.CONNECTOR_ID.AUTH;if(!n)return[];const i=s?`${s.caipNetworkId}:${n}`:n,o=We.getBalanceCacheForCaipAddress(i);if(o)return o.balances;if(s&&s.chainNamespace===B.CHAIN.EVM&&r){const e=await this.getEIP155Balances(n,s);if(e)return this.filterLowQualityTokens(e)}const a=await Mt.getBalance(n,s?.caipNetworkId,t);return this.filterLowQualityTokens(a.balances)},async getEIP155Balances(e,t){try{const s=Ls.getChainIdHexFromCAIP2ChainId(t.caipNetworkId),n=await Us.getCapabilities(e);if(!n?.[s]?.assetDiscovery?.supported)return null;const r=await Us.walletGetAssets({account:e,chainFilter:[s]});if(!Ls.isWalletGetAssetsResponse(r))return null;const i=(r[s]||[]).map((e=>Ls.createBalance(e,t.caipNetworkId)));return We.updateBalanceCache({caipAddress:`${t.caipNetworkId}:${e}`,balance:{balances:i},timestamp:Date.now()}),i}catch(e){return null}},filterLowQualityTokens:e=>e.filter((e=>"0"!==e.quantity.decimals)),async fetchERC20Balance({caipAddress:e,assetAddress:t,caipNetwork:s}){const n=await Bs.createViemPublicClient(s),{address:r}=oe.parseCaipAddress(e),[{result:i},{result:o},{result:a},{result:c}]=await n.multicall({contracts:[{address:t,functionName:"name",args:[],abi:vt},{address:t,functionName:"symbol",args:[],abi:vt},{address:t,functionName:"balanceOf",args:[r],abi:vt},{address:t,functionName:"decimals",args:[],abi:vt}]});return{name:i,symbol:o,decimals:c,balance:a&&c?It(a,c):"0"}}},$s={adapters:{}},Fs={state:$s,initialize(e){$s.adapters={...e}},get:e=>$s.adapters[e]},qs={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0,ton:void 0,tron:void 0},Ws=xe({providers:{...qs},providerIds:{...qs}}),Hs={state:Ws,subscribeKey:(e,t)=>De(Ws,e,t),subscribe:e=>Re(Ws,(()=>{e(Ws)})),subscribeProviders:e=>Re(Ws.providers,(()=>e(Ws.providers))),setProvider(e,t){e&&t&&(Ws.providers[e]=Le(t))},getProvider(e){if(e)return Ws.providers[e]},setProviderId(e,t){t&&(Ws.providerIds[e]=t)},getProviderId(e){if(e)return Ws.providerIds[e]},reset(){Ws.providers={...qs},Ws.providerIds={...qs}},resetChain(e){Ws.providers[e]=void 0,Ws.providerIds[e]=void 0}},zs={async getTokenList(e){const t=await Mt.fetchSwapTokens({chainId:e});return t?.tokens?.map((e=>({...e,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0})))||[]},async fetchGasPrice(){const e=Qs.state.activeCaipNetwork;if(!e)return null;try{if("solana"===e.chainNamespace){const e=(await(Us?.estimateGas({chainNamespace:"solana"})))?.toString();return{standard:e,fast:e,instant:e}}return await Mt.fetchGasPrice({chainId:e.caipNetworkId})}catch{return null}},async fetchSwapAllowance({tokenAddress:e,userAddress:t,sourceTokenAmount:s,sourceTokenDecimals:n}){const r=await Mt.fetchSwapAllowance({tokenAddress:e,userAddress:t});if(r?.allowance&&s&&n){const e=Us.parseUnits(s,n)||0;return BigInt(r.allowance)>=e}return!1},async getMyTokensWithBalance(e){const t=await js.getMyTokensWithBalance({forceUpdate:e,caipNetwork:Qs.state.activeCaipNetwork,address:Qs.getAccountData()?.address});return Qs.setAccountProp("tokenBalance",t,Qs.state.activeChain),this.mapBalancesToSwapTokens(t)},mapBalancesToSwapTokens:e=>e?.map((e=>({...e,address:e?.address?e.address:Es(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[],async handleSwapError(e){try{const t=e?.cause;if(!t?.json)return;const s=await t.json(),n=s?.reasons?.[0]?.description;return n?.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}},Vs=xe({tokenBalances:[],loading:!1}),Ks={state:Vs,subscribe:e=>Re(Vs,(()=>e(Vs))),subscribeKey:(e,t)=>De(Vs,e,t),setToken(e){e&&(Vs.token=Le(e))},setTokenAmount(e){Vs.sendTokenAmount=e},setReceiverAddress(e){Vs.receiverAddress=e},setReceiverProfileImageUrl(e){Vs.receiverProfileImageUrl=e},setReceiverProfileName(e){Vs.receiverProfileName=e},setNetworkBalanceInUsd(e){Vs.networkBalanceInUSD=e},setLoading(e){Vs.loading=e},getSdkEventProperties:e=>({message:He.parseError(e),isSmartAccount:Ns(Qs.state.activeChain)===Ye.ACCOUNT_TYPES.SMART_ACCOUNT,token:Vs.token?.symbol||"",amount:Vs.sendTokenAmount??0,network:Qs.state.activeCaipNetwork?.caipNetworkId||""}),async sendToken(){try{switch(Gs.setLoading(!0),Qs.state.activeCaipNetwork?.chainNamespace){case"eip155":return void await Gs.sendEvmToken();case"solana":return void await Gs.sendSolanaToken();default:throw new Error("Unsupported chain")}}catch(e){if(ae.isUserRejectedRequestError(e))throw new le(e);throw e}finally{Gs.setLoading(!1)}},async sendEvmToken(){const e=Qs.state.activeChain;if(!e)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const t=Ns(e);if(!Gs.state.sendTokenAmount||!Gs.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!Gs.state.token)throw new Error("A token is required");if(Gs.state.token?.address){ss.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===Ye.ACCOUNT_TYPES.SMART_ACCOUNT,token:Gs.state.token.address,amount:Gs.state.sendTokenAmount,network:Qs.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:e}=await Gs.sendERC20Token({receiverAddress:Gs.state.receiverAddress,tokenAddress:Gs.state.token.address,sendTokenAmount:Gs.state.sendTokenAmount,decimals:Gs.state.token.quantity.decimals});e&&(Vs.hash=e)}else{ss.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===Ye.ACCOUNT_TYPES.SMART_ACCOUNT,token:Gs.state.token.symbol||"",amount:Gs.state.sendTokenAmount,network:Qs.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:e}=await Gs.sendNativeToken({receiverAddress:Gs.state.receiverAddress,sendTokenAmount:Gs.state.sendTokenAmount,decimals:Gs.state.token.quantity.decimals});e&&(Vs.hash=e)}},async fetchTokenBalance(e){Vs.loading=!0;const t=Qs.state.activeChain,s=Qs.state.activeCaipNetwork?.caipNetworkId,n=Qs.state.activeCaipNetwork?.chainNamespace,r=Qs.getAccountData(t)?.caipAddress??Qs.state.activeCaipAddress,i=r?He.getPlainAddress(r):void 0;if(Vs.lastRetry&&!He.isAllowedRetry(Vs.lastRetry,30*qe.ONE_SEC_MS))return Vs.loading=!1,[];try{if(i&&s&&n){const e=await js.getMyTokensWithBalance();return Vs.tokenBalances=e,Vs.lastRetry=void 0,e}}catch(t){Vs.lastRetry=Date.now(),e?.(t),Rt.showError("Token Balance Unavailable")}finally{Vs.loading=!1}return[]},fetchNetworkBalance(){if(0===Vs.tokenBalances.length)return;const e=zs.mapBalancesToSwapTokens(Vs.tokenBalances);if(!e)return;const t=e.find((e=>e.address===Es()));t&&(Vs.networkBalanceInUSD=t?ee.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){hs.pushTransactionStack({});const t=e.receiverAddress,s=Qs.getAccountData()?.address,n=Us.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),r=await Us.sendTransaction({chainNamespace:B.CHAIN.EVM,to:t,address:s,data:"0x",value:n??BigInt(0)});return ss.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Ns("eip155")===Ye.ACCOUNT_TYPES.SMART_ACCOUNT,token:Gs.state.token?.symbol||"",amount:e.sendTokenAmount,network:Qs.state.activeCaipNetwork?.caipNetworkId||"",hash:r||""}}),Us._getClient()?.updateBalance("eip155"),Gs.resetSend(),{hash:r}},async sendERC20Token(e){hs.pushTransactionStack({onSuccess(){hs.replace("Account")}});const t=Us.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),s=Qs.getAccountData()?.address;if(s&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){const n=He.getPlainAddress(e.tokenAddress);if(!n)throw new Error("SendController:sendERC20Token - tokenAddress is required");const r=await Us.writeContract({fromAddress:s,tokenAddress:n,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:re.getERC20Abi(n),chainNamespace:B.CHAIN.EVM});return ss.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Ns("eip155")===Ye.ACCOUNT_TYPES.SMART_ACCOUNT,token:Gs.state.token?.symbol||"",amount:e.sendTokenAmount,network:Qs.state.activeCaipNetwork?.caipNetworkId||"",hash:r||""}}),Gs.resetSend(),{hash:r}}return{hash:void 0}},async sendSolanaToken(){if(!Gs.state.sendTokenAmount||!Gs.state.receiverAddress)throw new Error("An amount and receiver address are required");let e;hs.pushTransactionStack({onSuccess(){hs.replace("Account")}}),Gs.state.token&&Gs.state.token.address!==qe.SOLANA_NATIVE_TOKEN_ADDRESS&&(e=He.isCaipAddress(Gs.state.token.address)?He.getPlainAddress(Gs.state.token.address):Gs.state.token.address);const t=await Us.sendTransaction({chainNamespace:"solana",tokenMint:e,to:Gs.state.receiverAddress,value:Gs.state.sendTokenAmount});t&&(Vs.hash=t),Us._getClient()?.updateBalance("solana"),ss.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:Gs.state.token?.symbol||"",amount:Gs.state.sendTokenAmount,network:Qs.state.activeCaipNetwork?.caipNetworkId||"",hash:t||""}}),Gs.resetSend()},resetSend(){Vs.token=void 0,Vs.sendTokenAmount=void 0,Vs.receiverAddress=void 0,Vs.receiverProfileImageUrl=void 0,Vs.receiverProfileName=void 0,Vs.loading=!1,Vs.tokenBalances=[]}},Gs=Ht(Ks),Js={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},Ys={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},Xs=xe({chains:function(e){const t=[];let s=0;const n=new Map,r=new WeakMap,i=e=>r.get(e)||n;if(e){if("function"!=typeof e[Symbol.iterator])throw new TypeError("proxyMap:\n\tinitial state must be iterable\n\t\ttip: structure should be [[key, value]]");for(const[r,i]of e)n.set(r,s),t[s++]=i}const o={data:t,index:s,epoch:0,get size(){je(this)||(()=>{const e=Be.get(o),t=null==e?void 0:e[1];if(t&&!r.has(t)){const e=new Map(n);r.set(t,e)}})();return i(this).size},get(e){const t=i(this).get(e);if(void 0!==t)return this.data[t];this.epoch},has(e){const t=i(this);return this.epoch,t.has(e)},set(e,t){if(!je(this))throw new Error("Cannot perform mutations on a snapshot");const s=n.get(e);return void 0===s?(n.set(e,this.index),this.data[this.index++]=t):this.data[s]=t,this.epoch++,this},delete(e){if(!je(this))throw new Error("Cannot perform mutations on a snapshot");const t=n.get(e);return void 0!==t&&(delete this.data[t],n.delete(e),this.epoch++,!0)},clear(){if(!je(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,n.clear()},forEach(e){this.epoch;i(this).forEach(((t,s)=>{e(this.data[t],s,this)}))},*entries(){this.epoch;const e=i(this);for(const[t,s]of e)yield[t,this.data[s]]},*keys(){this.epoch;const e=i(this);for(const t of e.keys())yield t},*values(){this.epoch;const e=i(this);for(const t of e.values())yield this.data[t]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},a=xe(o);return Object.defineProperties(a,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(a),a}(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{connectionControllerClient:void 0},isSwitchingNamespace:!1}),Zs={state:Xs,subscribe:e=>Re(Xs,(()=>{e(Xs)})),subscribeKey:(e,t)=>De(Xs,e,t),subscribeAccountStateProp(e,t,s){const n=s||Xs.activeChain;return n?De(Xs.chains.get(n)?.accountState||{},e,t):()=>{}},subscribeChainProp(e,t,s){let n;return Re(Xs.chains,(()=>{const r=s||Xs.activeChain;if(r){const s=Xs.chains.get(r)?.[e];n!==s&&(n=s,t(s))}}))},initialize(e,t,s){const{chainId:n,namespace:r}=We.getActiveNetworkProps(),i=t?.find((e=>e.id.toString()===n?.toString())),o=e.find((e=>e?.namespace===r))||e?.[0],a=e.map((e=>e.namespace)).filter((e=>void 0!==e)),c=kt.state.enableEmbedded?new Set([...a]):new Set([...t?.map((e=>e.chainNamespace))??[]]);0!==e?.length&&o||(Xs.noAdapters=!0),Xs.noAdapters||(Xs.activeChain=o?.namespace,Xs.activeCaipNetwork=i,Qs.setChainNetworkData(o?.namespace,{caipNetwork:i}),Xs.activeChain&&_s.set({activeChain:o?.namespace})),c.forEach((e=>{const n=t?.filter((t=>t.chainNamespace===e)),r=We.getPreferredAccountTypes()||{},i={...kt.state.defaultAccountTypes,...r};Qs.state.chains.set(e,{namespace:e,networkState:xe({...Ys,caipNetwork:n?.[0]}),accountState:xe({...Js,preferredAccountType:i[e]}),caipNetworks:n??[],...s}),Qs.setRequestedCaipNetworks(n??[],e)}))},removeAdapter(e){if(Xs.activeChain===e){const t=Array.from(Xs.chains.entries()).find((([t])=>t!==e));if(t){const e=t[1]?.caipNetworks?.[0];e&&Qs.setActiveCaipNetwork(e)}}Xs.chains.delete(e)},addAdapter(e,{connectionControllerClient:t},s){if(!e.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");Xs.chains.set(e.namespace,{namespace:e.namespace,networkState:{...Ys,caipNetwork:s[0]},accountState:{...Js},caipNetworks:s,connectionControllerClient:t}),Qs.setRequestedCaipNetworks(s?.filter((t=>t.chainNamespace===e.namespace))??[],e.namespace)},addNetwork(e){const t=Xs.chains.get(e.chainNamespace);if(t){const s=[...t.caipNetworks||[]];t.caipNetworks?.find((t=>t.id===e.id))||s.push(e),Xs.chains.set(e.chainNamespace,{...t,caipNetworks:s}),Qs.setRequestedCaipNetworks(s,e.chainNamespace),bs.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){const s=Xs.chains.get(e);if(s){const n=Xs.activeCaipNetwork?.id===t,r=[...s.caipNetworks?.filter((e=>e.id!==t))||[]];n&&s?.caipNetworks?.[0]&&Qs.setActiveCaipNetwork(s.caipNetworks[0]),Xs.chains.set(e,{...s,caipNetworks:r}),Qs.setRequestedCaipNetworks(r||[],e),0===r.length&&bs.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){const s=Xs.chains.get(e);s&&(s.networkState={...s.networkState||Ys,...t},Xs.chains.set(e,s))},setChainAccountData(e,t,s=!0){if(!e)throw new Error("Chain is required to update chain account data");const n=Xs.chains.get(e);if(n){const s={...n.accountState||Js,...t};Xs.chains.set(e,{...n,accountState:s}),1!==Xs.chains.size&&Xs.activeChain!==e||t.caipAddress&&(Xs.activeCaipAddress=t.caipAddress)}},setChainNetworkData(e,t){if(!e)return;const s=Xs.chains.get(e);if(s){const n={...s.networkState||Ys,...t};Xs.chains.set(e,{...s,networkState:n})}},setAccountProp(e,t,s,n=!0){Qs.setChainAccountData(s,{[e]:t},n)},setActiveNamespace(e){Xs.activeChain=e;const t=e?Xs.chains.get(e):void 0,s=t?.networkState?.caipNetwork;s?.id&&e&&(Xs.activeCaipAddress=t?.accountState?.caipAddress,Xs.activeCaipNetwork=s,Qs.setChainNetworkData(e,{caipNetwork:s}),We.setActiveCaipNetworkId(s?.caipNetworkId),_s.set({activeChain:e,selectedNetworkId:s?.caipNetworkId}))},setActiveCaipNetwork(e){if(!e)return;const t=Xs.activeChain===e.chainNamespace;t||Qs.setIsSwitchingNamespace(!0);const s=Xs.chains.get(e.chainNamespace);Xs.activeChain=e.chainNamespace,Xs.activeCaipNetwork=e,Qs.setChainNetworkData(e.chainNamespace,{caipNetwork:e});let n=s?.accountState?.address;if(n)Xs.activeCaipAddress=`${e.chainNamespace}:${e.id}:${n}`;else if(t&&Xs.activeCaipAddress){const{address:t}=oe.parseCaipAddress(Xs.activeCaipAddress);n=t,Xs.activeCaipAddress=`${e.caipNetworkId}:${n}`}else Xs.activeCaipAddress=void 0;Qs.setChainAccountData(e.chainNamespace,{address:n,caipAddress:Xs.activeCaipAddress}),Gs.resetSend(),_s.set({activeChain:Xs.activeChain,selectedNetworkId:Xs.activeCaipNetwork?.caipNetworkId}),We.setActiveCaipNetworkId(e.caipNetworkId);Qs.checkIfSupportedNetwork(e.chainNamespace)||!kt.state.enableNetworkSwitch||kt.state.allowUnsupportedChain||Us.state.wcBasic||Qs.showUnsupportedChainUI()},addCaipNetwork(e){if(!e)return;const t=Xs.chains.get(e.chainNamespace);t&&t?.caipNetworks?.push(e)},async switchActiveNamespace(e){if(!e)return;const t=e!==Qs.state.activeChain,s=Qs.getNetworkData(e)?.caipNetwork,n=Qs.getCaipNetworkByNamespace(e,s?.id);t&&n&&await Qs.switchActiveNetwork(n)},async switchActiveNetwork(e,{throwOnFailure:t=!1}={}){const s=Qs.state.activeChain;if(!s)throw new Error("ChainController:switchActiveNetwork - namespace is required");const n="AUTH"===Hs.getProviderId(Xs.activeChain),r=Qs.getAccountData(s)?.address,i=B.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(e.chainNamespace);try{if(r&&e.chainNamespace===s||n&&i){const t=Fs.get(e.chainNamespace);if(!t)throw new Error("Adapter not found");await t.switchNetwork({caipNetwork:e})}Qs.setActiveCaipNetwork(e)}catch(e){if(t)throw e}ss.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})},getConnectionControllerClient(e){const t=e||Xs.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");const s=Xs.chains.get(t);if(!s?.connectionControllerClient)throw new Error("ConnectionController client not set");return s.connectionControllerClient},getNetworkProp(e,t){const s=Xs.chains.get(t)?.networkState;if(s)return s[e]},getRequestedCaipNetworks(e){const t=Xs.chains.get(e),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:n=[]}=t?.networkState||{};return He.sortRequestedNetworks(s,n).filter((e=>e?.id))},getAllRequestedCaipNetworks(){const e=[];return Xs.chains.forEach((t=>{if(!t.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const s=Qs.getRequestedCaipNetworks(t.namespace);e.push(...s)})),e},setRequestedCaipNetworks(e,t){Qs.setAdapterNetworkState(t,{requestedCaipNetworks:e});const s=Qs.getAllRequestedCaipNetworks().map((e=>e.chainNamespace)),n=Array.from(new Set(s));bs.filterByNamespaces(n)},getAllApprovedCaipNetworkIds(){const e=[];return Xs.chains.forEach((t=>{if(!t.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const s=Qs.getApprovedCaipNetworkIds(t.namespace);e.push(...s)})),e},getActiveCaipNetwork:e=>e?Xs.chains.get(e)?.networkState?.caipNetwork:Xs.activeCaipNetwork,getActiveCaipAddress:()=>Xs.activeCaipAddress,getApprovedCaipNetworkIds(e){const t=Xs.chains.get(e);return t?.networkState?.approvedCaipNetworkIds||[]},setApprovedCaipNetworksData(e,t){Qs.setAdapterNetworkState(e,t)},checkIfSupportedNetwork(e,t){const s=t||Xs.activeCaipNetwork?.caipNetworkId,n=Qs.getRequestedCaipNetworks(e);return!n.length||n?.some((e=>e.caipNetworkId===s))},checkIfSupportedChainId(e){if(!Xs.activeChain)return!0;const t=Qs.getRequestedCaipNetworks(Xs.activeChain);return t?.some((t=>t.id===e))},checkIfSmartAccountEnabled(){const e=j.caipNetworkIdToNumber(Xs.activeCaipNetwork?.caipNetworkId);if(!Xs.activeChain||!e)return!1;const t=Qe.get(Ke)?.split(",")||[];return Boolean(t?.includes(e.toString()))},showUnsupportedChainUI(){sn.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const e=Xs.activeCaipNetwork;return Boolean(e?.chainNamespace&&qe.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){Qs.setAdapterNetworkState(e,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(e){const t=e;if(!t)throw new Error("Chain is required to set account prop");const s=Qs.state.chains.get(t)?.accountState?.preferredAccountType,n=kt.state.defaultAccountTypes[t];Xs.activeCaipAddress=void 0,Qs.setChainAccountData(t,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:n||s,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),bs.removeConnectorId(t)},setIsSwitchingNamespace(e){Xs.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){const e=[];let t;if(Xs.chains.forEach((t=>{B.AUTH_CONNECTOR_SUPPORTED_CHAINS.find((e=>e===t.namespace))&&t.namespace&&e.push(t.namespace)})),e.length>0){const s=e[0];return t=s?Xs.chains.get(s)?.caipNetworks?.[0]:void 0,t}},getAccountData(e){const t=e||Xs.activeChain;if(t)return Qs.state.chains.get(t)?.accountState},getNetworkData(e){const t=e||Xs.activeChain;if(t)return Qs.state.chains.get(t)?.networkState},getCaipNetworkByNamespace(e,t){if(!e)return;const s=Qs.state.chains.get(e),n=s?.caipNetworks?.find((e=>e.id.toString()===t?.toString()));return n||(s?.networkState?.caipNetwork||s?.caipNetworks?.[0])},getRequestedCaipNetworkIds(){const e=bs.state.filterByNamespace;return(e?[Xs.chains.get(e)]:Array.from(Xs.chains.values())).flatMap((e=>e?.caipNetworks||[])).map((e=>e.caipNetworkId))},getCaipNetworks:e=>e?Qs.getRequestedCaipNetworks(e):Qs.getAllRequestedCaipNetworks(),getCaipNetworkById:(e,t)=>Zs.getCaipNetworks(t).find((t=>t.id.toString()===e.toString()||t.caipNetworkId.toString()===e.toString())),setLastConnectedSIWECaipNetwork(e){Xs.lastConnectedSIWECaipNetwork=e},getLastConnectedSIWECaipNetwork:()=>Xs.lastConnectedSIWECaipNetwork,async fetchTokenBalance(e){const t=Qs.getAccountData();if(!t)return[];const s=Qs.state.activeCaipNetwork?.caipNetworkId,n=Qs.state.activeCaipNetwork?.chainNamespace,r=Qs.state.activeCaipAddress,i=r?He.getPlainAddress(r):void 0;if(Qs.setAccountProp("balanceLoading",!0,n),t.lastRetry&&!He.isAllowedRetry(t.lastRetry,30*qe.ONE_SEC_MS))return Qs.setAccountProp("balanceLoading",!1,n),[];try{if(i&&s&&n){const e=await js.getMyTokensWithBalance();return Qs.setAccountProp("tokenBalance",e,n),Qs.setAccountProp("lastRetry",void 0,n),Qs.setAccountProp("balanceLoading",!1,n),e}}catch(t){Qs.setAccountProp("lastRetry",Date.now(),n),e?.(t),Rt.showError("Token Balance Unavailable")}finally{Qs.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(e){const t=e.chainNamespace,s=Boolean(Qs.getAccountData(t)?.caipAddress),n=Qs.getAllApprovedCaipNetworkIds(),r=!1!==Qs.getNetworkProp("supportsAllNetworks",t),i=bs.getConnectorId(t),o=bs.getAuthConnector(),a=i===B.CONNECTOR_ID.AUTH&&o;return!(!s||r||a)&&!n?.includes(e.caipNetworkId)}},Qs=Ht(Zs),en={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){const s=Qs.state.activeCaipNetwork,n=Qs.state.activeChain,r=hs.state.data;if(e.id===s?.id)return;const i=Boolean(Qs.getAccountData(n)?.address),o=Boolean(Qs.getAccountData(e.chainNamespace)?.address),a=e.chainNamespace!==n,c=bs.getConnectorId(n)===B.CONNECTOR_ID.AUTH,l=B.AUTH_CONNECTOR_SUPPORTED_CHAINS.find((t=>t===e.chainNamespace));t||c&&l?hs.push("SwitchNetwork",{...r,network:e}):i&&a&&!o?hs.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):hs.push("SwitchNetwork",{...r,network:e})}},tn=xe({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),sn=Ht({state:tn,subscribe:e=>Re(tn,(()=>e(tn))),subscribeKey:(e,t)=>De(tn,e,t),async open(e){const t=e?.namespace,s=Qs.state.activeChain,n=t&&t!==s,r=Qs.getAccountData(e?.namespace)?.caipAddress,i=Qs.state.noAdapters;if(Us.state.wcBasic?os.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await os.prefetch(),bs.setFilterByNamespace(e?.namespace),sn.setLoading(!0,t),t&&n){const e=Qs.getNetworkData(t)?.caipNetwork||Qs.getRequestedCaipNetworks(t)[0];e&&(i?(await Qs.switchActiveNetwork(e),hs.push("ConnectingWalletConnectBasic")):en.onSwitchNetwork({network:e,ignoreSwitchConfirmation:!0}))}else kt.state.manualWCControl||i&&!r?He.isMobile()?hs.reset("AllWallets"):hs.reset("ConnectingWalletConnectBasic"):e?.view?hs.reset(e.view,e.data):r?hs.reset("Account"):hs.reset("Connect");tn.open=!0,_s.set({open:!0}),ss.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:Boolean(r)}})},close(){const e=kt.state.enableEmbedded,t=Boolean(Qs.state.activeCaipAddress);tn.open&&ss.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),tn.open=!1,hs.reset("Connect"),sn.clearLoading(),e?t?hs.replace("Account"):hs.push("Connect"):_s.set({open:!1}),Us.resetUri()},setLoading(e,t){t&&tn.loadingNamespaceMap.set(t,e),tn.loading=e,_s.set({loading:e})},clearLoading(){tn.loadingNamespaceMap.clear(),tn.loading=!1,_s.set({loading:!1})},shake(){tn.shake||(tn.shake=!0,setTimeout((()=>{tn.shake=!1}),500))}}),nn={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},rn={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},on=xe({providers:Fe,selectedProvider:null,error:null,purchaseCurrency:nn,paymentCurrency:rn,purchaseCurrencies:[nn],paymentCurrencies:[],quotesLoading:!1}),an=Ht({state:on,subscribe:e=>Re(on,(()=>e(on))),subscribeKey:(e,t)=>De(on,e,t),setSelectedProvider(e){if(e&&"meld"===e.name){const t=Qs.state.activeChain,s=t===B.CHAIN.SOLANA?"SOL":"USDC",n=t?Qs.state.chains.get(t)?.accountState?.address??"":"",r=new URL(e.url);r.searchParams.append("publicKey","WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU"),r.searchParams.append("destinationCurrencyCode",s),r.searchParams.append("walletAddress",n),r.searchParams.append("externalCustomerId",kt.state.projectId),on.selectedProvider={...e,url:r.toString()}}else on.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every((e=>"string"==typeof e))){const t=e,s=Fe.filter((e=>t.includes(e.name)));on.providers=s}else on.providers=[]},setPurchaseCurrency(e){on.purchaseCurrency=e},setPaymentCurrency(e){on.paymentCurrency=e},setPurchaseAmount(e){an.state.purchaseAmount=e},setPaymentAmount(e){an.state.paymentAmount=e},async getAvailableCurrencies(){const e=await Mt.getOnrampOptions();on.purchaseCurrencies=e.purchaseCurrencies,on.paymentCurrencies=e.paymentCurrencies,on.paymentCurrency=e.paymentCurrencies[0]||rn,on.purchaseCurrency=e.purchaseCurrencies[0]||nn,await os.fetchCurrencyImages(e.paymentCurrencies.map((e=>e.id))),await os.fetchTokenImages(e.purchaseCurrencies.map((e=>e.symbol)))},async getQuote(){on.quotesLoading=!0;try{const e=await Mt.getOnrampQuote({purchaseCurrency:on.purchaseCurrency,paymentCurrency:on.paymentCurrency,amount:on.paymentAmount?.toString()||"0",network:on.purchaseCurrency?.symbol});return on.quotesLoading=!1,on.purchaseAmount=Number(e?.purchaseAmount.amount),e}catch(e){return on.error=e.message,on.quotesLoading=!1,null}finally{on.quotesLoading=!1}},resetState(){on.selectedProvider=null,on.error=null,on.purchaseCurrency=nn,on.paymentCurrency=rn,on.purchaseCurrencies=[nn],on.paymentCurrencies=[],on.paymentAmount=void 0,on.purchaseAmount=void 0,on.quotesLoading=!1}});class cn extends n{constructor(e){super()}}const ln=s.FIVE_SECONDS,dn="heartbeat_pulse";class hn extends cn{constructor(e){super(e),this.events=new t,this.interval=ln,this.interval=e?.interval||ln}static async init(e){const t=new hn(e);return await t.init(),t}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async initialize(){this.intervalRef=setInterval((()=>this.pulse()),s.toMiliseconds(this.interval))}pulse(){this.events.emit(dn)}}var un={},pn={};Object.defineProperty(pn,"__esModule",{value:!0}),pn.safeJsonParse=function(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return JSON.parse(e)}catch(t){return e}},pn.safeJsonStringify=function(e){return"string"==typeof e?e:JSON.stringify(e,((e,t)=>void 0===t?null:t))};var fn,gn={exports:{}};var mn,yn={},wn={};var bn,vn,En={};Object.defineProperty(un,"__esModule",{value:!0}),un.KeyValueStorage=void 0;const Cn=U,Nn=pn,An=Cn.__importDefault((fn||(fn=1,function(){let e;function t(){}e=t,e.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},e.prototype.setItem=function(e,t){this[e]=String(t)},e.prototype.removeItem=function(e){delete this[e]},e.prototype.clear=function(){const e=this;Object.keys(e).forEach((function(t){e[t]=void 0,delete e[t]}))},e.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},e.prototype.__defineGetter__("length",(function(){return Object.keys(this).length})),void 0!==L&&L.localStorage?gn.exports=L.localStorage:"undefined"!=typeof window&&window.localStorage?gn.exports=window.localStorage:gn.exports=new t}()),gn.exports)),In=(vn||(vn=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=U;t.__exportStar((mn||(mn=1,Object.defineProperty(wn,"__esModule",{value:!0}),wn.IKeyValueStorage=void 0,wn.IKeyValueStorage=class{}),wn),e),t.__exportStar(function(){if(bn)return En;bn=1,Object.defineProperty(En,"__esModule",{value:!0}),En.parseEntry=void 0;const e=pn;return En.parseEntry=function(t){var s;return[t[0],e.safeJsonParse(null!==(s=t[1])&&void 0!==s?s:"")]},En}(),e)}(yn)),yn);class Sn{constructor(){this.localStorage=An.default}getKeys(){return Cn.__awaiter(this,void 0,void 0,(function*(){return Object.keys(this.localStorage)}))}getEntries(){return Cn.__awaiter(this,void 0,void 0,(function*(){return Object.entries(this.localStorage).map(In.parseEntry)}))}getItem(e){return Cn.__awaiter(this,void 0,void 0,(function*(){const t=this.localStorage.getItem(e);if(null!==t)return Nn.safeJsonParse(t)}))}setItem(e,t){return Cn.__awaiter(this,void 0,void 0,(function*(){this.localStorage.setItem(e,Nn.safeJsonStringify(t))}))}removeItem(e){return Cn.__awaiter(this,void 0,void 0,(function*(){this.localStorage.removeItem(e)}))}}un.KeyValueStorage=Sn;var _n=un.default=Sn,On={exports:{}};function Tn(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var kn=function(e,t,s){var n=s&&s.stringify||Tn;if("object"==typeof e&&null!==e){var r=t.length+1;if(1===r)return e;var i=new Array(r);i[0]=n(e);for(var o=1;o<r;o++)i[o]=n(t[o]);return i.join(" ")}if("string"!=typeof e)return e;var a=t.length;if(0===a)return e;for(var c="",l=0,d=-1,h=e&&e.length||0,u=0;u<h;){if(37===e.charCodeAt(u)&&u+1<h){switch(d=d>-1?d:0,e.charCodeAt(u+1)){case 100:case 102:if(l>=a||null==t[l])break;d<u&&(c+=e.slice(d,u)),c+=Number(t[l]),d=u+2,u++;break;case 105:if(l>=a||null==t[l])break;d<u&&(c+=e.slice(d,u)),c+=Math.floor(Number(t[l])),d=u+2,u++;break;case 79:case 111:case 106:if(l>=a||void 0===t[l])break;d<u&&(c+=e.slice(d,u));var p=typeof t[l];if("string"===p){c+="'"+t[l]+"'",d=u+2,u++;break}if("function"===p){c+=t[l].name||"<anonymous>",d=u+2,u++;break}c+=n(t[l]),d=u+2,u++;break;case 115:if(l>=a)break;d<u&&(c+=e.slice(d,u)),c+=String(t[l]),d=u+2,u++;break;case 37:d<u&&(c+=e.slice(d,u)),c+="%",d=u+2,u++,l--}++l}++u}return-1===d?e:(d<h&&(c+=e.slice(d)),c)};const Pn=kn;On.exports=jn;const xn=function(){function e(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}().console||{},Rn={mapHttpRequest:zn,mapHttpResponse:zn,wrapRequestSerializer:Vn,wrapResponseSerializer:Vn,wrapErrorSerializer:Vn,req:zn,res:zn,err:Wn,errWithCause:Wn};function Un(e,t){return"silent"===e?1/0:t.levels.values[e]}const Ln=Symbol("pino.logFuncs"),Dn=Symbol("pino.hierarchy"),Mn={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Bn(e,t){const s={logger:t,parent:e[Dn]};t[Dn]=s}function jn(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const s=e.browser.write||xn;e.browser.write&&(e.browser.asObject=!0);const n=e.serializers||{},r=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,n);let i=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(i=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);"function"==typeof s&&a.forEach((function(e){s[e]=s})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",l=Object.create(s);l.log||(l.log=Kn),function(e,t,s){const n={};t.forEach((e=>{n[e]=s[e]?s[e]:xn[e]||xn[Mn[e]||"log"]||Kn})),e[Ln]=n}(l,a,s),Bn({},l),Object.defineProperty(l,"levelVal",{get:function(){return Un(this.level,this)}}),Object.defineProperty(l,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,$n(this,d,l,"error"),$n(this,d,l,"fatal"),$n(this,d,l,"warn"),$n(this,d,l,"info"),$n(this,d,l,"debug"),$n(this,d,l,"trace"),o.forEach((e=>{$n(this,d,l,e)}))}});const d={transmit:t,serialize:r,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:Hn(e),messageKey:e.messageKey||"msg",onChild:e.onChild||Kn};function h(s,i,o){if(!i)throw new Error("missing bindings for child Pino");o=o||{},r&&i.serializers&&(o.serializers=i.serializers);const a=o.serializers;if(r&&a){var c=Object.assign({},n,a),l=!0===e.browser.serialize?Object.keys(c):r;delete i.serializers,Fn([i],l,c,this._stdErrSerialize)}function d(e){this._childLevel=1+(0|e._childLevel),this.bindings=i,c&&(this.serializers=c,this._serialize=l),t&&(this._logEvent=qn([].concat(e._logEvent.bindings,i)))}d.prototype=this;const u=new d(this);return Bn(this,u),u.child=function(...e){return h.call(this,s,...e)},u.level=o.level||this.level,s.onChild(u),u}return l.levels=function(e){const t=e.customLevels||{},s=Object.assign({},jn.levels.values,t),n=Object.assign({},jn.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(s){t[e[s]]=s})),t}(t));return{values:s,labels:n}}(e),l.level=c,l.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=Kn,l.serializers=n,l._serialize=r,l._stdErrSerialize=i,l.child=function(...e){return h.call(this,d,...e)},t&&(l._logEvent=qn()),l}function $n(e,t,s,n){if(Object.defineProperty(e,n,{value:Un(e.level,s)>Un(n,s)?Kn:s[Ln][n],writable:!0,enumerable:!0,configurable:!0}),e[n]===Kn){if(!t.transmit)return;const r=Un(t.transmit.level||e.level,s);if(Un(n,s)<r)return}e[n]=function(e,t,s,n){return function(r){return function(){const i=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===xn?xn:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(t.serialize&&(Fn(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),t.asObject||t.formatters?r.call(a,...function(e,t,s,n,r){const{level:i,log:o=(e=>e)}=r.formatters||{},a=s.slice();let c=a[0];const l={};let d=1+(0|e._childLevel);if(d<1&&(d=1),n&&(l.time=n),i){const s=i(t,e.levels.values[t]);Object.assign(l,s)}else l.level=e.levels.values[t];if(r.asObjectBindingsOnly){if(null!==c&&"object"==typeof c)for(;d--&&"object"==typeof a[0];)Object.assign(l,a.shift());return[o(l),...a]}if(null!==c&&"object"==typeof c){for(;d--&&"object"==typeof a[0];)Object.assign(l,a.shift());c=a.length?Pn(a.shift(),a):void 0}else"string"==typeof c&&(c=Pn(a.shift(),a));return void 0!==c&&(l[r.messageKey]=c),[o(l)]}(this,n,o,i,t)):r.apply(a,o),t.transmit){const r=t.transmit.level||e._level,a=Un(r,s),c=Un(n,s);if(c<a)return;!function(e,t,s,n=!1){const r=t.send,i=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,l=e._logEvent.bindings;n||Fn(s,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=i,e._logEvent.messages=s.filter((function(e){return-1===l.indexOf(e)})),e._logEvent.level.label=o,e._logEvent.level.value=a,r(o,e._logEvent,c),e._logEvent=qn(l)}(this,{ts:i,methodLevel:n,methodValue:c,transmitLevel:r,transmitValue:s.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Un(e._level,s)},o,l)}}}(e[Ln][n])}(e,t,s,n);const r=function(e){const t=[];e.bindings&&t.push(e.bindings);let s=e[Dn];for(;s.parent;)s=s.parent,s.logger.bindings&&t.push(s.logger.bindings);return t.reverse()}(e);0!==r.length&&(e[n]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(r,e[n]))}function Fn(e,t,s,n){for(const r in e)if(n&&e[r]instanceof Error)e[r]=jn.stdSerializers.err(e[r]);else if("object"==typeof e[r]&&!Array.isArray(e[r])&&t)for(const n in e[r])t.indexOf(n)>-1&&n in s&&(e[r][n]=s[n](e[r][n]))}function qn(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function Wn(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const s in e)void 0===t[s]&&(t[s]=e[s]);return t}function Hn(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?Gn:Jn}function zn(){return{}}function Vn(e){return e}function Kn(){}function Gn(){return!1}function Jn(){return Date.now()}jn.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},jn.stdSerializers=Rn,jn.stdTimeFunctions=Object.assign({},{nullTime:Gn,epochTime:Jn,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),On.exports.default=jn,On.exports.pino=jn;const Yn="info",Xn="custom_context",Zn=1024e3;var Qn=Object.defineProperty,er=(e,t,s)=>((e,t,s)=>t in e?Qn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class tr{constructor(e){er(this,"nodeValue"),er(this,"sizeInBytes"),er(this,"next"),this.nodeValue=e,this.sizeInBytes=(new TextEncoder).encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class sr{constructor(e){er(this,"lengthInNodes"),er(this,"sizeInBytes"),er(this,"head"),er(this,"tail"),er(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new tr(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;null!==t;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}}function nr(e){return"string"==typeof e?e:(e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t)))(e)||""}var rr=Object.defineProperty,ir=(e,t,s)=>((e,t,s)=>t in e?rr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class or{constructor(e,t=Zn){ir(this,"logs"),ir(this,"level"),ir(this,"levelValue"),ir(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=On.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new sr(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===On.exports.levels.values.error?console.error(e):t===On.exports.levels.values.warn?console.warn(e):t===On.exports.levels.values.debug?console.debug(e):t===On.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(nr({timestamp:(new Date).toISOString(),log:e}));const t="string"==typeof e?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new sr(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(nr({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var ar=Object.defineProperty,cr=(e,t,s)=>((e,t,s)=>t in e?ar(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class lr{constructor(e,t=Zn){cr(this,"baseChunkLogger"),this.baseChunkLogger=new or(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),s=document.createElement("a");s.href=t,s.download=`walletconnect-logs-${(new Date).toISOString()}.txt`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)}}var dr=Object.defineProperty,hr=(e,t,s)=>((e,t,s)=>t in e?dr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ur{constructor(e,t=Zn){hr(this,"baseChunkLogger"),this.baseChunkLogger=new or(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var pr=Object.defineProperty,fr=Object.defineProperties,gr=Object.getOwnPropertyDescriptors,mr=Object.getOwnPropertySymbols,yr=Object.prototype.hasOwnProperty,wr=Object.prototype.propertyIsEnumerable,br=(e,t,s)=>t in e?pr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,vr=(e,t)=>{for(var s in t||(t={}))yr.call(t,s)&&br(e,s,t[s]);if(mr)for(var s of mr(t))wr.call(t,s)&&br(e,s,t[s]);return e},Er=(e,t)=>fr(e,gr(t));function Cr(e,t=Xn){return e[t]||""}function Nr(e,t,s=Xn){const n=function(e,t,s=Xn){const n=Cr(e,s);return n.trim()?`${n}/${t}`:t}(e,t,s);return function(e,t,s=Xn){return e[s]=t,e}(e.child({context:n}),n,s)}function Ar(e){var t;if(typeof e.loggerOverride<"u"&&"string"!=typeof e.loggerOverride)return{logger:e.loggerOverride,chunkLoggerController:null};const s=Er(vr({},e.opts),{level:"string"==typeof e.loggerOverride?e.loggerOverride:null==(t=e.opts)?void 0:t.level});return typeof window<"u"?function(e){var t,s;const n=new lr(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:On.exports(Er(vr({},e.opts),{level:"trace",browser:Er(vr({},null==(s=e.opts)?void 0:s.browser),{write:e=>n.write(e)})})),chunkLoggerController:n}}(Er(vr({},e),{opts:s})):function(e){var t,s;const n=new ur(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:On.exports(Er(vr({},e.opts),{level:"trace",browser:Er(vr({},null==(s=e.opts)?void 0:s.browser),{write:e=>n.write(e)})}),n),chunkLoggerController:n}}(Er(vr({},e),{opts:s}))}var Ir=Object.defineProperty,Sr=(e,t,s)=>((e,t,s)=>t in e?Ir(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class _r extends n{constructor(e){super(),this.opts=e,Sr(this,"protocol","wc"),Sr(this,"version",2)}}var Or=Object.defineProperty,Tr=(e,t,s)=>((e,t,s)=>t in e?Or(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class kr extends n{constructor(e,t){super(),this.core=e,this.logger=t,Tr(this,"records",new Map)}}class Pr{constructor(e,t){this.logger=e,this.core=t}}class xr extends n{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Rr extends n{constructor(e){super()}}class Ur{constructor(e,t,s,n){this.core=e,this.logger=t,this.name=s}}class Lr extends n{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Dr extends n{constructor(e,t){super(),this.core=e,this.logger=t}}class Mr{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}}class Br{constructor(e,t){this.projectId=e,this.logger=t}}class jr{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}}var $r=Object.defineProperty,Fr=(e,t,s)=>((e,t,s)=>t in e?$r(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class qr{constructor(e){this.opts=e,Fr(this,"protocol","wc"),Fr(this,"version",2)}}class Wr{constructor(e){this.client=e}}function Hr(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function zr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Vr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Kr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Gr(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),Hr(e),e}class Jr{clone(){return this._cloneInto()}}function Yr(e=32){if(Vr&&"function"==typeof Vr.getRandomValues)return Vr.getRandomValues(new Uint8Array(e));if(Vr&&"function"==typeof Vr.randomBytes)return Vr.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}class Xr extends Jr{constructor(e,t,s,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Kr(this.buffer)}update(e){zr(this);const{view:t,buffer:s,blockLen:n}=this,r=(e=Gr(e)).length;for(let i=0;i<r;){const o=Math.min(n-this.pos,r-i);if(o!==n)s.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=Kr(e);for(;n<=r-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){zr(this),function(e,t){Hr(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:n,isLE:r}=this;let{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>n-i&&(this.process(s,0),i=0);for(let e=i;e<n;e++)t[e]=0;(function(e,t,s,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)})(s,n-8,BigInt(8*this.length),r),this.process(s,0);const o=Kr(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,length:n,finished:r,destroyed:i,pos:o}=this;return e.length=n,e.pos=o,e.finished=r,e.destroyed=i,n%t&&e.buffer.set(s),e}}const Zr=BigInt(2**32-1),Qr=BigInt(32);function ei(e,t=!1){return t?{h:Number(e&Zr),l:Number(e>>Qr&Zr)}:{h:0|Number(e>>Qr&Zr),l:0|Number(e&Zr)}}const ti={fromBig:ei,split:function(e,t=!1){let s=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:i,l:o}=ei(e[r],t);[s[r],n[r]]=[i,o]}return[s,n]},toBig:(e,t)=>BigInt(e>>>0)<<Qr|BigInt(t>>>0),shrSH:(e,t,s)=>e>>>s,shrSL:(e,t,s)=>e<<32-s|t>>>s,rotrSH:(e,t,s)=>e>>>s|t<<32-s,rotrSL:(e,t,s)=>e<<32-s|t>>>s,rotrBH:(e,t,s)=>e<<64-s|t>>>s-32,rotrBL:(e,t,s)=>e>>>s-32|t<<64-s,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,s)=>e<<s|t>>>32-s,rotlSL:(e,t,s)=>t<<s|e>>>32-s,rotlBH:(e,t,s)=>t<<s-32|e>>>64-s,rotlBL:(e,t,s)=>e<<s-32|t>>>64-s,add:function(e,t,s,n){const r=(t>>>0)+(n>>>0);return{h:e+s+(r/2**32|0)|0,l:0|r}},add3L:(e,t,s)=>(e>>>0)+(t>>>0)+(s>>>0),add3H:(e,t,s,n)=>t+s+n+(e/2**32|0)|0,add4L:(e,t,s,n)=>(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),add4H:(e,t,s,n,r)=>t+s+n+r+(e/2**32|0)|0,add5H:(e,t,s,n,r,i)=>t+s+n+r+i+(e/2**32|0)|0,add5L:(e,t,s,n,r)=>(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0)+(r>>>0)},[si,ni]=ti.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))),ri=new Uint32Array(80),ii=new Uint32Array(80);class oi extends Xr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:s,Bl:n,Ch:r,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:d,Fl:h,Gh:u,Gl:p,Hh:f,Hl:g}=this;return[e,t,s,n,r,i,o,a,c,l,d,h,u,p,f,g]}set(e,t,s,n,r,i,o,a,c,l,d,h,u,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|s,this.Bl=0|n,this.Ch=0|r,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|d,this.Fl=0|h,this.Gh=0|u,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let s=0;s<16;s++,t+=4)ri[s]=e.getUint32(t),ii[s]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ri[e-15],s=0|ii[e-15],n=ti.rotrSH(t,s,1)^ti.rotrSH(t,s,8)^ti.shrSH(t,s,7),r=ti.rotrSL(t,s,1)^ti.rotrSL(t,s,8)^ti.shrSL(t,s,7),i=0|ri[e-2],o=0|ii[e-2],a=ti.rotrSH(i,o,19)^ti.rotrBH(i,o,61)^ti.shrSH(i,o,6),c=ti.rotrSL(i,o,19)^ti.rotrBL(i,o,61)^ti.shrSL(i,o,6),l=ti.add4L(r,c,ii[e-7],ii[e-16]),d=ti.add4H(l,n,a,ri[e-7],ri[e-16]);ri[e]=0|d,ii[e]=0|l}let{Ah:s,Al:n,Bh:r,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:d,El:h,Fh:u,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=ti.rotrSH(d,h,14)^ti.rotrSH(d,h,18)^ti.rotrBH(d,h,41),w=ti.rotrSL(d,h,14)^ti.rotrSL(d,h,18)^ti.rotrBL(d,h,41),b=d&u^~d&f,v=h&p^~h&g,E=ti.add5L(y,w,v,ni[e],ii[e]),C=ti.add5H(E,m,t,b,si[e],ri[e]),N=0|E,A=ti.rotrSH(s,n,28)^ti.rotrBH(s,n,34)^ti.rotrBH(s,n,39),I=ti.rotrSL(s,n,28)^ti.rotrBL(s,n,34)^ti.rotrBL(s,n,39),S=s&r^s&o^r&o,_=n&i^n&a^i&a;m=0|f,y=0|g,f=0|u,g=0|p,u=0|d,p=0|h,({h:d,l:h}=ti.add(0|c,0|l,0|C,0|N)),c=0|o,l=0|a,o=0|r,a=0|i,r=0|s,i=0|n;const O=ti.add3L(N,I,_);s=ti.add3H(O,C,A,S),n=0|O}({h:s,l:n}=ti.add(0|this.Ah,0|this.Al,0|s,0|n)),({h:r,l:i}=ti.add(0|this.Bh,0|this.Bl,0|r,0|i)),({h:o,l:a}=ti.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=ti.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:d,l:h}=ti.add(0|this.Eh,0|this.El,0|d,0|h)),({h:u,l:p}=ti.add(0|this.Fh,0|this.Fl,0|u,0|p)),({h:f,l:g}=ti.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=ti.add(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(s,n,r,i,o,a,c,l,d,h,u,p,f,g,m,y)}roundClean(){ri.fill(0),ii.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const ai=function(e){const t=t=>e().update(Gr(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}((()=>new oi)),ci=BigInt(0),li=BigInt(1),di=BigInt(2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hi(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ui(e){if(!hi(e))throw new Error("Uint8Array expected")}function pi(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const fi=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function gi(e){ui(e);let t="";for(let s=0;s<e.length;s++)t+=fi[e[s]];return t}function mi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?ci:BigInt("0x"+e)}const yi={_0:48,_9:57,A:65,F:70,a:97,f:102};function wi(e){return e>=yi._0&&e<=yi._9?e-yi._0:e>=yi.A&&e<=yi.F?e-(yi.A-10):e>=yi.a&&e<=yi.f?e-(yi.a-10):void 0}function bi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,s=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(s);for(let t=0,r=0;t<s;t++,r+=2){const s=wi(e.charCodeAt(r)),i=wi(e.charCodeAt(r+1));if(void 0===s||void 0===i){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}n[t]=16*s+i}return n}function vi(e){return ui(e),mi(gi(Uint8Array.from(e).reverse()))}function Ei(e,t){return bi(e.toString(16).padStart(2*t,"0"))}function Ci(e,t){return Ei(e,t).reverse()}function Ni(e,t,s){let n;if("string"==typeof t)try{n=bi(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!hi(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const r=n.length;if("number"==typeof s&&r!==s)throw new Error(e+" of length "+s+" expected, got "+r);return n}function Ai(...e){let t=0;for(let s=0;s<e.length;s++){const n=e[s];ui(n),t+=n.length}const s=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const r=e[t];s.set(r,n),n+=r.length}return s}const Ii=e=>"bigint"==typeof e&&ci<=e;function Si(e,t,s,n){if(!function(e,t,s){return Ii(e)&&Ii(t)&&Ii(s)&&t<=e&&e<s}(t,s,n))throw new Error("expected valid "+e+": "+s+" <= n < "+n+", got "+t)}const _i=e=>(di<<BigInt(e-1))-li,Oi={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||hi(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function Ti(e,t,s={}){const n=(t,s,n)=>{const r=Oi[s];if("function"!=typeof r)throw new Error("invalid validator function");const i=e[t];if(!(n&&void 0===i||r(i,e)))throw new Error("param "+String(t)+" is invalid. Expected "+s+", got "+i)};for(const[e,s]of Object.entries(t))n(e,s,!1);for(const[e,t]of Object.entries(s))n(e,t,!0);return e}function ki(e){const t=new WeakMap;return(s,...n)=>{const r=t.get(s);if(void 0!==r)return r;const i=e(s,...n);return t.set(s,i),i}}const Pi=BigInt(0),xi=BigInt(1),Ri=BigInt(2),Ui=BigInt(3),Li=BigInt(4),Di=BigInt(5),Mi=BigInt(8);function Bi(e,t){const s=e%t;return s>=Pi?s:t+s}function ji(e,t,s){if(t<Pi)throw new Error("invalid exponent, negatives unsupported");if(s<=Pi)throw new Error("invalid modulus");if(s===xi)return Pi;let n=xi;for(;t>Pi;)t&xi&&(n=n*e%s),e=e*e%s,t>>=xi;return n}function $i(e,t,s){let n=e;for(;t-- >Pi;)n*=n,n%=s;return n}function Fi(e,t){if(e===Pi)throw new Error("invert: expected non-zero number");if(t<=Pi)throw new Error("invert: expected positive modulus, got "+t);let s=Bi(e,t),n=t,r=Pi,i=xi;for(;s!==Pi;){const e=n%s,t=r-i*(n/s);n=s,s=e,r=i,i=t}if(n!==xi)throw new Error("invert: does not exist");return Bi(r,t)}function qi(e){if(e%Li===Ui){const t=(e+xi)/Li;return function(e,s){const n=e.pow(s,t);if(!e.eql(e.sqr(n),s))throw new Error("Cannot find square root");return n}}if(e%Mi===Di){const t=(e-Di)/Mi;return function(e,s){const n=e.mul(s,Ri),r=e.pow(n,t),i=e.mul(s,r),o=e.mul(e.mul(i,Ri),r),a=e.mul(i,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),s))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-xi)/Ri;let s,n,r;for(s=e-xi,n=0;s%Ri===Pi;s/=Ri,n++);for(r=Ri;r<e&&ji(r,t,e)!==e-xi;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===n){const t=(e+xi)/Li;return function(e,s){const n=e.pow(s,t);if(!e.eql(e.sqr(n),s))throw new Error("Cannot find square root");return n}}const i=(s+xi)/Ri;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=n,c=e.pow(e.mul(e.ONE,r),s),l=e.pow(o,i),d=e.pow(o,s);for(;!e.eql(d,e.ONE);){if(e.eql(d,e.ZERO))return e.ZERO;let t=1;for(let s=e.sqr(d);t<a&&!e.eql(s,e.ONE);t++)s=e.sqr(s);const s=e.pow(c,xi<<BigInt(a-t-1));c=e.sqr(s),l=e.mul(l,s),d=e.mul(d,c),a=t}return l}}(e)}const Wi=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Hi(e,t){const s=void 0!==t?t:e.toString(2).length;return{nBitLength:s,nByteLength:Math.ceil(s/8)}}function zi(e,t,s=!1,n={}){if(e<=Pi)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:i}=Hi(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:s,BITS:r,BYTES:i,MASK:_i(r),ZERO:Pi,ONE:xi,create:t=>Bi(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Pi<=t&&t<e},is0:e=>e===Pi,isOdd:e=>(e&xi)===xi,neg:t=>Bi(-t,e),eql:(e,t)=>e===t,sqr:t=>Bi(t*t,e),add:(t,s)=>Bi(t+s,e),sub:(t,s)=>Bi(t-s,e),mul:(t,s)=>Bi(t*s,e),pow:(e,t)=>function(e,t,s){if(s<Pi)throw new Error("invalid exponent, negatives unsupported");if(s===Pi)return e.ONE;if(s===xi)return t;let n=e.ONE,r=t;for(;s>Pi;)s&xi&&(n=e.mul(n,r)),r=e.sqr(r),s>>=xi;return n}(a,e,t),div:(t,s)=>Bi(t*Fi(s,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Fi(t,e),sqrt:n.sqrt||(t=>(o||(o=qi(e)),o(a,t))),invertBatch:e=>function(e,t){const s=new Array(t.length),n=t.reduce(((t,n,r)=>e.is0(n)?t:(s[r]=t,e.mul(t,n))),e.ONE),r=e.inv(n);return t.reduceRight(((t,n,r)=>e.is0(n)?t:(s[r]=e.mul(t,s[r]),e.mul(t,n))),r),s}(a,e),cmov:(e,t,s)=>s?t:e,toBytes:e=>s?Ci(e,i):Ei(e,i),fromBytes:e=>{if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);return s?vi(e):function(e){return mi(gi(e))}(e)}});return Object.freeze(a)}const Vi=BigInt(0),Ki=BigInt(1);function Gi(e,t){const s=t.negate();return e?s:t}function Ji(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Yi(e,t){Ji(e,t);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Xi=new WeakMap,Zi=new WeakMap;function Qi(e){return Zi.get(e)||1}function eo(e,t,s,n){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,s)=>{if(!(e instanceof t))throw new Error("invalid point at index "+s)}))}(s,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,s)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+s)}))}(n,t),s.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const r=e.ZERO,i=function(e){let t;for(t=0;e>ci;e>>=li,t+=1);return t}(BigInt(s.length)),o=i>12?i-3:i>4?i-2:i?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r);let l=r;for(let e=Math.floor((t.BITS-1)/o)*o;e>=0;e-=o){c.fill(r);for(let t=0;t<n.length;t++){const r=n[t],i=Number(r>>BigInt(e)&BigInt(a));c[i]=c[i].add(s[t])}let t=r;for(let e=c.length-1,s=r;e>0;e--)s=s.add(c[e]),t=t.add(s);if(l=l.add(t),0!==e)for(let e=0;e<o;e++)l=l.double()}return l}function to(e){return function(e){const t=Wi.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});Ti(e,t)}(e.Fp),Ti(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Hi(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const so=BigInt(0),no=BigInt(1),ro=BigInt(2),io=BigInt(8),oo={zip215:!0};function ao(e){const t=function(e){const t=to(e);return Ti(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:s,n:n,prehash:r,hash:i,randomBytes:o,nByteLength:a,h:c}=t,l=ro<<BigInt(8*a)-no,d=s.create,h=zi(t.n,t.nBitLength),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:s.sqrt(e*s.inv(t))}}catch{return{isValid:!1,value:so}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,s)=>{if(pi("phflag",s),t.length||s)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){Si("coordinate "+e,t,so,l)}function m(e){if(!(e instanceof b))throw new Error("ExtendedPoint expected")}const y=ki(((e,t)=>{const{ex:n,ey:r,ez:i}=e,o=e.is0();null==t&&(t=o?io:s.inv(i));const a=d(n*t),c=d(r*t),l=d(i*t);if(o)return{x:so,y:no};if(l!==no)throw new Error("invZ was invalid");return{x:a,y:c}})),w=ki((e=>{const{a:s,d:n}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:r,ey:i,ez:o,et:a}=e,c=d(r*r),l=d(i*i),h=d(o*o),u=d(h*h),p=d(c*s);if(d(h*d(p+l))!==d(u+d(n*d(c*l))))throw new Error("bad point: equation left != right (1)");if(d(r*i)!==d(o*a))throw new Error("bad point: equation left != right (2)");return!0}));class b{constructor(e,t,s,n){this.ex=e,this.ey=t,this.ez=s,this.et=n,g("x",e),g("y",t),g("z",s),g("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof b)throw new Error("extended point not allowed");const{x:t,y:s}=e||{};return g("x",t),g("y",s),new b(t,s,no,d(t*s))}static normalizeZ(e){const t=s.invertBatch(e.map((e=>e.ez)));return e.map(((e,s)=>e.toAffine(t[s]))).map(b.fromAffine)}static msm(e,t){return eo(b,h,e,t)}_setWindowSize(e){C.setWindowSize(this,e)}assertValidity(){w(this)}equals(e){m(e);const{ex:t,ey:s,ez:n}=this,{ex:r,ey:i,ez:o}=e,a=d(t*o),c=d(r*n),l=d(s*o),h=d(i*n);return a===c&&l===h}is0(){return this.equals(b.ZERO)}negate(){return new b(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){const{a:e}=t,{ex:s,ey:n,ez:r}=this,i=d(s*s),o=d(n*n),a=d(ro*d(r*r)),c=d(e*i),l=s+n,h=d(d(l*l)-i-o),u=c+o,p=u-a,f=c-o,g=d(h*p),m=d(u*f),y=d(h*f),w=d(p*u);return new b(g,m,w,y)}add(e){m(e);const{a:s,d:n}=t,{ex:r,ey:i,ez:o,et:a}=this,{ex:c,ey:l,ez:h,et:u}=e;if(s===BigInt(-1)){const e=d((i-r)*(l+c)),t=d((i+r)*(l-c)),s=d(t-e);if(s===so)return this.double();const n=d(o*ro*u),p=d(a*ro*h),f=p+n,g=t+e,m=p-n,y=d(f*s),w=d(g*m),v=d(f*m),E=d(s*g);return new b(y,w,E,v)}const p=d(r*c),f=d(i*l),g=d(a*n*u),y=d(o*h),w=d((r+i)*(c+l)-p-f),v=y-g,E=y+g,C=d(f-s*p),N=d(w*v),A=d(E*C),I=d(w*C),S=d(v*E);return new b(N,A,S,I)}subtract(e){return this.add(e.negate())}wNAF(e){return C.wNAFCached(this,e,b.normalizeZ)}multiply(e){const t=e;Si("scalar",t,no,n);const{p:s,f:r}=this.wNAF(t);return b.normalizeZ([s,r])[0]}multiplyUnsafe(e,t=b.ZERO){const s=e;return Si("scalar",s,so,n),s===so?E:this.is0()||s===no?this:C.wNAFCachedUnsafe(this,s,b.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(e){return y(this,e)}clearCofactor(){const{h:e}=t;return e===no?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:r,a:i}=t,o=s.BYTES;e=Ni("pointHex",e,o),pi("zip215",n);const a=e.slice(),c=e[o-1];a[o-1]=-129&c;const h=vi(a),p=n?l:s.ORDER;Si("pointHex.y",h,so,p);const f=d(h*h),g=d(f-no),m=d(r*f-i);let{isValid:y,value:w}=u(g,m);if(!y)throw new Error("Point.fromHex: invalid y coordinate");const v=(w&no)===no,E=0!=(128&c);if(!n&&w===so&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(w=d(-w)),b.fromAffine({x:w,y:h})}static fromPrivateKey(e){return I(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Ci(t,s.BYTES);return n[n.length-1]|=e&no?128:0,n}toHex(){return gi(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,no,d(t.Gx*t.Gy)),b.ZERO=new b(so,no,no,so);const{BASE:v,ZERO:E}=b,C=function(e,t){return{constTimeNegate:Gi,hasPrecomputes:e=>1!==Qi(e),unsafeLadder(t,s,n=e.ZERO){let r=t;for(;s>Vi;)s&Ki&&(n=n.add(r)),r=r.double(),s>>=Ki;return n},precomputeWindow(e,s){const{windows:n,windowSize:r}=Yi(s,t),i=[];let o=e,a=o;for(let e=0;e<n;e++){a=o,i.push(a);for(let e=1;e<r;e++)a=a.add(o),i.push(a);o=a.double()}return i},wNAF(s,n,r){const{windows:i,windowSize:o}=Yi(s,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**s-1),d=2**s,h=BigInt(s);for(let e=0;e<i;e++){const t=e*o;let s=Number(r&l);r>>=h,s>o&&(s-=d,r+=Ki);const i=t,u=t+Math.abs(s)-1,p=e%2!=0,f=s<0;0===s?c=c.add(Gi(p,n[i])):a=a.add(Gi(f,n[u]))}return{p:a,f:c}},wNAFUnsafe(s,n,r,i=e.ZERO){const{windows:o,windowSize:a}=Yi(s,t),c=BigInt(2**s-1),l=2**s,d=BigInt(s);for(let e=0;e<o;e++){const t=e*a;if(r===Vi)break;let s=Number(r&c);if(r>>=d,s>a&&(s-=l,r+=Ki),0===s)continue;let o=n[t+Math.abs(s)-1];s<0&&(o=o.negate()),i=i.add(o)}return i},getPrecomputes(e,t,s){let n=Xi.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&Xi.set(t,s(n))),n},wNAFCached(e,t,s){const n=Qi(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)},wNAFCachedUnsafe(e,t,s,n){const r=Qi(e);return 1===r?this.unsafeLadder(e,t,n):this.wNAFUnsafe(r,this.getPrecomputes(r,e,s),t,n)},setWindowSize(e,s){Ji(s,t),Zi.set(e,s),Xi.delete(e)}}}(b,8*a);function N(e){return Bi(e,n)}function A(e){return N(vi(e))}function I(e){const t=s.BYTES;e=Ni("private key",e,t);const n=Ni("hashed private key",i(e),2*t),r=p(n.slice(0,t)),o=n.slice(t,2*t),a=A(r),c=v.multiply(a),l=c.toRawBytes();return{head:r,prefix:o,scalar:a,point:c,pointBytes:l}}function S(e=new Uint8Array,...t){const s=Ai(...t);return A(i(f(s,Ni("context",e),!!r)))}const _=oo;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,i={}){e=Ni("message",e),r&&(e=r(e));const{prefix:o,scalar:a,pointBytes:c}=I(t),l=S(i.context,o,e),d=v.multiply(l).toRawBytes(),h=N(l+S(i.context,d,c,e)*a);return Si("signature.s",h,so,n),Ni("result",Ai(d,Ci(h,s.BYTES)),2*s.BYTES)},verify:function(e,t,n,i=_){const{context:o,zip215:a}=i,c=s.BYTES;e=Ni("signature",e,2*c),t=Ni("message",t),n=Ni("publicKey",n,c),void 0!==a&&pi("zip215",a),r&&(t=r(t));const l=vi(e.slice(c,2*c));let d,h,u;try{d=b.fromHex(n,a),h=b.fromHex(e.slice(0,c),a),u=v.multiplyUnsafe(l)}catch{return!1}if(!a&&d.isSmallOrder())return!1;const p=S(o,h.toRawBytes(),d.toRawBytes(),t);return h.add(d.multiplyUnsafe(p)).subtract(u).clearCofactor().equals(b.ZERO)},ExtendedPoint:b,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>o(s.BYTES),precompute:(e=8,t=b.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}BigInt(0),BigInt(1);const co=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),lo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const ho=BigInt(1),uo=BigInt(2);BigInt(3);const po=BigInt(5),fo=BigInt(8);function go(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function mo(e,t){const s=co,n=Bi(t*t*t,s),r=function(e){const t=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=co,o=e*e%i*e%i,a=$i(o,uo,i)*o%i,c=$i(a,ho,i)*e%i,l=$i(c,po,i)*c%i,d=$i(l,t,i)*l%i,h=$i(d,s,i)*d%i,u=$i(h,n,i)*h%i,p=$i(u,r,i)*u%i,f=$i(p,r,i)*u%i,g=$i(f,t,i)*l%i;return{pow_p_5_8:$i(g,uo,i)*e%i,b2:o}}(e*Bi(n*n*t,s)).pow_p_5_8;let i=Bi(e*n*r,s);const o=Bi(t*i*i,s),a=i,c=Bi(i*lo,s),l=o===e,d=o===Bi(-e,s),h=o===Bi(-e*lo,s);return l&&(i=a),(d||h)&&(i=c),((e,t)=>(Bi(e,t)&xi)===xi)(i,s)&&(i=Bi(-i,s)),{isValid:l||d,value:i}}const yo=zi(co,void 0,!0),wo=ao({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:yo,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:fo,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ai,randomBytes:Yr,adjustScalarBytes:go,uvRatio:mo}),bo=".",vo="base64url",Eo="utf8",Co="utf8",No=":",Ao="did",Io="key",So="base58btc",_o="z",Oo="K36";function To(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function ko(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?To(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Po(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const s=ko(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return To(s)}var xo=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var r=0;r<e.length;r++){var i=e.charAt(r),o=i.charCodeAt(0);if(255!==s[o])throw new TypeError(i+" is ambiguous");s[o]=r}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,r=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*l+1>>>0,o=new Uint8Array(i);e[t];){var d=s[e.charCodeAt(t)];if(255===d)return;for(var h=0,u=i-1;(0!==d||h<r)&&-1!==u;u--,h++)d+=a*o[u]>>>0,o[u]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");r=h,t++}if(" "!==e[t]){for(var p=i-r;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)f[g++]=o[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var s=0,n=0,r=0,i=t.length;r!==i&&0===t[r];)r++,s++;for(var o=(i-r)*d+1>>>0,l=new Uint8Array(o);r!==i;){for(var h=t[r],u=0,p=o-1;(0!==h||u<n)&&-1!==p;p--,u++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=u,r++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(s);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode:function(e){var s=h(e);if(s)return s;throw new Error(`Non-${t} character`)}}},Ro=xo;const Uo=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Lo{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Do{constructor(e,t,s){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=s}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Bo(this,e)}}class Mo{constructor(e){this.decoders=e}or(e){return Bo(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Bo=(e,t)=>new Mo({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class jo{constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Lo(e,t,s),this.decoder=new Do(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const $o=({name:e,prefix:t,encode:s,decode:n})=>new jo(e,t,s,n),Fo=({prefix:e,name:t,alphabet:s})=>{const{encode:n,decode:r}=Ro(s,t);return $o({prefix:e,name:t,encode:n,decode:e=>Uo(r(e))})},qo=({name:e,prefix:t,bitsPerChar:s,alphabet:n})=>$o({prefix:t,name:e,encode:e=>((e,t,s)=>{const n="="===t[t.length-1],r=(1<<s)-1;let i="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>s;)o-=s,i+=t[r&a>>o];if(o&&(i+=t[r&a<<s-o]),n)for(;i.length*s&7;)i+="=";return i})(e,n,s),decode:t=>((e,t,s,n)=>{const r={};for(let e=0;e<t.length;++e)r[t[e]]=e;let i=e.length;for(;"="===e[i-1];)--i;const o=new Uint8Array(i*s/8|0);let a=0,c=0,l=0;for(let t=0;t<i;++t){const i=r[e[t]];if(void 0===i)throw new SyntaxError(`Non-${n} character`);c=c<<s|i,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,n,s,e)}),Wo=$o({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var Ho=Object.freeze({__proto__:null,identity:Wo});const zo=qo({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vo=Object.freeze({__proto__:null,base2:zo});const Ko=qo({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Go=Object.freeze({__proto__:null,base8:Ko});const Jo=Fo({prefix:"9",name:"base10",alphabet:"0123456789"});var Yo=Object.freeze({__proto__:null,base10:Jo});const Xo=qo({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Zo=qo({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Qo=Object.freeze({__proto__:null,base16:Xo,base16upper:Zo});const ea=qo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ta=qo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),sa=qo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),na=qo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ra=qo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ia=qo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),oa=qo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),aa=qo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ca=qo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var la=Object.freeze({__proto__:null,base32:ea,base32upper:ta,base32pad:sa,base32padupper:na,base32hex:ra,base32hexupper:ia,base32hexpad:oa,base32hexpadupper:aa,base32z:ca});const da=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ha=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ua=Object.freeze({__proto__:null,base36:da,base36upper:ha});const pa=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),fa=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ga=Object.freeze({__proto__:null,base58btc:pa,base58flickr:fa});const ma=qo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ya=qo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),wa=qo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ba=qo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var va=Object.freeze({__proto__:null,base64:ma,base64pad:ya,base64url:wa,base64urlpad:ba});const Ea=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Ca=Ea.reduce(((e,t,s)=>(e[s]=t,e)),[]),Na=Ea.reduce(((e,t,s)=>(e[t.codePointAt(0)]=s,e)),[]);const Aa=$o({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=Ca[t]),"")},decode:function(e){const t=[];for(const s of e){const e=Na[s.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${s}`);t.push(e)}return new Uint8Array(t)}});var Ia=Object.freeze({__proto__:null,base256emoji:Aa}),Sa=function e(t,s,n){s=s||[];for(var r=n=n||0;t>=Ta;)s[n++]=255&t|_a,t/=128;for(;t&Oa;)s[n++]=255&t|_a,t>>>=7;return s[n]=0|t,e.bytes=n-r+1,s},_a=128,Oa=-128,Ta=Math.pow(2,31);var ka=function e(t,s){var n,r=0,i=(s=s||0,0),o=s,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],r+=i<28?(n&xa)<<i:(n&xa)*Math.pow(2,i),i+=7}while(n>=Pa);return e.bytes=o-s,r},Pa=128,xa=127;var Ra=Math.pow(2,7),Ua=Math.pow(2,14),La=Math.pow(2,21),Da=Math.pow(2,28),Ma=Math.pow(2,35),Ba=Math.pow(2,42),ja=Math.pow(2,49),$a=Math.pow(2,56),Fa=Math.pow(2,63),qa={encode:Sa,decode:ka,encodingLength:function(e){return e<Ra?1:e<Ua?2:e<La?3:e<Da?4:e<Ma?5:e<Ba?6:e<ja?7:e<$a?8:e<Fa?9:10}},Wa=qa;const Ha=(e,t,s=0)=>(Wa.encode(e,t,s),t),za=e=>Wa.encodingLength(e),Va=(e,t)=>{const s=t.byteLength,n=za(e),r=n+za(s),i=new Uint8Array(r+s);return Ha(e,i,0),Ha(s,i,n),i.set(t,r),new Ka(e,s,t,i)};class Ka{constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}}const Ga=({name:e,code:t,encode:s})=>new Ja(e,t,s);class Ja{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Va(this.code,t):t.then((e=>Va(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Ya=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Xa=Ga({name:"sha2-256",code:18,encode:Ya("SHA-256")}),Za=Ga({name:"sha2-512",code:19,encode:Ya("SHA-512")});Object.freeze({__proto__:null,sha256:Xa,sha512:Za});const Qa=Uo,ec={code:0,name:"identity",encode:Qa,digest:e=>Va(0,Qa(e))};Object.freeze({__proto__:null,identity:ec});new TextEncoder,new TextDecoder;const tc={...Ho,...Vo,...Go,...Yo,...Qo,...la,...ua,...ga,...va,...Ia};function sc(e,t,s,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:n}}}const nc=sc("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),rc=sc("ascii","a",(e=>{let t="a";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t}),(e=>{const t=ko((e=e.substring(1)).length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t})),ic={utf8:nc,"utf-8":nc,hex:tc.base16,latin1:rc,ascii:rc,binary:rc,...tc};function oc(e,t="utf8"){const s=ic[t];if(!s)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?s.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}function ac(e,t="utf8"){const s=ic[t];if(!s)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?s.decoder.decode(`${s.prefix}${e}`):To(globalThis.Buffer.from(e,"utf-8"))}function cc(e){return r(oc(ac(e,vo),Eo))}function lc(e){return oc(ac(i(e),Eo),vo)}function dc(e){const t=ac(Oo,So),s=_o+oc(Po([t,e]),So);return[Ao,Io,s].join(No)}function hc(e){return oc(e,vo)}function uc(e){const t=e.split(bo),s=cc(t[0]),n=cc(t[1]),r=function(e){return ac(e,vo)}(t[2]);return{header:s,payload:n,signature:r,data:ac(t.slice(0,2).join(bo),Co)}}function pc(e=Yr(32)){const t=wo.getPublicKey(e);return{secretKey:Po([e,t]),publicKey:t}}async function fc(e,t,n,r,i=s.fromMiliseconds(Date.now())){const o={alg:"EdDSA",typ:"JWT"},a={iss:dc(r.publicKey),sub:e,aud:t,iat:i,exp:i+n},c=function(e){return ac([lc(e.header),lc(e.payload)].join(bo),Co)}({header:o,payload:a});return function(e){return[lc(e.header),lc(e.payload),hc(e.signature)].join(bo)}({header:o,payload:a,signature:wo.sign(c,r.secretKey.slice(0,32))})}
2
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function gc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function mc(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every((e=>"string"==typeof e)):t.every((e=>Number.isSafeInteger(e)))))}function yc(e){if("function"!=typeof e)throw new Error("function expected");return!0}function wc(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function bc(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function vc(e){if(!Array.isArray(e))throw new Error("array expected")}function Ec(e,t){if(!mc(!0,t))throw new Error(`${e}: array of strings expected`)}function Cc(e,t){if(!mc(!1,t))throw new Error(`${e}: array of numbers expected`)}function Nc(...e){const t=e=>e,s=(e,t)=>s=>e(t(s)),n=e.map((e=>e.encode)).reduceRight(s,t),r=e.map((e=>e.decode)).reduce(s,t);return{encode:n,decode:r}}function Ac(e){const t="string"==typeof e?e.split(""):e,s=t.length;Ec("alphabet",t);const n=new Map(t.map(((e,t)=>[e,t])));return{encode:n=>(vc(n),n.map((n=>{if(!Number.isSafeInteger(n)||n<0||n>=s)throw new Error(`alphabet.encode: digit index outside alphabet "${n}". Allowed: ${e}`);return t[n]}))),decode:t=>(vc(t),t.map((t=>{wc("alphabet.decode",t);const s=n.get(t);if(void 0===s)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return s})))}}function Ic(e=""){return wc("join",e),{encode:t=>(Ec("join.decode",t),t.join(e)),decode:t=>(wc("join.decode",t),t.split(e))}}function Sc(e,t="="){return bc(e),wc("padding",t),{encode(s){for(Ec("padding.encode",s);s.length*e%8;)s.push(t);return s},decode(s){Ec("padding.decode",s);let n=s.length;if(n*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&s[n-1]===t;n--){if((n-1)*e%8==0)throw new Error("padding: invalid, string has too much padding")}return s.slice(0,n)}}}function _c(e){return yc(e),{encode:e=>e,decode:t=>e(t)}}function Oc(e,t,s){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(s<2)throw new Error(`convertRadix: invalid to=${s}, base cannot be less than 2`);if(vc(e),!e.length)return[];let n=0;const r=[],i=Array.from(e,(e=>{if(bc(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e})),o=i.length;for(;;){let e=0,a=!0;for(let r=n;r<o;r++){const o=i[r],c=t*e,l=c+o;if(!Number.isSafeInteger(l)||c/t!==e||l-o!==c)throw new Error("convertRadix: carry overflow");const d=l/s;e=l%s;const h=Math.floor(d);if(i[r]=h,!Number.isSafeInteger(h)||h*s+e!==l)throw new Error("convertRadix: carry overflow");a&&(h?a=!1:n=r)}if(r.push(e),a)break}for(let t=0;t<e.length-1&&0===e[t];t++)r.push(0);return r.reverse()}const Tc=(e,t)=>0===t?e:Tc(t,e%t),kc=(e,t)=>e+(t-Tc(e,t)),Pc=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function xc(e,t,s,n){if(vc(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(s<=0||s>32)throw new Error(`convertRadix2: wrong to=${s}`);if(kc(t,s)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${s} carryBits=${kc(t,s)}`);let r=0,i=0;const o=Pc[t],a=Pc[s]-1,c=[];for(const n of e){if(bc(n),n>=o)throw new Error(`convertRadix2: invalid data word=${n} from=${t}`);if(r=r<<t|n,i+t>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=s;i-=s)c.push((r>>i-s&a)>>>0);const e=Pc[i];if(void 0===e)throw new Error("invalid carry");r&=e-1}if(r=r<<s-i&a,!n&&i>=t)throw new Error("Excess padding");if(!n&&r>0)throw new Error(`Non-zero padding: ${r}`);return n&&i>0&&c.push(r>>>0),c}function Rc(e,t=!1){if(bc(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(kc(8,e)>32||kc(e,8)>32)throw new Error("radix2: carry overflow");return{encode:s=>{if(!gc(s))throw new Error("radix2.encode input should be Uint8Array");return xc(Array.from(s),8,e,!t)},decode:s=>(Cc("radix2.decode",s),Uint8Array.from(xc(s,e,8,t)))}}function Uc(e){return yc(e),function(...t){try{return e.apply(null,t)}catch(e){}}}Nc(Rc(4),Ac("0123456789ABCDEF"),Ic(""));const Lc=Nc(Rc(5),Ac("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Sc(5),Ic(""));Nc(Rc(5),Ac("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ic("")),Nc(Rc(5),Ac("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Sc(5),Ic("")),Nc(Rc(5),Ac("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Ic("")),Nc(Rc(5),Ac("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Ic(""),_c((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))));const Dc=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)();Dc||Nc(Rc(6),Ac("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Sc(6),Ic("")),Nc(Rc(6),Ac("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ic("")),Dc||Nc(Rc(6),Ac("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Sc(6),Ic("")),Nc(Rc(6),Ac("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Ic(""));const Mc=e=>{return Nc((bc(t=58),{encode:e=>{if(!gc(e))throw new Error("radix.encode input should be Uint8Array");return Oc(Array.from(e),256,t)},decode:e=>(Cc("radix.decode",e),Uint8Array.from(Oc(e,t,256)))}),Ac(e),Ic(""));var t},Bc=Mc("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");Mc("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Mc("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const jc=Nc(Ac("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Ic("")),$c=[996825010,642813549,513874426,1027748829,705979059];function Fc(e){const t=e>>25;let s=(33554431&e)<<5;for(let e=0;e<$c.length;e++)1==(t>>e&1)&&(s^=$c[e]);return s}function qc(e,t,s=1){const n=e.length;let r=1;for(let t=0;t<n;t++){const s=e.charCodeAt(t);if(s<33||s>126)throw new Error(`Invalid prefix (${e})`);r=Fc(r)^s>>5}r=Fc(r);for(let t=0;t<n;t++)r=Fc(r)^31&e.charCodeAt(t);for(let e of t)r=Fc(r)^e;for(let e=0;e<6;e++)r=Fc(r);return r^=s,jc.encode(xc([r%Pc[30]],30,5,!1))}function Wc(e){const t="bech32"===e?1:734539939,s=Rc(5),n=s.decode,r=s.encode,i=Uc(n);function o(e,s,n=90){wc("bech32.encode prefix",e),gc(s)&&(s=Array.from(s)),Cc("bech32.encode",s);const r=e.length;if(0===r)throw new TypeError(`Invalid prefix length ${r}`);const i=r+7+s.length;if(!1!==n&&i>n)throw new TypeError(`Length ${i} exceeds limit ${n}`);const o=e.toLowerCase(),a=qc(o,s,t);return`${o}1${jc.encode(s)}${a}`}function a(e,s=90){wc("bech32.decode input",e);const n=e.length;if(n<8||!1!==s&&n>s)throw new TypeError(`invalid string length: ${n} (${e}). Expected (8..${s})`);const r=e.toLowerCase();if(e!==r&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const i=r.lastIndexOf("1");if(0===i||-1===i)throw new Error('Letter "1" must be present between prefix and data only');const o=r.slice(0,i),a=r.slice(i+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const c=jc.decode(a).slice(0,-6),l=qc(o,c,t);if(!a.endsWith(l))throw new Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:o,words:c}}return{encode:o,decode:a,encodeFromBytes:function(e,t){return o(e,r(t))},decodeToBytes:function(e){const{prefix:t,words:s}=a(e,!1);return{prefix:t,words:s,bytes:n(s)}},decodeUnsafe:Uc(a),fromWords:n,fromWordsUnsafe:i,toWords:r}}Wc("bech32"),Wc("bech32m");(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||Nc(Rc(4),Ac("0123456789abcdef"),Ic(""),_c((e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));const Hc={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}},zc=":";function Vc(e){const[t,s]=e.split(zc);return{namespace:t,reference:s}}function Kc(e,t){return e.includes(":")?[e]:t.chains||[]}const Gc={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Jc={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function Yc(e,t){const{message:s,code:n}=Jc[e];return{message:t?`${s} ${t}`:s,code:n}}function Xc(e,t){const{message:s,code:n}=Gc[e];return{message:t?`${s} ${t}`:s,code:n}}var Zc=Object.defineProperty,Qc=Object.defineProperties,el=Object.getOwnPropertyDescriptors,tl=Object.getOwnPropertySymbols,sl=Object.prototype.hasOwnProperty,nl=Object.prototype.propertyIsEnumerable,rl=(e,t,s)=>t in e?Zc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,il=(e,t)=>{for(var s in t||(t={}))sl.call(t,s)&&rl(e,s,t[s]);if(tl)for(var s of tl(t))nl.call(t,s)&&rl(e,s,t[s]);return e},ol=(e,t,s)=>rl(e,"symbol"!=typeof t?t+"":t,s);const al="ReactNative",cl={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},ll="js";function dl(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function hl(){return!l()&&!!d()&&navigator.product===al}function ul(){return!dl()&&!!d()&&!!l()}function pl(){return hl()?cl.reactNative:dl()?cl.node:ul()?cl.browser:cl.unknown}function fl(){var e;try{return hl()&&typeof global<"u"&&typeof(null==global?void 0:global.Application)<"u"?null==(e=global.Application)?void 0:e.applicationId:void 0}catch{return}}function gl(e){var t,s;const n=ml();try{return null!=e&&e.url&&n.url&&new URL(e.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),e.url=n.url),null!=(t=e?.icons)&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter((e=>""!==e))),((e,t)=>Qc(e,el(t)))(il(il({},n),e),{url:e?.url||n.url,name:e?.name||n.name,description:e?.description||n.description,icons:null!=(s=e?.icons)&&s.length&&e.icons.length>0?e.icons:n.icons})}catch(t){return console.warn("Error populating app metadata",t),e||n}}function ml(){return o()||{name:"",description:"",url:"",icons:[""]}}function yl(e,t,s){const n=function(){if(pl()===cl.reactNative&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"){const{OS:e,Version:t}=global.Platform;return[e,t].join("-")}const e=m();if(null===e)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[t,e.name,e.version].join("-"):[t,e.version].join("-")}(),r=function(){var e;const t=pl();return t===cl.browser?[t,(null==(e=y())?void 0:e.host)||"unknown"].join(":"):t}();return[[e,t].join("-"),[ll,s].join("-"),n,r].join("/")}function wl({protocol:e,version:t,relayUrl:s,sdkVersion:n,auth:r,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d={auth:r,ua:yl(e,t,n),projectId:i,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=function(e,t){const s=new URLSearchParams(e);return Object.entries(t).sort((([e],[t])=>e.localeCompare(t))).forEach((([e,t])=>{null!=t&&s.set(e,String(t))})),s.toString()}(l[1]||"",d);return l[0]+"?"+h}function bl(e,t){return e.filter((e=>t.includes(e))).length===e.length}function vl(e){return Object.fromEntries(e.entries())}function El(e){return new Map(Object.entries(e))}function Cl(e=s.FIVE_MINUTES,t){const n=s.toMiliseconds(e||s.FIVE_MINUTES);let r,i,o,a;return{resolve:e=>{o&&r&&(clearTimeout(o),r(e),a=Promise.resolve(e))},reject:e=>{o&&i&&(clearTimeout(o),i(e))},done:()=>new Promise(((e,s)=>{if(a)return e(a);o=setTimeout((()=>{const e=Yc("EXPIRED"),n=new Error(t||e.message);n.code=e.code,s(n)}),n),r=e,i=s}))}}function Nl(e,t,s){return new Promise((async(n,r)=>{const i=setTimeout((()=>r(new Error(s))),t);try{n(await e)}catch(e){r(e)}clearTimeout(i)}))}function Al(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function Il(e){const[t,s]=e.split(":"),n={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof s)n.topic=s;else{if("id"!==t||!Number.isInteger(Number(s)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${s}`);n.id=Number(s)}return n}function Sl(e,t){return s.fromMiliseconds((t||Date.now())+s.toMiliseconds(e))}function _l(e){return Date.now()>=s.toMiliseconds(e)}function Ol(e,t){return`${e}${t?`:${t}`:""}`}function Tl(e=[],t=[]){return[...new Set([...e,...t])]}async function kl({id:e,topic:t,wcDeepLink:s}){var n;try{if(!s)return;const r="string"==typeof s?JSON.parse(s):s,i=r?.href;if("string"!=typeof i)return;const o=function(e,t,s){const n=`requestId=${t}&sessionTopic=${s}`;e.endsWith("/")&&(e=e.slice(0,-1));let r=`${e}`;if(e.startsWith("https://t.me")){r=`${r}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const s=Buffer.from(e).toString("base64");return t?s.replace(/[=]/g,""):s}(n,!0)}`}else r=`${r}/wc?${n}`;return r}(i,e,t),a=pl();if(a===cl.browser){if(null==(n=l())||!n.hasFocus())return void console.warn("Document does not have focus, skipping deeplink.");!function(e){let t="_self";!function(){try{return window.self!==window.top}catch{return!1}}()?(typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"):t="_top",window.open(e,t,"noreferrer noopener")}(o)}else a===cl.reactNative&&typeof(null==global?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(e){console.error(e)}}function Pl(e,t){if(!e.includes(t))return null;const s=e.split(/([&,?,=])/),n=s.indexOf(t);return s[n+2]}function xl(){return typeof crypto<"u"&&null!=crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function Rl(){return typeof process<"u"&&"true"===process.env.IS_VITEST}function Ul(e){return Buffer.from(e,"base64").toString("utf-8")}class Ll{constructor({limit:e}){ol(this,"limit"),ol(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const e=this.set.values().next().value;e&&this.set.delete(e)}this.set.add(e)}}has(e){return this.set.has(e)}}const Dl=BigInt(2**32-1),Ml=BigInt(32);function Bl(e,t=!1){return t?{h:Number(e&Dl),l:Number(e>>Ml&Dl)}:{h:0|Number(e>>Ml&Dl),l:0|Number(e&Dl)}}function jl(e,t=!1){const s=e.length;let n=new Uint32Array(s),r=new Uint32Array(s);for(let i=0;i<s;i++){const{h:s,l:o}=Bl(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}const $l=(e,t,s)=>e>>>s,Fl=(e,t,s)=>e<<32-s|t>>>s,ql=(e,t,s)=>e>>>s|t<<32-s,Wl=(e,t,s)=>e<<32-s|t>>>s,Hl=(e,t,s)=>e<<64-s|t>>>s-32,zl=(e,t,s)=>e>>>s-32|t<<64-s,Vl=(e,t)=>t,Kl=(e,t)=>e;function Gl(e,t,s,n){const r=(t>>>0)+(n>>>0);return{h:e+s+(r/2**32|0)|0,l:0|r}}const Jl=(e,t,s)=>(e>>>0)+(t>>>0)+(s>>>0),Yl=(e,t,s,n)=>t+s+n+(e/2**32|0)|0,Xl=(e,t,s,n)=>(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),Zl=(e,t,s,n,r)=>t+s+n+r+(e/2**32|0)|0,Ql=(e,t,s,n,r)=>(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0)+(r>>>0),ed=(e,t,s,n,r,i)=>t+s+n+r+i+(e/2**32|0)|0,td="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function sd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function nd(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function rd(e,...t){if(!sd(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function id(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");nd(e.outputLen),nd(e.blockLen)}function od(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ad(e,t){rd(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function cd(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function ld(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function dd(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function hd(e,t){return e<<32-t|e>>>t}const ud=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function pd(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const fd=ud?e=>e:e=>pd(e);const gd=ud?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=pd(e[t]);return e},md="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,yd=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function wd(e){if(rd(e),md)return e.toHex();let t="";for(let s=0;s<e.length;s++)t+=yd[e[s]];return t}const bd={_0:48,_9:57,A:65,F:70,a:97,f:102};function vd(e){return e>=bd._0&&e<=bd._9?e-bd._0:e>=bd.A&&e<=bd.F?e-(bd.A-10):e>=bd.a&&e<=bd.f?e-(bd.a-10):void 0}function Ed(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(md)return Uint8Array.fromHex(e);const t=e.length,s=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(s);for(let t=0,r=0;t<s;t++,r+=2){const s=vd(e.charCodeAt(r)),i=vd(e.charCodeAt(r+1));if(void 0===s||void 0===i){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}n[t]=16*s+i}return n}function Cd(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Nd(e){return"string"==typeof e&&(e=Cd(e)),rd(e),e}function Ad(...e){let t=0;for(let s=0;s<e.length;s++){const n=e[s];rd(n),t+=n.length}const s=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const r=e[t];s.set(r,n),n+=r.length}return s}class Id{}function Sd(e){const t=t=>e().update(Nd(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}function _d(e=32){if(td&&"function"==typeof td.getRandomValues)return td.getRandomValues(new Uint8Array(e));if(td&&"function"==typeof td.randomBytes)return Uint8Array.from(td.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const Od=BigInt(0),Td=BigInt(1),kd=BigInt(2),Pd=BigInt(7),xd=BigInt(256),Rd=BigInt(113),Ud=[],Ld=[],Dd=[];for(let e=0,t=Td,s=1,n=0;e<24;e++){[s,n]=[n,(2*s+3*n)%5],Ud.push(2*(5*n+s)),Ld.push((e+1)*(e+2)/2%64);let r=Od;for(let e=0;e<7;e++)t=(t<<Td^(t>>Pd)*Rd)%xd,t&kd&&(r^=Td<<(Td<<BigInt(e))-Td);Dd.push(r)}const Md=jl(Dd,!0),Bd=Md[0],jd=Md[1],$d=(e,t,s)=>s>32?((e,t,s)=>t<<s-32|e>>>64-s)(e,t,s):((e,t,s)=>e<<s|t>>>32-s)(e,t,s),Fd=(e,t,s)=>s>32?((e,t,s)=>e<<s-32|t>>>64-s)(e,t,s):((e,t,s)=>t<<s|e>>>32-s)(e,t,s);class qd extends Id{constructor(e,t,s,n=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=n,this.rounds=r,nd(s),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=cd(this.state)}clone(){return this._cloneInto()}keccak(){gd(this.state32),function(e,t=24){const s=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)s[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const n=(t+8)%10,r=(t+2)%10,i=s[r],o=s[r+1],a=$d(i,o,1)^s[n],c=Fd(i,o,1)^s[n+1];for(let s=0;s<50;s+=10)e[t+s]^=a,e[t+s+1]^=c}let t=e[2],r=e[3];for(let s=0;s<24;s++){const n=Ld[s],i=$d(t,r,n),o=Fd(t,r,n),a=Ud[s];t=e[a],r=e[a+1],e[a]=i,e[a+1]=o}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)s[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~s[(n+2)%10]&s[(n+4)%10]}e[0]^=Bd[n],e[1]^=jd[n]}ld(s)}(this.state32,this.rounds),gd(this.state32),this.posOut=0,this.pos=0}update(e){od(this),rd(e=Nd(e));const{blockLen:t,state:s}=this,n=e.length;for(let r=0;r<n;){const i=Math.min(t-this.pos,n-r);for(let t=0;t<i;t++)s[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:s,blockLen:n}=this;e[s]^=t,0!=(128&t)&&s===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){od(this,!1),rd(e),this.finish();const t=this.state,{blockLen:s}=this;for(let n=0,r=e.length;n<r;){this.posOut>=s&&this.keccak();const i=Math.min(s-this.posOut,r-n);e.set(t.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return nd(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ad(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,ld(this.state)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:n,rounds:r,enableXOF:i}=this;return e||(e=new qd(t,s,n,i,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=s,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const Wd=((e,t,s)=>Sd((()=>new qd(t,e,s))))(1,136,32);function Hd(e,t,s){return e&t^~e&s}function zd(e,t,s){return e&t^e&s^t&s}class Vd extends Id{constructor(e,t,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=dd(this.buffer)}update(e){od(this),rd(e=Nd(e));const{view:t,buffer:s,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(n-this.pos,r-i);if(o!==n)s.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(t,0),this.pos=0);else{const t=dd(e);for(;n<=r-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){od(this),ad(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:n,isLE:r}=this;let{pos:i}=this;t[i++]=128,ld(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(s,0),i=0);for(let e=i;e<n;e++)t[e]=0;(function(e,t,s,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)})(s,n-8,BigInt(8*this.length),r),this.process(s,0);const o=dd(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,length:n,finished:r,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=o,n%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}}const Kd=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Gd=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Jd=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Yd=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Xd=new Uint32Array(64);class Zd extends Vd{constructor(e=32){super(64,e,8,!1),this.A=0|Kd[0],this.B=0|Kd[1],this.C=0|Kd[2],this.D=0|Kd[3],this.E=0|Kd[4],this.F=0|Kd[5],this.G=0|Kd[6],this.H=0|Kd[7]}get(){const{A:e,B:t,C:s,D:n,E:r,F:i,G:o,H:a}=this;return[e,t,s,n,r,i,o,a]}set(e,t,s,n,r,i,o,a){this.A=0|e,this.B=0|t,this.C=0|s,this.D=0|n,this.E=0|r,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let s=0;s<16;s++,t+=4)Xd[s]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Xd[e-15],s=Xd[e-2],n=hd(t,7)^hd(t,18)^t>>>3,r=hd(s,17)^hd(s,19)^s>>>10;Xd[e]=r+Xd[e-7]+n+Xd[e-16]|0}let{A:s,B:n,C:r,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(hd(o,6)^hd(o,11)^hd(o,25))+Hd(o,a,c)+Yd[e]+Xd[e]|0,d=(hd(s,2)^hd(s,13)^hd(s,22))+zd(s,n,r)|0;l=c,c=a,a=o,o=i+t|0,i=r,r=n,n=s,s=t+d|0}s=s+this.A|0,n=n+this.B|0,r=r+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(s,n,r,i,o,a,c,l)}roundClean(){ld(Xd)}destroy(){this.set(0,0,0,0,0,0,0,0),ld(this.buffer)}}const Qd=jl(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))),eh=Qd[0],th=Qd[1],sh=new Uint32Array(80),nh=new Uint32Array(80);class rh extends Vd{constructor(e=64){super(128,e,16,!1),this.Ah=0|Jd[0],this.Al=0|Jd[1],this.Bh=0|Jd[2],this.Bl=0|Jd[3],this.Ch=0|Jd[4],this.Cl=0|Jd[5],this.Dh=0|Jd[6],this.Dl=0|Jd[7],this.Eh=0|Jd[8],this.El=0|Jd[9],this.Fh=0|Jd[10],this.Fl=0|Jd[11],this.Gh=0|Jd[12],this.Gl=0|Jd[13],this.Hh=0|Jd[14],this.Hl=0|Jd[15]}get(){const{Ah:e,Al:t,Bh:s,Bl:n,Ch:r,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:d,Fl:h,Gh:u,Gl:p,Hh:f,Hl:g}=this;return[e,t,s,n,r,i,o,a,c,l,d,h,u,p,f,g]}set(e,t,s,n,r,i,o,a,c,l,d,h,u,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|s,this.Bl=0|n,this.Ch=0|r,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|d,this.Fl=0|h,this.Gh=0|u,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let s=0;s<16;s++,t+=4)sh[s]=e.getUint32(t),nh[s]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|sh[e-15],s=0|nh[e-15],n=ql(t,s,1)^ql(t,s,8)^$l(t,0,7),r=Wl(t,s,1)^Wl(t,s,8)^Fl(t,s,7),i=0|sh[e-2],o=0|nh[e-2],a=ql(i,o,19)^Hl(i,o,61)^$l(i,0,6),c=Wl(i,o,19)^zl(i,o,61)^Fl(i,o,6),l=Xl(r,c,nh[e-7],nh[e-16]),d=Zl(l,n,a,sh[e-7],sh[e-16]);sh[e]=0|d,nh[e]=0|l}let{Ah:s,Al:n,Bh:r,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:d,El:h,Fh:u,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=ql(d,h,14)^ql(d,h,18)^Hl(d,h,41),w=Wl(d,h,14)^Wl(d,h,18)^zl(d,h,41),b=d&u^~d&f,v=Ql(y,w,h&p^~h&g,th[e],nh[e]),E=ed(v,m,t,b,eh[e],sh[e]),C=0|v,N=ql(s,n,28)^Hl(s,n,34)^Hl(s,n,39),A=Wl(s,n,28)^zl(s,n,34)^zl(s,n,39),I=s&r^s&o^r&o,S=n&i^n&a^i&a;m=0|f,y=0|g,f=0|u,g=0|p,u=0|d,p=0|h,({h:d,l:h}=Gl(0|c,0|l,0|E,0|C)),c=0|o,l=0|a,o=0|r,a=0|i,r=0|s,i=0|n;const _=Jl(C,A,S);s=Yl(_,E,N,I),n=0|_}({h:s,l:n}=Gl(0|this.Ah,0|this.Al,0|s,0|n)),({h:r,l:i}=Gl(0|this.Bh,0|this.Bl,0|r,0|i)),({h:o,l:a}=Gl(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=Gl(0|this.Dh,0|this.Dl,0|c,0|l)),({h:d,l:h}=Gl(0|this.Eh,0|this.El,0|d,0|h)),({h:u,l:p}=Gl(0|this.Fh,0|this.Fl,0|u,0|p)),({h:f,l:g}=Gl(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=Gl(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(s,n,r,i,o,a,c,l,d,h,u,p,f,g,m,y)}roundClean(){ld(sh,nh)}destroy(){ld(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class ih extends rh{constructor(){super(48),this.Ah=0|Gd[0],this.Al=0|Gd[1],this.Bh=0|Gd[2],this.Bl=0|Gd[3],this.Ch=0|Gd[4],this.Cl=0|Gd[5],this.Dh=0|Gd[6],this.Dl=0|Gd[7],this.Eh=0|Gd[8],this.El=0|Gd[9],this.Fh=0|Gd[10],this.Fl=0|Gd[11],this.Gh=0|Gd[12],this.Gl=0|Gd[13],this.Hh=0|Gd[14],this.Hl=0|Gd[15]}}const oh=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class ah extends rh{constructor(){super(32),this.Ah=0|oh[0],this.Al=0|oh[1],this.Bh=0|oh[2],this.Bl=0|oh[3],this.Ch=0|oh[4],this.Cl=0|oh[5],this.Dh=0|oh[6],this.Dl=0|oh[7],this.Eh=0|oh[8],this.El=0|oh[9],this.Fh=0|oh[10],this.Fl=0|oh[11],this.Gh=0|oh[12],this.Gl=0|oh[13],this.Hh=0|oh[14],this.Hl=0|oh[15]}}const ch=Sd((()=>new Zd)),lh=Sd((()=>new rh)),dh=Sd((()=>new ih)),hh=Sd((()=>new ah)),uh=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),ph=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),fh=new Uint32Array(32);function gh(e,t,s,n,r,i){const o=r[i],a=r[i+1];let c=fh[2*e],l=fh[2*e+1],d=fh[2*t],h=fh[2*t+1],u=fh[2*s],p=fh[2*s+1],f=fh[2*n],g=fh[2*n+1],m=Jl(c,d,o);l=Yl(m,l,h,a),c=0|m,({Dh:g,Dl:f}={Dh:g^l,Dl:f^c}),({Dh:g,Dl:f}={Dh:Vl(0,f),Dl:Kl(g)}),({h:p,l:u}=Gl(p,u,g,f)),({Bh:h,Bl:d}={Bh:h^p,Bl:d^u}),({Bh:h,Bl:d}={Bh:ql(h,d,24),Bl:Wl(h,d,24)}),fh[2*e]=c,fh[2*e+1]=l,fh[2*t]=d,fh[2*t+1]=h,fh[2*s]=u,fh[2*s+1]=p,fh[2*n]=f,fh[2*n+1]=g}function mh(e,t,s,n,r,i){const o=r[i],a=r[i+1];let c=fh[2*e],l=fh[2*e+1],d=fh[2*t],h=fh[2*t+1],u=fh[2*s],p=fh[2*s+1],f=fh[2*n],g=fh[2*n+1],m=Jl(c,d,o);l=Yl(m,l,h,a),c=0|m,({Dh:g,Dl:f}={Dh:g^l,Dl:f^c}),({Dh:g,Dl:f}={Dh:ql(g,f,16),Dl:Wl(g,f,16)}),({h:p,l:u}=Gl(p,u,g,f)),({Bh:h,Bl:d}={Bh:h^p,Bl:d^u}),({Bh:h,Bl:d}={Bh:Hl(h,d,63),Bl:zl(h,d,63)}),fh[2*e]=c,fh[2*e+1]=l,fh[2*t]=d,fh[2*t+1]=h,fh[2*s]=u,fh[2*s+1]=p,fh[2*n]=f,fh[2*n+1]=g}class yh extends Id{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,nd(e),nd(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=cd(this.buffer)}update(e){od(this),rd(e=Nd(e));const{blockLen:t,buffer:s,buffer32:n}=this,r=e.length,i=e.byteOffset,o=e.buffer;for(let a=0;a<r;){this.pos===t&&(gd(n),this.compress(n,0,!1),gd(n),this.pos=0);const c=Math.min(t-this.pos,r-a),l=i+a;if(c!==t||l%4||!(a+c<r))s.set(e.subarray(a,a+c),this.pos),this.pos+=c,this.length+=c,a+=c;else{const e=new Uint32Array(o,l,Math.floor((r-a)/4));gd(e);for(let s=0;a+t<r;s+=n.length,a+=t)this.length+=t,this.compress(e,s,!1);gd(e)}}return this}digestInto(e){od(this),ad(e,this);const{pos:t,buffer32:s}=this;this.finished=!0,ld(this.buffer.subarray(t)),gd(s),this.compress(s,0,!0),gd(s);const n=cd(e);this.get().forEach(((e,t)=>n[t]=fd(e)))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){const{buffer:t,length:s,finished:n,destroyed:r,outputLen:i,pos:o}=this;return e||(e=new this.constructor({dkLen:i})),e.set(...this.get()),e.buffer.set(t),e.destroyed=r,e.finished=n,e.length=s,e.pos=o,e.outputLen=i,e}clone(){return this._cloneInto()}}class wh extends yh{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|ph[0],this.v0h=0|ph[1],this.v1l=0|ph[2],this.v1h=0|ph[3],this.v2l=0|ph[4],this.v2h=0|ph[5],this.v3l=0|ph[6],this.v3h=0|ph[7],this.v4l=0|ph[8],this.v4h=0|ph[9],this.v5l=0|ph[10],this.v5h=0|ph[11],this.v6l=0|ph[12],this.v6h=0|ph[13],this.v7l=0|ph[14],this.v7h=0|ph[15],function(e,t={},s,n,r){if(nd(s),e<0||e>s)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=t;if(void 0!==i&&(i.length<1||i.length>s))throw new Error("key length must be undefined or 1.."+s);if(void 0!==o&&o.length!==n)throw new Error("salt must be undefined or "+n);if(void 0!==a&&a.length!==r)throw new Error("personalization must be undefined or "+r)}(t,e,64,16,16);let{key:s,personalization:n,salt:r}=e,i=0;if(void 0!==s&&(s=Nd(s),i=s.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,void 0!==r){r=Nd(r);const e=cd(r);this.v4l^=fd(e[0]),this.v4h^=fd(e[1]),this.v5l^=fd(e[2]),this.v5h^=fd(e[3])}if(void 0!==n){n=Nd(n);const e=cd(n);this.v6l^=fd(e[0]),this.v6h^=fd(e[1]),this.v7l^=fd(e[2]),this.v7h^=fd(e[3])}if(void 0!==s){const e=new Uint8Array(this.blockLen);e.set(s),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:s,v1h:n,v2l:r,v2h:i,v3l:o,v3h:a,v4l:c,v4h:l,v5l:d,v5h:h,v6l:u,v6h:p,v7l:f,v7h:g}=this;return[e,t,s,n,r,i,o,a,c,l,d,h,u,p,f,g]}set(e,t,s,n,r,i,o,a,c,l,d,h,u,p,f,g){this.v0l=0|e,this.v0h=0|t,this.v1l=0|s,this.v1h=0|n,this.v2l=0|r,this.v2h=0|i,this.v3l=0|o,this.v3h=0|a,this.v4l=0|c,this.v4h=0|l,this.v5l=0|d,this.v5h=0|h,this.v6l=0|u,this.v6h=0|p,this.v7l=0|f,this.v7h=0|g}compress(e,t,s){this.get().forEach(((e,t)=>fh[t]=e)),fh.set(ph,16);let{h:n,l:r}=Bl(BigInt(this.length));fh[24]=ph[8]^r,fh[25]=ph[9]^n,s&&(fh[28]=~fh[28],fh[29]=~fh[29]);let i=0;const o=uh;for(let s=0;s<12;s++)gh(0,4,8,12,e,t+2*o[i++]),mh(0,4,8,12,e,t+2*o[i++]),gh(1,5,9,13,e,t+2*o[i++]),mh(1,5,9,13,e,t+2*o[i++]),gh(2,6,10,14,e,t+2*o[i++]),mh(2,6,10,14,e,t+2*o[i++]),gh(3,7,11,15,e,t+2*o[i++]),mh(3,7,11,15,e,t+2*o[i++]),gh(0,5,10,15,e,t+2*o[i++]),mh(0,5,10,15,e,t+2*o[i++]),gh(1,6,11,12,e,t+2*o[i++]),mh(1,6,11,12,e,t+2*o[i++]),gh(2,7,8,13,e,t+2*o[i++]),mh(2,7,8,13,e,t+2*o[i++]),gh(3,4,9,14,e,t+2*o[i++]),mh(3,4,9,14,e,t+2*o[i++]);this.v0l^=fh[0]^fh[16],this.v0h^=fh[1]^fh[17],this.v1l^=fh[2]^fh[18],this.v1h^=fh[3]^fh[19],this.v2l^=fh[4]^fh[20],this.v2h^=fh[5]^fh[21],this.v3l^=fh[6]^fh[22],this.v3h^=fh[7]^fh[23],this.v4l^=fh[8]^fh[24],this.v4h^=fh[9]^fh[25],this.v5l^=fh[10]^fh[26],this.v5h^=fh[11]^fh[27],this.v6l^=fh[12]^fh[28],this.v6h^=fh[13]^fh[29],this.v7l^=fh[14]^fh[30],this.v7h^=fh[15]^fh[31],ld(fh)}destroy(){this.destroyed=!0,ld(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const bh=function(e){const t=(t,s)=>e(s).update(Nd(t)).digest(),s=e({});return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=t=>e(t),t}((e=>new wh(e))),vh="https://rpc.walletconnect.org/v1";function Eh(e){const t=`Ethereum Signed Message:\n${e.length}`,s=(new TextEncoder).encode(t+e);return"0x"+Buffer.from(Wd(s)).toString("hex")}async function Ch(e,t,s,n,r,i){switch(s.t){case"eip191":return await function(e,t,s){const n=p(s);return f({payload:Eh(t),signature:n}).toLowerCase()===e.toLowerCase()}(e,t,s.s);case"eip1271":return await async function(e,t,s,n,r,i){const o=Vc(n);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{const o="0x1626ba7e",a="0000000000000000000000000000000000000000000000000000000000000040",c=s.substring(2),l=(c.length/2).toString(16).padStart(64,"0"),d=o+(t.startsWith("0x")?t:Eh(t)).substring(2)+a+l+c,h=await fetch(`${i||vh}/?chainId=${n}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Nh(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:d},"latest"]})}),{result:u}=await h.json();return!!u&&u.slice(0,o.length).toLowerCase()===o.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,s.s,n,r,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}function Nh(){return Date.now()+Math.floor(1e3*Math.random())}function Ah(e){const t=new Uint8Array(Buffer.from(e,"base64")),s=Array.from("TransactionData::").map((e=>e.charCodeAt(0))),n=new Uint8Array(s.length+t.length);n.set(s),n.set(t,s.length);const r=bh(n,{dkLen:32});return Bc.encode(r)}function Ih(e){const t=new Uint8Array(ch(function(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if("object"==typeof e&&null!=e&&e.data)return new Uint8Array(Object.values(e.data));if("object"==typeof e&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}(e)));return Bc.encode(t)}function Sh(e){const t=Buffer.from(e,"base64"),s=h(t).txn;if(!s)throw new Error("Invalid signed transaction: missing 'txn' field");const n=u(s),r=Buffer.from("TX"),i=Buffer.concat([r,Buffer.from(n)]),o=hh(i);return Lc.encode(o).replace(/=+$/,"")}function _h(e){const t=[];let s=BigInt(e);for(;s>=BigInt(128);)t.push(Number(s&BigInt(127)|BigInt(128))),s>>=BigInt(7);return t.push(Number(s)),Buffer.from(t)}function Oh(e){const t=Buffer.from(e.signed.bodyBytes,"base64"),s=Buffer.from(e.signed.authInfoBytes,"base64"),n=Buffer.from(e.signature.signature,"base64"),r=[];r.push(Buffer.from([10])),r.push(_h(t.length)),r.push(t),r.push(Buffer.from([18])),r.push(_h(s.length)),r.push(s),r.push(Buffer.from([26])),r.push(_h(n.length)),r.push(n);const i=Buffer.concat(r),o=ch(i);return Buffer.from(o).toString("hex").toUpperCase()}var Th=Object.defineProperty,kh=Object.defineProperties,Ph=Object.getOwnPropertyDescriptors,xh=Object.getOwnPropertySymbols,Rh=Object.prototype.hasOwnProperty,Uh=Object.prototype.propertyIsEnumerable,Lh=(e,t,s)=>t in e?Th(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Dh=(e,t)=>{for(var s in t||(t={}))Rh.call(t,s)&&Lh(e,s,t[s]);if(xh)for(var s of xh(t))Uh.call(t,s)&&Lh(e,s,t[s]);return e},Mh=(e,t)=>kh(e,Ph(t));const Bh="did:pkh:",jh={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},$h=e=>e?.split(":"),Fh=e=>{const t=e&&$h(e);if(t)return t[2]+":"+t[3]},qh=e=>{const t=e&&$h(e);if(t)return t.pop()};async function Wh(e){const{cacao:t,projectId:s}=e,{s:n,p:r}=t,i=Hh(r,r.iss),o=qh(r.iss);return await Ch(o,i,n,Fh(r.iss),s)}const Hh=(e,t)=>{const s=(e=>{const t=e&&$h(e);if(t)return e.includes(Bh)?t[2]:t[0]})(t);if(!s)throw new Error("Invalid issuer: "+t);const n=`${e.domain} wants you to sign in with your ${(e=>e?jh[e]||e:"")(s)} account:`,r=qh(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=e.statement||void 0;const o=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${(e=>{const t=e&&$h(e);if(t)return e.includes(Bh)?t[3]:t[1]})(t)}`,l=`Nonce: ${e.nonce}`,d=`Issued At: ${e.iat}`,h=e.exp?`Expiration Time: ${e.exp}`:void 0,u=e.nbf?`Not Before: ${e.nbf}`:void 0,p=e.requestId?`Request ID: ${e.requestId}`:void 0,f=e.resources?`Resources:${e.resources.map((e=>`\n- ${e}`)).join("")}`:void 0,g=Qh(e.resources);if(g){i=function(e="",t){zh(t);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(s))return e;const n=[];let r=0;Object.keys(t.att).forEach((e=>{const s=Object.keys(t.att[e]).map((e=>({ability:e.split("/")[0],action:e.split("/")[1]})));s.sort(((e,t)=>e.action.localeCompare(t.action)));const i={};s.forEach((e=>{i[e.ability]||(i[e.ability]=[]),i[e.ability].push(e.action)}));const o=Object.keys(i).map((t=>(r++,`(${r}) '${t}': '${i[t].join("', '")}' for '${e}'.`)));n.push(o.join(", ").replace(".,","."))}));const i=n.join(" "),o=`${s}${i}`;return`${e?e+" ":""}${o}`}(i,Gh(g))}return[n,r,"",i,"",o,a,c,l,d,h,u,p,f].filter((e=>null!=e)).join("\n")};function zh(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(null==t||!t.length)throw new Error("No resources found in `att` property");t.forEach((t=>{const s=e.att[t];if(Array.isArray(s))throw new Error(`Resource must be an object: ${t}`);if("object"!=typeof s)throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(s).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(s).forEach((e=>{const t=s[e];if(!Array.isArray(t))throw new Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw new Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach((t=>{if("object"!=typeof t)throw new Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)}))}))}))}function Vh(e,t,s={}){t=t?.sort(((e,t)=>e.localeCompare(t)));const n=t.map((t=>({[`${e}/${t}`]:[s]})));return Object.assign({},...n)}function Kh(e){return zh(e),`urn:recap:${function(e){return Buffer.from(JSON.stringify(e)).toString("base64")}(e).replace(/=/g,"")}`}function Gh(e){const t=function(e){return JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}(e.replace("urn:recap:",""));return zh(t),t}function Jh(e,t,s){const n=function(e,t,s,n={}){return s?.sort(((e,t)=>e.localeCompare(t))),{att:{[e]:Vh(t,s,n)}}}(e,t,s);return Kh(n)}function Yh(e,t){const s=function(e,t){zh(e),zh(t);const s=Object.keys(e.att).concat(Object.keys(t.att)).sort(((e,t)=>e.localeCompare(t))),n={att:{}};return s.forEach((s=>{var r,i;Object.keys((null==(r=e.att)?void 0:r[s])||{}).concat(Object.keys((null==(i=t.att)?void 0:i[s])||{})).sort(((e,t)=>e.localeCompare(t))).forEach((r=>{var i,o;n.att[s]=Mh(Dh({},n.att[s]),{[r]:(null==(i=e.att[s])?void 0:i[r])||(null==(o=t.att[s])?void 0:o[r])})}))})),n}(Gh(e),Gh(t));return Kh(s)}function Xh(e){var t;const s=Gh(e);zh(s);const n=null==(t=s.att)?void 0:t.eip155;return n?Object.keys(n).map((e=>e.split("/")[1])):[]}function Zh(e){const t=Gh(e);zh(t);const s=[];return Object.values(t.att).forEach((e=>{Object.values(e).forEach((e=>{var t;null!=(t=e?.[0])&&t.chains&&s.push(e[0].chains)}))})),[...new Set(s.flat())]}function Qh(e){if(!e)return;const t=e?.[e.length-1];return function(e){return e&&e.includes("urn:recap:")}(t)?t:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function eu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function tu(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function su(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function nu(e,...t){if(!eu(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ru(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function iu(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function ou(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const au=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function cu(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!eu(e))throw new Error("Uint8Array expected, got "+typeof e);e=uu(e)}return e}function lu(e,t,s=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(s&&!function(e){return e.byteOffset%4==0}(t))throw new Error("invalid output, must be aligned");return t}function du(e,t,s,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function hu(e,t,s){tu(s);const n=new Uint8Array(16),r=function(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}(n);return du(r,0,BigInt(t),s),du(r,8,BigInt(e),s),n}function uu(e){return Uint8Array.from(e)}const pu=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),fu=pu("expand 16-byte k"),gu=pu("expand 32-byte k"),mu=iu(fu),yu=iu(gu);function wu(e,t){return e<<t|e>>>32-t}function bu(e){return e.byteOffset%4==0}const vu=64,Eu=16,Cu=2**32-1,Nu=new Uint32Array;const Au=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Iu{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,nu(e=cu(e),32);const t=Au(e,0),s=Au(e,2),n=Au(e,4),r=Au(e,6),i=Au(e,8),o=Au(e,10),a=Au(e,12),c=Au(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|s<<3),this.r[2]=7939&(s>>>10|n<<6),this.r[3]=8191&(n>>>7|r<<9),this.r[4]=255&(r>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Au(e,16+2*t)}process(e,t,s=!1){const n=s?0:2048,{h:r,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],d=i[4],h=i[5],u=i[6],p=i[7],f=i[8],g=i[9],m=Au(e,t+0),y=Au(e,t+2),w=Au(e,t+4),b=Au(e,t+6),v=Au(e,t+8),E=Au(e,t+10),C=Au(e,t+12),N=Au(e,t+14);let A=r[0]+(8191&m),I=r[1]+(8191&(m>>>13|y<<3)),S=r[2]+(8191&(y>>>10|w<<6)),_=r[3]+(8191&(w>>>7|b<<9)),O=r[4]+(8191&(b>>>4|v<<12)),T=r[5]+(v>>>1&8191),k=r[6]+(8191&(v>>>14|E<<2)),P=r[7]+(8191&(E>>>11|C<<5)),x=r[8]+(8191&(C>>>8|N<<8)),R=r[9]+(N>>>5|n),U=0,L=U+A*o+I*(5*g)+S*(5*f)+_*(5*p)+O*(5*u);U=L>>>13,L&=8191,L+=T*(5*h)+k*(5*d)+P*(5*l)+x*(5*c)+R*(5*a),U+=L>>>13,L&=8191;let D=U+A*a+I*o+S*(5*g)+_*(5*f)+O*(5*p);U=D>>>13,D&=8191,D+=T*(5*u)+k*(5*h)+P*(5*d)+x*(5*l)+R*(5*c),U+=D>>>13,D&=8191;let M=U+A*c+I*a+S*o+_*(5*g)+O*(5*f);U=M>>>13,M&=8191,M+=T*(5*p)+k*(5*u)+P*(5*h)+x*(5*d)+R*(5*l),U+=M>>>13,M&=8191;let B=U+A*l+I*c+S*a+_*o+O*(5*g);U=B>>>13,B&=8191,B+=T*(5*f)+k*(5*p)+P*(5*u)+x*(5*h)+R*(5*d),U+=B>>>13,B&=8191;let j=U+A*d+I*l+S*c+_*a+O*o;U=j>>>13,j&=8191,j+=T*(5*g)+k*(5*f)+P*(5*p)+x*(5*u)+R*(5*h),U+=j>>>13,j&=8191;let $=U+A*h+I*d+S*l+_*c+O*a;U=$>>>13,$&=8191,$+=T*o+k*(5*g)+P*(5*f)+x*(5*p)+R*(5*u),U+=$>>>13,$&=8191;let F=U+A*u+I*h+S*d+_*l+O*c;U=F>>>13,F&=8191,F+=T*a+k*o+P*(5*g)+x*(5*f)+R*(5*p),U+=F>>>13,F&=8191;let q=U+A*p+I*u+S*h+_*d+O*l;U=q>>>13,q&=8191,q+=T*c+k*a+P*o+x*(5*g)+R*(5*f),U+=q>>>13,q&=8191;let W=U+A*f+I*p+S*u+_*h+O*d;U=W>>>13,W&=8191,W+=T*l+k*c+P*a+x*o+R*(5*g),U+=W>>>13,W&=8191;let H=U+A*g+I*f+S*p+_*u+O*h;U=H>>>13,H&=8191,H+=T*d+k*l+P*c+x*a+R*o,U+=H>>>13,H&=8191,U=(U<<2)+U|0,U=U+L|0,L=8191&U,U>>>=13,D+=U,r[0]=L,r[1]=D,r[2]=M,r[3]=B,r[4]=j,r[5]=$,r[6]=F,r[7]=q,r[8]=W,r[9]=H}finalize(){const{h:e,pad:t}=this,s=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,s[0]=e[0]+5,n=s[0]>>>13,s[0]&=8191;for(let t=1;t<10;t++)s[t]=e[t]+n,n=s[t]>>>13,s[t]&=8191;s[9]-=8192;let r=(1^n)-1;for(let e=0;e<10;e++)s[e]&=r;r=~r;for(let t=0;t<10;t++)e[t]=e[t]&r|s[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let s=1;s<8;s++)i=(e[s]+t[s]|0)+(i>>>16)|0,e[s]=65535&i;ou(s)}update(e){ru(this),nu(e=cu(e));const{buffer:t,blockLen:s}=this,n=e.length;for(let r=0;r<n;){const i=Math.min(s-this.pos,n-r);if(i!==s)t.set(e.subarray(r,r+i),this.pos),this.pos+=i,r+=i,this.pos===s&&(this.process(t,0,!1),this.pos=0);else for(;s<=n-r;r+=s)this.process(e,r)}return this}destroy(){ou(this.h,this.r,this.buffer,this.pad)}digestInto(e){ru(this),function(e,t){nu(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}(e,this),this.finished=!0;const{buffer:t,h:s}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let t=0;t<8;t++)e[r++]=s[t]>>>0,e[r++]=s[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}}const Su=function(e){const t=(t,s)=>e(s).update(cu(t)).digest(),s=e(new Uint8Array(32));return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=t=>e(t),t}((e=>new Iu(e)));const _u=function(e,t){const{allowShortKeys:s,extendNonceFn:n,counterLength:r,counterRight:i,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return su(r),su(o),tu(i),tu(s),(t,a,c,l,d=0)=>{nu(t),nu(a),nu(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),nu(l),su(d),d<0||d>=Cu)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const u=[];let p,f,g=t.length;if(32===g)u.push(p=uu(t)),f=yu;else{if(16!==g||!s)throw new Error(`arx: invalid 32-byte key, got length=${g}`);p=new Uint8Array(32),p.set(t),p.set(t,16),f=mu,u.push(p)}bu(a)||u.push(a=uu(a));const m=iu(p);if(n){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");n(f,m,iu(a.subarray(0,16)),m),a=a.subarray(16)}const y=16-r;if(y!==a.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,u.push(a)}const w=iu(a);return function(e,t,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(vu),d=iu(l),h=bu(r)&&bu(i),u=h?iu(r):Nu,p=h?iu(i):Nu;for(let f=0;f<c;o++){if(e(t,s,n,d,o,a),o>=Cu)throw new Error("arx: counter overflow");const g=Math.min(vu,c-f);if(h&&g===vu){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,s=0;s<Eu;s++)t=e+s,p[t]=u[t]^d[s];f+=vu}else{for(let e,t=0;t<g;t++)e=f+t,i[e]=r[e]^l[t];f+=g}}}(e,f,m,w,c,l,d,o),ou(...u),l}}((function(e,t,s,n,r,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],d=t[0],h=t[1],u=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],w=r,b=s[0],v=s[1],E=s[2],C=o,N=a,A=c,I=l,S=d,_=h,O=u,T=p,k=f,P=g,x=m,R=y,U=w,L=b,D=v,M=E;for(let e=0;e<i;e+=2)C=C+S|0,U=wu(U^C,16),k=k+U|0,S=wu(S^k,12),C=C+S|0,U=wu(U^C,8),k=k+U|0,S=wu(S^k,7),N=N+_|0,L=wu(L^N,16),P=P+L|0,_=wu(_^P,12),N=N+_|0,L=wu(L^N,8),P=P+L|0,_=wu(_^P,7),A=A+O|0,D=wu(D^A,16),x=x+D|0,O=wu(O^x,12),A=A+O|0,D=wu(D^A,8),x=x+D|0,O=wu(O^x,7),I=I+T|0,M=wu(M^I,16),R=R+M|0,T=wu(T^R,12),I=I+T|0,M=wu(M^I,8),R=R+M|0,T=wu(T^R,7),C=C+_|0,M=wu(M^C,16),x=x+M|0,_=wu(_^x,12),C=C+_|0,M=wu(M^C,8),x=x+M|0,_=wu(_^x,7),N=N+O|0,U=wu(U^N,16),R=R+U|0,O=wu(O^R,12),N=N+O|0,U=wu(U^N,8),R=R+U|0,O=wu(O^R,7),A=A+T|0,L=wu(L^A,16),k=k+L|0,T=wu(T^k,12),A=A+T|0,L=wu(L^A,8),k=k+L|0,T=wu(T^k,7),I=I+S|0,D=wu(D^I,16),P=P+D|0,S=wu(S^P,12),I=I+S|0,D=wu(D^I,8),P=P+D|0,S=wu(S^P,7);let B=0;n[B++]=o+C|0,n[B++]=a+N|0,n[B++]=c+A|0,n[B++]=l+I|0,n[B++]=d+S|0,n[B++]=h+_|0,n[B++]=u+O|0,n[B++]=p+T|0,n[B++]=f+k|0,n[B++]=g+P|0,n[B++]=m+x|0,n[B++]=y+R|0,n[B++]=w+U|0,n[B++]=b+L|0,n[B++]=v+D|0,n[B++]=E+M|0}),{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ou=new Uint8Array(16),Tu=(e,t)=>{e.update(t);const s=t.length%16;s&&e.update(Ou.subarray(s))},ku=new Uint8Array(32);function Pu(e,t,s,n,r){const i=e(t,s,ku),o=Su.create(i);r&&Tu(o,r),Tu(o,n);const a=hu(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return ou(i,a),c}const xu=((e,t)=>{function s(s,...n){if(nu(s),!au)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?nu(t):nu(t,e.nonceLength)}const r=e.tagLength;r&&void 0!==n[1]&&nu(n[1]);const i=t(s,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");nu(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,nu(e),o(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(nu(e),r&&e.length<r)throw new Error("invalid ciphertext length: smaller than tagLength="+r);return o(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(s,e),s})({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,s,n)=>({encrypt(r,i){const o=r.length;(i=lu(o+16,i,!1)).set(r);const a=i.subarray(0,-16);e(t,s,a,a,1);const c=Pu(e,t,s,a,n);return i.set(c,o),ou(c),i},decrypt(r,i){i=lu(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Pu(e,t,s,o,n);if(!function(e,t){if(e.length!==t.length)return!1;let s=0;for(let n=0;n<e.length;n++)s|=e[n]^t[n];return 0===s}(a,c))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),e(t,s,i,i,1),ou(c),i}}))(_u));class Ru extends Id{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,id(e);const s=Nd(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,r=new Uint8Array(n);r.set(s.length>n?e.create().update(s).digest():s);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),ld(r)}update(e){return od(this),this.iHash.update(e),this}digestInto(e){od(this),rd(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:s,finished:n,destroyed:r,blockLen:i,outputLen:o}=this;return e.finished=n,e.destroyed=r,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Uu=(e,t,s)=>new Ru(e,t).update(s).digest();Uu.create=(e,t)=>new Ru(e,t);const Lu=Uint8Array.from([0]),Du=Uint8Array.of();const Mu=(e,t,s,n,r)=>function(e,t,s,n=32){id(e),nd(n);const r=e.outputLen;if(n>255*r)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/r);void 0===s&&(s=Du);const o=new Uint8Array(i*r),a=Uu.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let e=0;e<i;e++)Lu[0]=e+1,c.update(0===e?Du:l).update(s).update(Lu).digestInto(l),o.set(l,r*e),a._cloneInto(c);return a.destroy(),c.destroy(),ld(l,Lu),o.slice(0,n)}(e,function(e,t,s){return id(e),void 0===s&&(s=new Uint8Array(e.outputLen)),Uu(e,Nd(s),Nd(t))}(e,t,s),n,r),Bu=ch,ju=BigInt(0),$u=BigInt(1);function Fu(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function qu(e,t,s=""){const n=sd(e),r=e?.length,i=void 0!==t;if(!n||i&&r!==t){throw new Error((s&&`"${s}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(n?`length=${r}`:"type="+typeof e))}return e}function Wu(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Hu(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?ju:BigInt("0x"+e)}function zu(e){return Hu(wd(e))}function Vu(e){return rd(e),Hu(wd(Uint8Array.from(e).reverse()))}function Ku(e,t){return Ed(e.toString(16).padStart(2*t,"0"))}function Gu(e,t){return Ku(e,t).reverse()}function Ju(e,t,s){let n;if("string"==typeof t)try{n=Ed(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!sd(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const r=n.length;if("number"==typeof s&&r!==s)throw new Error(e+" of length "+s+" expected, got "+r);return n}const Yu=e=>"bigint"==typeof e&&ju<=e;function Xu(e,t,s,n){if(!function(e,t,s){return Yu(e)&&Yu(t)&&Yu(s)&&t<=e&&e<s}(t,s,n))throw new Error("expected valid "+e+": "+s+" <= n < "+n+", got "+t)}function Zu(e){let t;for(t=0;e>ju;e>>=$u,t+=1);return t}const Qu=e=>($u<<BigInt(e))-$u;function ep(e,t,s={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function n(t,s,n){const r=e[t];if(n&&void 0===r)return;const i=typeof r;if(i!==s||null===r)throw new Error(`param "${t}" is invalid: expected ${s}, got ${i}`)}Object.entries(t).forEach((([e,t])=>n(e,t,!1))),Object.entries(s).forEach((([e,t])=>n(e,t,!0)))}function tp(e){const t=new WeakMap;return(s,...n)=>{const r=t.get(s);if(void 0!==r)return r;const i=e(s,...n);return t.set(s,i),i}}const sp=BigInt(0),np=BigInt(1),rp=BigInt(2),ip=BigInt(3),op=BigInt(4),ap=BigInt(5),cp=BigInt(7),lp=BigInt(8),dp=BigInt(9),hp=BigInt(16);function up(e,t){const s=e%t;return s>=sp?s:t+s}function pp(e,t,s){let n=e;for(;t-- >sp;)n*=n,n%=s;return n}function fp(e,t){if(e===sp)throw new Error("invert: expected non-zero number");if(t<=sp)throw new Error("invert: expected positive modulus, got "+t);let s=up(e,t),n=t,r=sp,i=np;for(;s!==sp;){const e=n%s,t=r-i*(n/s);n=s,s=e,r=i,i=t}if(n!==np)throw new Error("invert: does not exist");return up(r,t)}function gp(e,t,s){if(!e.eql(e.sqr(t),s))throw new Error("Cannot find square root")}function mp(e,t){const s=(e.ORDER+np)/op,n=e.pow(t,s);return gp(e,n,t),n}function yp(e,t){const s=(e.ORDER-ap)/lp,n=e.mul(t,rp),r=e.pow(n,s),i=e.mul(t,r),o=e.mul(e.mul(i,rp),r),a=e.mul(i,e.sub(o,e.ONE));return gp(e,a,t),a}function wp(e){if(e<ip)throw new Error("sqrt is not defined for small field");let t=e-np,s=0;for(;t%rp===sp;)t/=rp,s++;let n=rp;const r=Ap(e);for(;1===Cp(r,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===s)return mp;let i=r.pow(n,t);const o=(t+np)/rp;return function(e,n){if(e.is0(n))return n;if(1!==Cp(e,n))throw new Error("Cannot find square root");let r=s,a=e.mul(e.ONE,i),c=e.pow(n,t),l=e.pow(n,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,s=e.sqr(c);for(;!e.eql(s,e.ONE);)if(t++,s=e.sqr(s),t===r)throw new Error("Cannot find square root");const n=np<<BigInt(r-t-1),i=e.pow(a,n);r=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}function bp(e){return e%op===ip?mp:e%lp===ap?yp:e%hp===dp?function(e){const t=Ap(e),s=wp(e),n=s(t,t.neg(t.ONE)),r=s(t,n),i=s(t,t.neg(n)),o=(e+cp)/hp;return(e,t)=>{let s=e.pow(t,o),a=e.mul(s,n);const c=e.mul(s,r),l=e.mul(s,i),d=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);s=e.cmov(s,a,d),a=e.cmov(l,c,h);const u=e.eql(e.sqr(a),t),p=e.cmov(s,a,u);return gp(e,p,t),p}}(e):wp(e)}const vp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ep(e,t,s=!1){const n=new Array(t.length).fill(s?e.ZERO:void 0),r=t.reduce(((t,s,r)=>e.is0(s)?t:(n[r]=t,e.mul(t,s))),e.ONE),i=e.inv(r);return t.reduceRight(((t,s,r)=>e.is0(s)?t:(n[r]=e.mul(t,n[r]),e.mul(t,s))),i),n}function Cp(e,t){const s=(e.ORDER-np)/rp,n=e.pow(t,s),r=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function Np(e,t){void 0!==t&&nd(t);const s=void 0!==t?t:e.toString(2).length;return{nBitLength:s,nByteLength:Math.ceil(s/8)}}function Ap(e,t,s=!1,n={}){if(e<=sp)throw new Error("invalid field: expected ORDER > 0, got "+e);let r,i,o,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||s)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(r=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(s=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(r=t),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=Np(e,r);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const h=Object.freeze({ORDER:e,isLE:s,BITS:c,BYTES:l,MASK:Qu(c),ZERO:sp,ONE:np,allowedLengths:o,create:t=>up(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return sp<=t&&t<e},is0:e=>e===sp,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&np)===np,neg:t=>up(-t,e),eql:(e,t)=>e===t,sqr:t=>up(t*t,e),add:(t,s)=>up(t+s,e),sub:(t,s)=>up(t-s,e),mul:(t,s)=>up(t*s,e),pow:(e,t)=>function(e,t,s){if(s<sp)throw new Error("invalid exponent, negatives unsupported");if(s===sp)return e.ONE;if(s===np)return t;let n=e.ONE,r=t;for(;s>sp;)s&np&&(n=e.mul(n,r)),r=e.sqr(r),s>>=np;return n}(h,e,t),div:(t,s)=>up(t*fp(s,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>fp(t,e),sqrt:i||(t=>(d||(d=bp(e)),d(h,t))),toBytes:e=>s?Gu(e,l):Ku(e,l),fromBytes:(t,n=!0)=>{if(o){if(!o.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,s?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let r=s?Vu(t):zu(t);if(a&&(r=up(r,e)),!n&&!h.isValid(r))throw new Error("invalid field element: outside of range 0..ORDER");return r},invertBatch:e=>Ep(h,e),cmov:(e,t,s)=>s?t:e});return Object.freeze(h)}function Ip(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Sp(e){const t=Ip(e);return t+Math.ceil(t/2)}const _p=BigInt(0),Op=BigInt(1);function Tp(e,t){const s=t.negate();return e?s:t}function kp(e,t){const s=Ep(e.Fp,t.map((e=>e.Z)));return t.map(((t,n)=>e.fromAffine(t.toAffine(s[n]))))}function Pp(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function xp(e,t){Pp(e,t);const s=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Qu(e),maxNumber:s,shiftBy:BigInt(e)}}function Rp(e,t,s){const{windowSize:n,mask:r,maxNumber:i,shiftBy:o}=s;let a=Number(e&r),c=e>>o;a>n&&(a-=i,c+=Op);const l=t*n;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const Up=new WeakMap,Lp=new WeakMap;function Dp(e){return Lp.get(e)||1}function Mp(e){if(e!==_p)throw new Error("invalid wNAF")}class Bp{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,s=this.ZERO){let n=e;for(;t>_p;)t&Op&&(s=s.add(n)),n=n.double(),t>>=Op;return s}precomputeWindow(e,t){const{windows:s,windowSize:n}=xp(t,this.bits),r=[];let i=e,o=i;for(let e=0;e<s;e++){o=i,r.push(o);for(let e=1;e<n;e++)o=o.add(i),r.push(o);i=o.double()}return r}wNAF(e,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,r=this.BASE;const i=xp(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:d,offsetF:h}=Rp(s,e,i);s=o,c?r=r.add(Tp(d,t[h])):n=n.add(Tp(l,t[a]))}return Mp(s),{p:n,f:r}}wNAFUnsafe(e,t,s,n=this.ZERO){const r=xp(e,this.bits);for(let e=0;e<r.windows&&s!==_p;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=Rp(s,e,r);if(s=i,!a){const e=t[o];n=n.add(c?e.negate():e)}}return Mp(s),n}getPrecomputes(e,t,s){let n=Up.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof s&&(n=s(n)),Up.set(t,n))),n}cached(e,t,s){const n=Dp(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){const r=Dp(e);return 1===r?this._unsafeLadder(e,t,n):this.wNAFUnsafe(r,this.getPrecomputes(r,e,s),t,n)}createCache(e,t){Pp(t,this.bits),Lp.set(e,t),Up.delete(e)}hasCache(e){return 1!==Dp(e)}}function jp(e,t,s,n){(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,s)=>{if(!(e instanceof t))throw new Error("invalid point at index "+s)}))})(s,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,s)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+s)}))}(n,t);const r=s.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Zu(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Qu(c),d=new Array(Number(l)+1).fill(o);let h=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){d.fill(o);for(let t=0;t<i;t++){const r=n[t],i=Number(r>>BigInt(e)&l);d[i]=d[i].add(s[t])}let t=o;for(let e=d.length-1,s=o;e>0;e--)s=s.add(d[e]),t=t.add(s);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function $p(e,t,s){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=vp.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});ep(e,t)}(t),t}return Ap(e,{isLE:s})}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Cd("HashToScalar-");const Fp=BigInt(0),qp=BigInt(1),Wp=BigInt(2);function Hp(e){const t=function(e){return ep(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}(e),{P:s,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:o}=t,a="x25519"===n;if(!a&&"x448"!==n)throw new Error("invalid type");const c=o||_d,l=a?255:448,d=a?32:56,h=BigInt(a?9:5),u=BigInt(a?121665:39081),p=a?Wp**BigInt(254):Wp**BigInt(447),f=a?BigInt(8)*Wp**BigInt(251)-qp:BigInt(4)*Wp**BigInt(445)-qp,g=p+f+qp,m=e=>up(e,s),y=w(h);function w(e){return Gu(m(e),d)}function b(e,t){const n=function(e,t){Xu("u",e,Fp,s),Xu("scalar",t,p,g);const n=t,r=e;let o=qp,a=Fp,c=e,d=qp,h=Fp;for(let e=BigInt(l-1);e>=Fp;e--){const t=n>>e&qp;h^=t,({x_2:o,x_3:c}=E(h,o,c)),({x_2:a,x_3:d}=E(h,a,d)),h=t;const s=o+a,i=m(s*s),l=o-a,p=m(l*l),f=i-p,g=c+d,y=m((c-d)*s),w=m(g*l),b=y+w,v=y-w;c=m(b*b),d=m(r*m(v*v)),o=m(i*p),a=m(f*(i+m(u*f)))}({x_2:o,x_3:c}=E(h,o,c)),({x_2:a,x_3:d}=E(h,a,d));const f=i(a);return m(o*f)}(function(e){const t=Ju("u coordinate",e,d);return a&&(t[31]&=127),m(Vu(t))}(t),function(e){return Vu(r(Ju("scalar",e,d)))}(e));if(n===Fp)throw new Error("invalid private or public key received");return w(n)}function v(e){return b(e,y)}function E(e,t,s){const n=m(e*(t-s));return{x_2:t=m(t-n),x_3:s=m(s+n)}}const C={secretKey:d,publicKey:d,seed:d},N=(e=c(d))=>(rd(e,C.seed),e);return{keygen:function(e){const t=N(e);return{secretKey:t,publicKey:v(t)}},getSharedSecret:(e,t)=>b(e,t),getPublicKey:e=>v(e),scalarMult:b,scalarMultBase:v,utils:{randomSecretKey:N,randomPrivateKey:N},GuBytes:y.slice(),lengths:C}}const zp=BigInt(1),Vp=BigInt(2),Kp=BigInt(3),Gp=BigInt(5),Jp=BigInt(8),Yp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function Xp(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Zp=Ap({p:Yp,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}.p,{isLE:!0}),Qp=(()=>{const e=Zp.ORDER;return Hp({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:s,b2:n}=function(e){const t=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=Yp,o=e*e%i*e%i,a=pp(o,Vp,i)*o%i,c=pp(a,zp,i)*e%i,l=pp(c,Gp,i)*c%i,d=pp(l,t,i)*l%i,h=pp(d,s,i)*d%i,u=pp(h,n,i)*h%i,p=pp(u,r,i)*u%i,f=pp(p,r,i)*u%i,g=pp(f,t,i)*l%i;return{pow_p_5_8:pp(g,Vp,i)*e%i,b2:o}}(t);return up(pp(s,Kp,e)*n,e)},adjustScalarBytes:Xp})})(),ef=(e,t)=>(e+(e>=0?t:-t)/cf)/t;function tf(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function sf(e,t){const s={};for(let n of Object.keys(t))s[n]=void 0===e[n]?t[n]:e[n];return Fu(s.lowS,"lowS"),Fu(s.prehash,"prehash"),void 0!==s.format&&tf(s.format),s}class nf extends Error{constructor(e=""){super(e)}}const rf={Err:nf,_tlv:{encode:(e,t)=>{const{Err:s}=rf;if(e<0||e>256)throw new s("tlv.encode: wrong tag");if(1&t.length)throw new s("tlv.encode: unpadded data");const n=t.length/2,r=Wu(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?Wu(r.length/2|128):"";return Wu(e)+i+r+t},decode(e,t){const{Err:s}=rf;let n=0;if(e<0||e>256)throw new s("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new s("tlv.decode: wrong tlv");const r=t[n++];let i=0;if(!!(128&r)){const e=127&r;if(!e)throw new s("tlv.decode(long): indefinite length not supported");if(e>4)throw new s("tlv.decode(long): byte length is too big");const o=t.subarray(n,n+e);if(o.length!==e)throw new s("tlv.decode: length bytes not complete");if(0===o[0])throw new s("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(n+=e,i<128)throw new s("tlv.decode(long): not minimal encoding")}else i=r;const o=t.subarray(n,n+i);if(o.length!==i)throw new s("tlv.decode: wrong value length");return{v:o,l:t.subarray(n+i)}}},_int:{encode(e){const{Err:t}=rf;if(e<of)throw new t("integer: negative integers are not allowed");let s=Wu(e);if(8&Number.parseInt(s[0],16)&&(s="00"+s),1&s.length)throw new t("unexpected DER parsing assertion: unpadded hex");return s},decode(e){const{Err:t}=rf;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return zu(e)}},toSig(e){const{Err:t,_int:s,_tlv:n}=rf,r=Ju("signature",e),{v:i,l:o}=n.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(e){const{_tlv:t,_int:s}=rf,n=t.encode(2,s.encode(e.r))+t.encode(2,s.encode(e.s));return t.encode(48,n)}},of=BigInt(0),af=BigInt(1),cf=BigInt(2),lf=BigInt(3),df=BigInt(4);function hf(e,t){const{BYTES:s}=e;let n;if("bigint"==typeof t)n=t;else{let r=Ju("private key",t);try{n=e.fromBytes(r)}catch{throw new Error(`invalid private key: expected ui8a of size ${s}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function uf(e,t={}){const s=function(e,t,s={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const s=t[e];if(!("bigint"==typeof s&&s>_p))throw new Error(`CURVE.${e} must be positive bigint`)}const r=$p(t.p,s.Fp,n),i=$p(t.n,s.Fn,n),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!r.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:r,Fn:i}}("weierstrass",e,t),{Fp:n,Fn:r}=s;let i=s.CURVE;const{h:o,n:a}=i;ep(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!n.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ff(n,r);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,s){const{x:r,y:i}=t.toAffine(),o=n.toBytes(r);if(Fu(s,"isCompressed"),s){d();return Ad(pf(!n.isOdd(i)),o)}return Ad(Uint8Array.of(4),o,n.toBytes(i))},u=t.fromBytes||function(e){qu(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:s}=l,r=e.length,i=e[0],o=e.subarray(1);if(r!==t||2!==i&&3!==i){if(r===s&&4===i){const e=n.BYTES,t=n.fromBytes(o.subarray(0,e)),s=n.fromBytes(o.subarray(e,2*e));if(!f(t,s))throw new Error("bad point: is not on curve");return{x:t,y:s}}throw new Error(`bad point: got length ${r}, expected compressed=${t} or uncompressed=${s}`)}{const e=n.fromBytes(o);if(!n.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=p(e);let s;try{s=n.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}d();return 1==(1&i)!==n.isOdd(s)&&(s=n.neg(s)),{x:e,y:s}}};function p(e){const t=n.sqr(e),s=n.mul(t,e);return n.add(n.add(s,n.mul(e,i.a)),i.b)}function f(e,t){const s=n.sqr(t),r=p(e);return n.eql(s,r)}if(!f(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const g=n.mul(n.pow(i.a,lf),df),m=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(g,m)))throw new Error("bad curve params: a or b");function y(e,t,s=!1){if(!n.isValid(t)||s&&n.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof N))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,s){const[[n,r],[i,o]]=t,a=ef(o*e,s),c=ef(-r*e,s);let l=e-a*n-c*i,d=-a*r-c*o;const h=l<of,u=d<of;h&&(l=-l),u&&(d=-d);const p=Qu(Math.ceil(Zu(s)/2))+af;if(l<of||l>=p||d<of||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:l,k2neg:u,k2:d}}(e,c.basises,r.ORDER)}const v=tp(((e,t)=>{const{X:s,Y:r,Z:i}=e;if(n.eql(i,n.ONE))return{x:s,y:r};const o=e.is0();null==t&&(t=o?n.ONE:n.inv(i));const a=n.mul(s,t),c=n.mul(r,t),l=n.mul(i,t);if(o)return{x:n.ZERO,y:n.ZERO};if(!n.eql(l,n.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),E=tp((e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:s,y:r}=e.toAffine();if(!n.isValid(s)||!n.isValid(r))throw new Error("bad point: x or y not field elements");if(!f(s,r))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));function C(e,t,s,r,i){return s=new N(n.mul(s.X,e),s.Y,s.Z),t=Tp(r,t),s=Tp(i,s),t.add(s)}class N{constructor(e,t,s){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",s),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:s}=e||{};if(!e||!n.isValid(t)||!n.isValid(s))throw new Error("invalid affine point");if(e instanceof N)throw new Error("projective point not allowed");return n.is0(t)&&n.is0(s)?N.ZERO:new N(t,s,n.ONE)}static fromBytes(e){const t=N.fromAffine(u(qu(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return N.fromBytes(Ju("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return I.createCache(this,e),t||this.multiply(lf),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){w(e);const{X:t,Y:s,Z:r}=this,{X:i,Y:o,Z:a}=e,c=n.eql(n.mul(t,a),n.mul(i,r)),l=n.eql(n.mul(s,a),n.mul(o,r));return c&&l}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,s=n.mul(t,lf),{X:r,Y:o,Z:a}=this;let c=n.ZERO,l=n.ZERO,d=n.ZERO,h=n.mul(r,r),u=n.mul(o,o),p=n.mul(a,a),f=n.mul(r,o);return f=n.add(f,f),d=n.mul(r,a),d=n.add(d,d),c=n.mul(e,d),l=n.mul(s,p),l=n.add(c,l),c=n.sub(u,l),l=n.add(u,l),l=n.mul(c,l),c=n.mul(f,c),d=n.mul(s,d),p=n.mul(e,p),f=n.sub(h,p),f=n.mul(e,f),f=n.add(f,d),d=n.add(h,h),h=n.add(d,h),h=n.add(h,p),h=n.mul(h,f),l=n.add(l,h),p=n.mul(o,a),p=n.add(p,p),h=n.mul(p,f),c=n.sub(c,h),d=n.mul(p,u),d=n.add(d,d),d=n.add(d,d),new N(c,l,d)}add(e){w(e);const{X:t,Y:s,Z:r}=this,{X:o,Y:a,Z:c}=e;let l=n.ZERO,d=n.ZERO,h=n.ZERO;const u=i.a,p=n.mul(i.b,lf);let f=n.mul(t,o),g=n.mul(s,a),m=n.mul(r,c),y=n.add(t,s),b=n.add(o,a);y=n.mul(y,b),b=n.add(f,g),y=n.sub(y,b),b=n.add(t,r);let v=n.add(o,c);return b=n.mul(b,v),v=n.add(f,m),b=n.sub(b,v),v=n.add(s,r),l=n.add(a,c),v=n.mul(v,l),l=n.add(g,m),v=n.sub(v,l),h=n.mul(u,b),l=n.mul(p,m),h=n.add(l,h),l=n.sub(g,h),h=n.add(g,h),d=n.mul(l,h),g=n.add(f,f),g=n.add(g,f),m=n.mul(u,m),b=n.mul(p,b),g=n.add(g,m),m=n.sub(f,m),m=n.mul(u,m),b=n.add(b,m),f=n.mul(g,b),d=n.add(d,f),f=n.mul(v,b),l=n.mul(y,l),l=n.sub(l,f),f=n.mul(y,g),h=n.mul(v,h),h=n.add(h,f),new N(l,d,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(N.ZERO)}multiply(e){const{endo:s}=t;if(!r.isValidNot0(e))throw new Error("invalid scalar: out of range");let n,i;const o=e=>I.cached(this,e,(e=>kp(N,e)));if(s){const{k1neg:t,k1:r,k2neg:a,k2:c}=b(e),{p:l,f:d}=o(r),{p:h,f:u}=o(c);i=d.add(u),n=C(s.beta,l,h,t,a)}else{const{p:t,f:s}=o(e);n=t,i=s}return kp(N,[n,i])[0]}multiplyUnsafe(e){const{endo:s}=t,n=this;if(!r.isValid(e))throw new Error("invalid scalar: out of range");if(e===of||n.is0())return N.ZERO;if(e===af)return n;if(I.hasCache(this))return this.multiply(e);if(s){const{k1neg:t,k1:r,k2neg:i,k2:o}=b(e),{p1:a,p2:c}=function(e,t,s,n){let r=t,i=e.ZERO,o=e.ZERO;for(;s>_p||n>_p;)s&Op&&(i=i.add(r)),n&Op&&(o=o.add(r)),r=r.double(),s>>=Op,n>>=Op;return{p1:i,p2:o}}(N,n,r,o);return C(s.beta,a,c,t,i)}return I.unsafe(n,e)}multiplyAndAddUnsafe(e,t,s){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(s));return n.is0()?void 0:n}toAffine(e){return v(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===af||(e?e(N,this):I.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===af?this:e?e(N,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Fu(e,"isCompressed"),this.assertValidity(),h(N,this,e)}toHex(e=!0){return wd(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return kp(N,e)}static msm(e,t){return jp(N,r,e,t)}static fromPrivateKey(e){return N.BASE.multiply(hf(r,e))}}N.BASE=new N(i.Gx,i.Gy,n.ONE),N.ZERO=new N(n.ZERO,n.ONE,n.ZERO),N.Fp=n,N.Fn=r;const A=r.BITS,I=new Bp(N,t.endo?Math.ceil(A/2):A);return N.BASE.precompute(8),N}function pf(e){return Uint8Array.of(e?2:3)}function ff(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function gf(e,t={}){const{Fn:s}=e,n=t.randomBytes||_d,r=Object.assign(ff(e.Fp,s),{seed:Sp(s.ORDER)});function i(e){try{return!!hf(s,e)}catch{return!1}}function o(e=n(r.seed)){return function(e,t,s=!1){const n=e.length,r=Ip(t),i=Sp(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=up(s?Vu(e):zu(e),t-np)+np;return s?Gu(o,r):Ku(o,r)}(qu(e,r.seed,"seed"),s.ORDER)}function a(t,n=!0){return e.BASE.multiply(hf(s,t)).toBytes(n)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:n,publicKey:i,publicKeyUncompressed:o}=r;if(s.allowedLengths||n===i)return;const a=Ju("key",t).length;return a===i||a===o}return Object.freeze({getPublicKey:a,getSharedSecret:function(t,n,r=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(n))throw new Error("second arg must be public key");const i=hf(s,t);return e.fromHex(n).multiply(i).toBytes(r)},keygen:function(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:{isValidSecretKey:i,isValidPublicKey:function(t,s){const{publicKey:n,publicKeyUncompressed:i}=r;try{const r=t.length;return!(!0===s&&r!==n||!1===s&&r!==i)&&!!e.fromBytes(t)}catch{return!1}},randomSecretKey:o,isValidPrivateKey:i,randomPrivateKey:o,normPrivateKeyToScalar:e=>hf(s,e),precompute:(t=8,s=e.BASE)=>s.precompute(t,!1)},lengths:r})}function mf(e,t,s={}){id(t),ep(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||_d,r=s.hmac||((e,...s)=>Uu(t,e,Ad(...s))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:u,lengths:p}=gf(e,s),f={prehash:!1,lowS:"boolean"==typeof s.lowS&&s.lowS,format:void 0,extraEntropy:!1},g="compact";function m(e){return e>a>>af}function y(e,t){if(!o.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class w{constructor(e,t,s){this.r=y("r",e),this.s=y("s",t),null!=s&&(this.recovery=s),Object.freeze(this)}static fromBytes(e,t=g){let s;if(function(e,t){tf(t);const s=p.signature;qu(e,"compact"===t?s:"recovered"===t?s+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:s}=rf.toSig(qu(e));return new w(t,s)}"recovered"===t&&(s=e[0],t="compact",e=e.subarray(1));const n=o.BYTES,r=e.subarray(0,n),i=e.subarray(n,2*n);return new w(o.fromBytes(r),o.fromBytes(i),s)}static fromHex(e,t){return this.fromBytes(Ed(e),t)}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const s=i.ORDER,{r:n,s:r,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*cf<s&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?n+a:n;if(!i.isValid(l))throw new Error("recovery id 2 or 3 invalid");const d=i.toBytes(l),h=e.fromBytes(Ad(pf(0==(1&c)),d)),u=o.inv(l),p=v(Ju("msgHash",t)),f=o.create(-p*u),g=o.create(r*u),m=e.BASE.multiplyUnsafe(f).add(h.multiplyUnsafe(g));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=g){if(tf(e),"der"===e)return Ed(rf.hexFromSig(this));const t=o.toBytes(this.r),s=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return Ad(Uint8Array.of(this.recovery),t,s)}return Ad(t,s)}toHex(e){return wd(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(Ju("sig",e),"compact")}static fromDER(e){return w.fromBytes(Ju("sig",e),"der")}normalizeS(){return this.hasHighS()?new w(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return wd(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return wd(this.toBytes("compact"))}}const b=s.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=zu(e),s=8*e.length-c;return s>0?t>>BigInt(s):t},v=s.bits2int_modN||function(e){return o.create(b(e))},E=Qu(c);function C(e){return Xu("num < 2^"+c,e,of,E),o.toBytes(e)}function N(e,s){return qu(e,void 0,"message"),s?qu(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:u,lengths:p,Point:e,sign:function(s,i,a={}){s=Ju("message",s);const{seed:c,k2sig:l}=function(t,s,r){if(["recovered","canonical"].some((e=>e in r)))throw new Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=sf(r,f);t=N(t,a);const l=v(t),d=hf(o,s),h=[C(d),C(l)];if(null!=c&&!1!==c){const e=!0===c?n(p.secretKey):c;h.push(Ju("extraEntropy",e))}const u=Ad(...h),g=l;return{seed:u,k2sig:function(t){const s=b(t);if(!o.isValidNot0(s))return;const n=o.inv(s),r=e.BASE.multiply(s).toAffine(),a=o.create(r.x);if(a===of)return;const c=o.create(n*o.create(g+a*d));if(c===of)return;let l=(r.x===a?0:2)|Number(r.y&af),h=c;return i&&m(c)&&(h=o.neg(c),l^=1),new w(a,h,l)}}}(s,i,a);return function(e,t,s){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof s)throw new Error("hmacFn must be a function");const n=e=>new Uint8Array(e),r=e=>Uint8Array.of(e);let i=n(e),o=n(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>s(o,i,...e),d=(e=n(0))=>{o=l(r(0),e),i=l(),0!==e.length&&(o=l(r(1),e),i=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const s=[];for(;e<t;){i=l();const t=i.slice();s.push(t),e+=i.length}return Ad(...s)};return(e,t)=>{let s;for(c(),d(e);!(s=t(h()));)d();return c(),s}}(t.outputLen,o.BYTES,r)(c,l)},verify:function(t,s,n,r={}){const{lowS:i,prehash:a,format:c}=sf(r,f);if(n=Ju("publicKey",n),s=N(Ju("message",s),a),"strict"in r)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const s="string"==typeof e||sd(e),n=!s&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!s&&!n)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)t=new w(e.r,e.s);else if(s){try{t=w.fromBytes(Ju("sig",e),"der")}catch(e){if(!(e instanceof rf.Err))throw e}if(!t)try{t=w.fromBytes(Ju("sig",e),"compact")}catch{return!1}}return t||!1}(t):w.fromBytes(Ju("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(n);if(i&&l.hasHighS())return!1;const{r:r,s:a}=l,c=v(s),d=o.inv(a),h=o.create(c*d),u=o.create(r*d),p=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(u));return!p.is0()&&o.create(p.x)===r}catch{return!1}},recoverPublicKey:function(e,t,s={}){const{prehash:n}=sf(s,f);return t=N(t,n),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function yf(e){const{CURVE:t,curveOpts:s}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},s=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map((e=>Math.ceil(e/2))))):void 0;return{CURVE:t,curveOpts:{Fp:s,Fn:Ap(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:s,hash:e.hash,ecdsaOpts:n}}function wf(e){const{CURVE:t,curveOpts:s,hash:n,ecdsaOpts:r}=yf(e);return function(e,t){const s=t.Point;return Object.assign({},t,{ProjectivePoint:s,CURVE:Object.assign({},e,Np(s.Fn.ORDER,s.Fn.BITS))})}(e,mf(uf(t,s),n,r))}function bf(e,t){const s=t=>wf({...e,hash:t});return{...s(t),create:s}}const vf={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Ef={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Cf={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Nf=Ap(vf.p),Af=Ap(Ef.p),If=Ap(Cf.p),Sf=bf({...vf,Fp:Nf,lowS:!1},ch);bf({...Ef,Fp:Af,lowS:!1},dh),bf({...Cf,Fp:If,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},lh);const _f=Sf,Of="base10",Tf="base16",kf="base64pad",Pf="base64url",xf="utf8",Rf=0,Uf=1,Lf=2,Df=0,Mf=1,Bf=12,jf=32;function $f(){const e=_d(jf);return c(e,Tf)}function Ff(e){const t=Bu(a(e,Tf));return c(t,Tf)}function qf(e){const t=Bu(a(e,xf));return c(t,Tf)}function Wf(e){return a(`${e}`,Of)}function Hf(e){return Number(c(e,Of))}function zf(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Vf(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=(4-t.length%4)%4;return t+"=".repeat(s)}function Kf(e){if(Hf(e.type)===Lf)return c(w([e.type,e.sealed]),kf);if(Hf(e.type)===Uf){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return c(w([e.type,e.senderPublicKey,e.iv,e.sealed]),kf)}return c(w([e.type,e.iv,e.sealed]),kf)}function Gf(e){const t=(e.encoding||kf)===Pf?Vf(e.encoded):e.encoded,s=a(t,kf),n=s.slice(Df,Mf),r=Mf;if(Hf(n)===Uf){const e=r+jf,t=e+Bf,i=s.slice(r,e),o=s.slice(e,t);return{type:n,sealed:s.slice(t),iv:o,senderPublicKey:i}}if(Hf(n)===Lf){return{type:n,sealed:s.slice(r),iv:_d(Bf)}}const i=r+Bf,o=s.slice(r,i);return{type:n,sealed:s.slice(i),iv:o}}function Jf(e){const t=e?.type||Rf;if(t===Uf){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function Yf(e){return e.type===Uf&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function Xf(e){return e.type===Lf}function Zf(e,t){const[s,n,r]=e.split("."),i=Buffer.from(Vf(r),"base64");if(64!==i.length)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=Bu(`${s}.${n}`),l=function(e){const t=Buffer.from(e.x,"base64"),s=Buffer.from(e.y,"base64");return w([new Uint8Array([4]),t,s])}(t);if(!_f.verify(w([o,a]),c,l))throw new Error("Invalid signature");return uc(e).payload}function Qf(e){return e?.relay||{protocol:"irn"}}function eg(e){const t=Hc[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}var tg=Object.defineProperty,sg=Object.defineProperties,ng=Object.getOwnPropertyDescriptors,rg=Object.getOwnPropertySymbols,ig=Object.prototype.hasOwnProperty,og=Object.prototype.propertyIsEnumerable,ag=(e,t,s)=>t in e?tg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,cg=(e,t)=>{for(var s in t||(t={}))ig.call(t,s)&&ag(e,s,t[s]);if(rg)for(var s of rg(t))og.call(t,s)&&ag(e,s,t[s]);return e};function lg(e,t="-"){const s={},n="relay"+t;return Object.keys(e).forEach((t=>{if(t.startsWith(n)){const r=t.replace(n,""),i=e[t];s[r]=i}})),s}function dg(e){if(!e.includes("wc:")){const t=Ul(e);null!=t&&t.includes("wc:")&&(e=t)}const t=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),s=-1!==e.indexOf("?")?e.indexOf("?"):void 0,n=e.substring(0,t),r=e.substring(t+1,s).split("@"),i=typeof s<"u"?e.substring(s):"",o=new URLSearchParams(i),a=Object.fromEntries(o.entries()),c="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:n,topic:hg(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:lg(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function hg(e){return e.startsWith("//")?e.substring(2):e}function ug(e){const t=new URLSearchParams,s=cg(cg(((e,t)=>sg(e,ng(t)))(cg({},function(e,t="-"){const s={};return Object.keys(e).forEach((n=>{const r=n,i="relay"+t+r;e[r]&&(s[i]=e[r])})),s}(e.relay)),{symKey:e.symKey}),e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()}),e.methods&&{methods:e.methods.join(",")});return Object.entries(s).sort((([e],[t])=>e.localeCompare(t))).forEach((([e,s])=>{void 0!==s&&t.append(e,String(s))})),`${e.protocol}:${e.topic}@${e.version}?${t}`}function pg(e,t,s){return`${e}?wc_ev=${s}&topic=${t}`}var fg=Object.defineProperty,gg=Object.defineProperties,mg=Object.getOwnPropertyDescriptors,yg=Object.getOwnPropertySymbols,wg=Object.prototype.hasOwnProperty,bg=Object.prototype.propertyIsEnumerable,vg=(e,t,s)=>t in e?fg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Eg=(e,t)=>{for(var s in t||(t={}))wg.call(t,s)&&vg(e,s,t[s]);if(yg)for(var s of yg(t))bg.call(t,s)&&vg(e,s,t[s]);return e},Cg=(e,t)=>gg(e,mg(t));function Ng(e){const t=[];return e.forEach((e=>{const[s,n]=e.split(":");t.push(`${s}:${n}`)})),t}function Ag(e){const t=[];return Object.values(e).forEach((e=>{t.push(...Ng(e.accounts))})),[...new Set(t)]}function Ig(e){return e.includes(":")}function Sg(e){return Ig(e)?e.split(":")[0]:e}function _g(e){var t,s,n;const r={};if(!kg(e))return r;for(const[i,o]of Object.entries(e)){const e=Ig(i)?[i]:o.chains,a=o.methods||[],c=o.events||[],l=Sg(i);r[l]=Cg(Eg({},r[l]),{chains:Tl(e,null==(t=r[l])?void 0:t.chains),methods:Tl(a,null==(s=r[l])?void 0:s.methods),events:Tl(c,null==(n=r[l])?void 0:n.events)})}return r}function Og(e,t){t=t.map((e=>e.replace("did:pkh:","")));const s=function(e){const t={};return e?.forEach((e=>{var s;const[n,r]=e.split(":");t[n]||(t[n]={accounts:[],chains:[],events:[],methods:[]}),t[n].accounts.push(e),null==(s=t[n].chains)||s.push(`${n}:${r}`)})),t}(t);for(const[t,n]of Object.entries(s))n.methods?n.methods=Tl(n.methods,e):n.methods=e,n.events=["chainChanged","accountsChanged"];return s}function Tg(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function kg(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Pg(e){return typeof e>"u"}function xg(e,t){return!(!t||!Pg(e))||"string"==typeof e&&!!e.trim().length}function Rg(e,t){return!(!t||!Pg(e))||"number"==typeof e&&!isNaN(e)}function Ug(e){return!(!xg(e,!1)||!e.includes(":"))&&2===e.split(":").length}function Lg(e){let t=!0;return Tg(e)?e.length&&(t=e.every((e=>xg(e,!1)))):t=!1,t}function Dg(e,t,s){let n=null;return Object.entries(e).forEach((([e,r])=>{if(n)return;const i=function(e,t,s){let n=null;return Tg(t)&&t.length?t.forEach((e=>{n||Ug(e)||(n=Xc("UNSUPPORTED_CHAINS",`${s}, chain ${e} should be a string and conform to "namespace:chainId" format`))})):Ug(e)||(n=Xc("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}(e,Kc(e,r),`${t} ${s}`);i&&(n=i)})),n}function Mg(e,t){let s=null;return Tg(e)?e.forEach((e=>{s||function(e){if(xg(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&Ug(e)}}return!1}(e)||(s=Xc("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))})):s=Xc("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function Bg(e,t){let s=null;return Object.values(e).forEach((e=>{if(s)return;const n=function(e,t){let s=null;return Lg(e?.methods)?Lg(e?.events)||(s=Xc("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):s=Xc("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),s}(e,`${t}, namespace`);n&&(s=n)})),s}function jg(e,t){let s=null;if(e&&kg(e)){const n=Bg(e,t);n&&(s=n);const r=function(e,t){let s=null;return Object.values(e).forEach((e=>{if(s)return;const n=Mg(e?.accounts,`${t} namespace`);n&&(s=n)})),s}(e,t);r&&(s=r)}else s=Yc("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return s}function $g(e){return xg(e.protocol,!0)}function Fg(e){return typeof e<"u"&&null!==typeof e}function qg(e,t){return!(!Ug(t)||!Ag(e).includes(t))}function Wg(e,t,s){return!!xg(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach((e=>{Ng(e.accounts).includes(t)&&s.push(...e.methods)})),s}(e,t).includes(s)}function Hg(e,t,s){return!!xg(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach((e=>{Ng(e.accounts).includes(t)&&s.push(...e.events)})),s}(e,t).includes(s)}function zg(e,t,s){let n=null;const r=function(e){const t={};return Object.keys(e).forEach((s=>{var n;s.includes(":")?t[s]=e[s]:null==(n=e[s].chains)||n.forEach((n=>{t[n]={methods:e[s].methods,events:e[s].events}}))})),t}(e),i=function(e){const t={};return Object.keys(e).forEach((s=>{if(s.includes(":"))t[s]=e[s];else{const n=Ng(e[s].accounts);n?.forEach((n=>{t[n]={accounts:e[s].accounts.filter((e=>e.includes(`${n}:`))),methods:e[s].methods,events:e[s].events}}))}})),t}(t),o=Object.keys(r),a=Object.keys(i),c=Vg(Object.keys(e)),l=Vg(Object.keys(t)),d=c.filter((e=>!l.includes(e)));return d.length&&(n=Yc("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(t).toString()}`)),bl(o,a)||(n=Yc("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach((e=>{if(!e.includes(":")||n)return;const r=Ng(t[e].accounts);r.includes(e)||(n=Yc("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${r.toString()}`))})),o.forEach((e=>{n||(bl(r[e].methods,i[e].methods)?bl(r[e].events,i[e].events)||(n=Yc("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${e}`)):n=Yc("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${e}`))})),n}function Vg(e){return[...new Set(e.map((e=>e.includes(":")?e.split(":")[0]:e)))]}function Kg(){const e=pl();return new Promise((t=>{switch(e){case cl.browser:t(ul()&&navigator?.onLine);break;case cl.reactNative:t(async function(){if(hl()&&typeof global<"u"&&null!=global&&global.NetInfo){const e=await(null==global?void 0:global.NetInfo.fetch());return e?.isConnected}return!0}());break;case cl.node:default:t(!0)}}))}function Gg(e){switch(pl()){case cl.browser:!function(e){!hl()&&ul()&&(window.addEventListener("online",(()=>e(!0))),window.addEventListener("offline",(()=>e(!1))))}(e);break;case cl.reactNative:!function(e){hl()&&typeof global<"u"&&null!=global&&global.NetInfo&&global?.NetInfo.addEventListener((t=>e(t?.isConnected)))}(e)}}const Jg={};class Yg{static get(e){return Jg[e]}static set(e,t){Jg[e]=t}static delete(e){delete Jg[e]}}function Xg({publicKey:e,signature:t,payload:s}){var n;const r=Zg(s.method),i=128|parseInt((null==(n=s.version)?void 0:n.toString())||"4"),o=function(e){const t=Bc.decode(e)[0];return 42===t?0:60===t?2:1}(s.address),a="00"===s.era?new Uint8Array([0]):Zg(s.era);if(1!==a.length&&2!==a.length)throw new Error("Invalid era length");const c=parseInt(s.nonce,16),l=new Uint8Array([255&c,c>>8&255]),d=BigInt(`0x${function(e){return e.startsWith("0x")?e.slice(2):e}(s.tip)}`),h=function(e){if(e<BigInt(1)<<BigInt(6))return new Uint8Array([Number(e<<BigInt(2))]);if(e<BigInt(1)<<BigInt(14)){const t=e<<BigInt(2)|BigInt(1);return new Uint8Array([Number(t&BigInt(255)),Number(t>>BigInt(8)&BigInt(255))])}if(e<BigInt(1)<<BigInt(30)){const t=e<<BigInt(2)|BigInt(2);return new Uint8Array([Number(t&BigInt(255)),Number(t>>BigInt(8)&BigInt(255)),Number(t>>BigInt(16)&BigInt(255)),Number(t>>BigInt(24)&BigInt(255))])}throw new Error("BigInt compact encoding not supported > 2^30")}(d),u=new Uint8Array([0,...e,o,...t,...a,...l,...h,...r]),p=function(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){const t=e<<2|1;return new Uint8Array([255&t,t>>8&255])}if(e<1<<30){const t=e<<2|2;return new Uint8Array([255&t,t>>8&255,t>>16&255,t>>24&255])}throw new Error("Compact encoding > 2^30 not supported")}(u.length+1);return new Uint8Array([...p,i,...u])}function Zg(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map((e=>parseInt(e,16))))}function Qg(e){const t=Uint8Array.from(Buffer.from(e.signature,"hex")),s=function(e){const t=Bc.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}(e.transaction.address),n=Xg({publicKey:s,signature:t,payload:e.transaction});return function(e){const t=Zg(e),s=g.blake2b(t,void 0,32);return"0x"+Buffer.from(s).toString("hex")}(Buffer.from(n).toString("hex"))}function em({logger:e,name:t}){const s="string"==typeof e?Ar({opts:{level:e,name:t}}).logger:e;return s.level="string"==typeof e?e:e.level,s}class tm extends b{constructor(e){super(e),this.events=new t,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(v(e.method,e.params||[],e.id||E().toString()),t)}async requestStrict(e,t){return new Promise((async(s,n)=>{if(!this.connection.connected)try{await this.open()}catch(e){n(e)}this.events.on(`${e.id}`,(e=>{C(e)?n(e.error):s(e.result)}));try{await this.connection.send(e,t)}catch(e){n(e)}}))}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),N(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&3e3===e.code&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),"string"==typeof e&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",(e=>this.onPayload(e))),this.connection.on("close",(e=>this.onClose(e))),this.connection.on("error",(e=>this.events.emit("error",e))),this.connection.on("register_error",(e=>this.onClose())),this.hasRegisteredEventListeners=!0)}}const sm=e=>e.split("?")[0],nm=typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws");class rm{constructor(e){if(this.url=e,this.events=new t,this.registering=!1,!A(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise(((e,t)=>{typeof this.socket>"u"?t(new Error("Connection already closed")):(this.socket.onclose=t=>{this.onClose(t),e()},this.socket.close())}))}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(i(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!A(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return t(new Error("WebSocket connection is missing or invalid"));e(this.socket)}))}))}return this.url=e,this.registering=!0,new Promise(((t,s)=>{const n=I.isReactNative()?void 0:{rejectUnauthorized:!S(e)},r=new nm(e,[],n);typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u"?r.onerror=e=>{const t=e;s(this.emitError(t.error))}:r.on("error",(e=>{s(this.emitError(e))})),r.onopen=()=>{this.onOpen(r),t(r)}}))}onOpen(e){e.onmessage=e=>this.onPayload(e),e.onclose=e=>this.onClose(e),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const t="string"==typeof e.data?r(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const s=this.parseError(t),n=s.message||s.toString(),r=_(e,n);this.events.emit("payload",r)}parseError(e,t=this.url){return O(e,sm(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${sm(this.url)}`));return this.events.emit("register_error",t),t}}const im="core",om=`wc@2:${im}:`,am="error",cm={database:":memory:"},lm="client_ed25519_seed",dm=s.ONE_DAY,hm=s.SIX_HOURS,um="wss://relay.walletconnect.org",pm="relayer_message",fm="relayer_message_ack",gm="relayer_connect",mm="relayer_disconnect",ym="relayer_error",wm="relayer_connection_stalled",bm="relayer_publish",vm="payload",Em="connect",Cm="disconnect",Nm="error",Am="2.23.7",Im={link_mode:"link_mode",relay:"relay"},Sm="inbound",_m="outbound",Om="WALLETCONNECT_LINK_MODE_APPS",Tm="subscription_created",km="subscription_deleted",Pm="subscription_sync",xm="subscription_resubscribed",Rm={wc_pairingDelete:{req:{ttl:s.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:s.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:s.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:s.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:s.ONE_DAY,prompt:!1,tag:0},res:{ttl:s.ONE_DAY,prompt:!1,tag:0}}},Um="pairing_create",Lm="pairing_expire",Dm="pairing_delete",Mm="pairing_ping",Bm="history_created",jm="history_updated",$m="history_deleted",Fm="history_sync",qm="expirer_created",Wm="expirer_deleted",Hm="expirer_expired",zm="expirer_sync",Vm="https://verify.walletconnect.org",Km=Vm,Gm=`${Km}/v3`,Jm=["https://verify.walletconnect.com",Vm],Ym="pairing_started",Xm="pairing_uri_validation_success",Zm="pairing_uri_not_expired",Qm="store_new_pairing",ey="subscribing_pairing_topic",ty="subscribe_pairing_topic_success",sy="existing_pairing",ny="pairing_not_expired",ry="emit_inactive_pairing",iy="emit_session_proposal",oy="no_internet_connection",ay="malformed_pairing_uri",cy="active_pairing_already_exists",ly="subscribe_pairing_topic_failure",dy="pairing_expired",hy="proposal_listener_not_found",uy="session_approve_started",py="session_namespaces_validation_success",fy="subscribing_session_topic",gy="subscribe_session_topic_success",my="session_approve_publish_success",yy="store_session",wy="session_request_response_started",by="session_request_response_validation_success",vy="session_request_response_publish_started",Ey="no_internet_connection",Cy="proposal_expired",Ny="subscribe_session_topic_failure",Ay="session_approve_namespace_validation_failure",Iy="proposal_not_found",Sy="session_request_response_validation_failure",_y="session_request_response_publish_failure",Oy="authenticated_session_approve_started",Ty="create_authenticated_session_topic",ky="cacaos_verified",Py="store_authenticated_session",xy="subscribing_authenticated_session_topic",Ry="subscribe_authenticated_session_topic_success",Uy="publishing_authenticated_session_approve",Ly="no_internet_connection",Dy="invalid_cacao",My="subscribe_authenticated_session_topic_failure",By="authenticated_session_approve_publish_failure",jy="authenticated_session_pending_request_not_found";var $y=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var r=0;r<e.length;r++){var i=e.charAt(r),o=i.charCodeAt(0);if(255!==s[o])throw new TypeError(i+" is ambiguous");s[o]=r}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,r=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*l+1>>>0,o=new Uint8Array(i);e[t];){var d=s[e.charCodeAt(t)];if(255===d)return;for(var h=0,u=i-1;(0!==d||h<r)&&-1!==u;u--,h++)d+=a*o[u]>>>0,o[u]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");r=h,t++}if(" "!==e[t]){for(var p=i-r;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)f[g++]=o[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var s=0,n=0,r=0,i=t.length;r!==i&&0===t[r];)r++,s++;for(var o=(i-r)*d+1>>>0,l=new Uint8Array(o);r!==i;){for(var h=t[r],u=0,p=o-1;(0!==h||u<n)&&-1!==p;p--,u++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=u,r++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(s);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode:function(e){var s=h(e);if(s)return s;throw new Error(`Non-${t} character`)}}},Fy=$y;const qy=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Wy{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Hy{constructor(e,t,s){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=s}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Vy(this,e)}}class zy{constructor(e){this.decoders=e}or(e){return Vy(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Vy=(e,t)=>new zy({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Ky{constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Wy(e,t,s),this.decoder=new Hy(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Gy=({name:e,prefix:t,encode:s,decode:n})=>new Ky(e,t,s,n),Jy=({prefix:e,name:t,alphabet:s})=>{const{encode:n,decode:r}=Fy(s,t);return Gy({prefix:e,name:t,encode:n,decode:e=>qy(r(e))})},Yy=({name:e,prefix:t,bitsPerChar:s,alphabet:n})=>Gy({prefix:t,name:e,encode:e=>((e,t,s)=>{const n="="===t[t.length-1],r=(1<<s)-1;let i="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>s;)o-=s,i+=t[r&a>>o];if(o&&(i+=t[r&a<<s-o]),n)for(;i.length*s&7;)i+="=";return i})(e,n,s),decode:t=>((e,t,s,n)=>{const r={};for(let e=0;e<t.length;++e)r[t[e]]=e;let i=e.length;for(;"="===e[i-1];)--i;const o=new Uint8Array(i*s/8|0);let a=0,c=0,l=0;for(let t=0;t<i;++t){const i=r[e[t]];if(void 0===i)throw new SyntaxError(`Non-${n} character`);c=c<<s|i,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,n,s,e)}),Xy=Gy({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var Zy=Object.freeze({__proto__:null,identity:Xy});const Qy=Yy({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ew=Object.freeze({__proto__:null,base2:Qy});const tw=Yy({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var sw=Object.freeze({__proto__:null,base8:tw});const nw=Jy({prefix:"9",name:"base10",alphabet:"0123456789"});var rw=Object.freeze({__proto__:null,base10:nw});const iw=Yy({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ow=Yy({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var aw=Object.freeze({__proto__:null,base16:iw,base16upper:ow});const cw=Yy({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lw=Yy({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dw=Yy({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hw=Yy({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uw=Yy({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pw=Yy({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fw=Yy({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gw=Yy({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mw=Yy({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var yw=Object.freeze({__proto__:null,base32:cw,base32upper:lw,base32pad:dw,base32padupper:hw,base32hex:uw,base32hexupper:pw,base32hexpad:fw,base32hexpadupper:gw,base32z:mw});const ww=Jy({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bw=Jy({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vw=Object.freeze({__proto__:null,base36:ww,base36upper:bw});const Ew=Jy({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Cw=Jy({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Nw=Object.freeze({__proto__:null,base58btc:Ew,base58flickr:Cw});const Aw=Yy({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Iw=Yy({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Sw=Yy({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_w=Yy({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ow=Object.freeze({__proto__:null,base64:Aw,base64pad:Iw,base64url:Sw,base64urlpad:_w});const Tw=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),kw=Tw.reduce(((e,t,s)=>(e[s]=t,e)),[]),Pw=Tw.reduce(((e,t,s)=>(e[t.codePointAt(0)]=s,e)),[]);const xw=Gy({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=kw[t]),"")},decode:function(e){const t=[];for(const s of e){const e=Pw[s.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${s}`);t.push(e)}return new Uint8Array(t)}});var Rw=Object.freeze({__proto__:null,base256emoji:xw}),Uw=function e(t,s,n){s=s||[];for(var r=n=n||0;t>=Mw;)s[n++]=255&t|Lw,t/=128;for(;t&Dw;)s[n++]=255&t|Lw,t>>>=7;return s[n]=0|t,e.bytes=n-r+1,s},Lw=128,Dw=-128,Mw=Math.pow(2,31);var Bw=function e(t,s){var n,r=0,i=(s=s||0,0),o=s,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],r+=i<28?(n&$w)<<i:(n&$w)*Math.pow(2,i),i+=7}while(n>=jw);return e.bytes=o-s,r},jw=128,$w=127;var Fw=Math.pow(2,7),qw=Math.pow(2,14),Ww=Math.pow(2,21),Hw=Math.pow(2,28),zw=Math.pow(2,35),Vw=Math.pow(2,42),Kw=Math.pow(2,49),Gw=Math.pow(2,56),Jw=Math.pow(2,63),Yw={encode:Uw,decode:Bw,encodingLength:function(e){return e<Fw?1:e<qw?2:e<Ww?3:e<Hw?4:e<zw?5:e<Vw?6:e<Kw?7:e<Gw?8:e<Jw?9:10}},Xw=Yw;const Zw=(e,t,s=0)=>(Xw.encode(e,t,s),t),Qw=e=>Xw.encodingLength(e),eb=(e,t)=>{const s=t.byteLength,n=Qw(e),r=n+Qw(s),i=new Uint8Array(r+s);return Zw(e,i,0),Zw(s,i,n),i.set(t,r),new tb(e,s,t,i)};class tb{constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}}const sb=({name:e,code:t,encode:s})=>new nb(e,t,s);class nb{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?eb(this.code,t):t.then((e=>eb(this.code,e)))}throw Error("Unknown type, must be binary type")}}const rb=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),ib=sb({name:"sha2-256",code:18,encode:rb("SHA-256")}),ob=sb({name:"sha2-512",code:19,encode:rb("SHA-512")});Object.freeze({__proto__:null,sha256:ib,sha512:ob});const ab=qy,cb={code:0,name:"identity",encode:ab,digest:e=>eb(0,ab(e))};Object.freeze({__proto__:null,identity:cb});new TextEncoder,new TextDecoder;const lb={...Zy,...ew,...sw,...rw,...aw,...yw,...vw,...Nw,...Ow,...Rw};function db(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function hb(e,t,s,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:n}}}const ub=hb("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),pb=hb("ascii","a",(e=>{let t="a";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t}),(e=>{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?db(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}((e=e.substring(1)).length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t})),fb={utf8:ub,"utf-8":ub,hex:lb.base16,latin1:pb,ascii:pb,binary:pb,...lb};var gb=Object.defineProperty,mb=(e,t,s)=>((e,t,s)=>t in e?gb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class yb{constructor(e,t){this.core=e,this.logger=t,mb(this,"keychain",new Map),mb(this,"name","keychain"),mb(this,"version","0.3"),mb(this,"initialized",!1),mb(this,"storagePrefix",om),mb(this,"init",(async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}})),mb(this,"has",(e=>(this.isInitialized(),this.keychain.has(e)))),mb(this,"set",(async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()})),mb(this,"get",(e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=Yc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t})),mb(this,"del",(async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()})),this.core=e,this.logger=Nr(t,this.name)}get context(){return Cr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,vl(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?El(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var wb=Object.defineProperty,bb=(e,t,s)=>((e,t,s)=>t in e?wb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class vb{constructor(e,t,s){this.core=e,this.logger=t,bb(this,"name","crypto"),bb(this,"keychain"),bb(this,"randomSessionIdentifier",$f()),bb(this,"initialized",!1),bb(this,"clientId"),bb(this,"init",(async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)})),bb(this,"hasKeys",(e=>(this.isInitialized(),this.keychain.has(e)))),bb(this,"getClientId",(async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const e=dc(pc(await this.getClientSeed()).publicKey);return this.clientId=e,e})),bb(this,"generateKeyPair",(()=>{this.isInitialized();const e=function(){const e=Qp.utils.randomPrivateKey(),t=Qp.getPublicKey(e);return{privateKey:c(e,Tf),publicKey:c(t,Tf)}}();return this.setPrivateKey(e.publicKey,e.privateKey)})),bb(this,"signJWT",(async e=>{this.isInitialized();const t=pc(await this.getClientSeed()),s=this.randomSessionIdentifier,n=dm;return await fc(s,e,n,t)})),bb(this,"generateSharedKey",((e,t,s)=>{this.isInitialized();const n=function(e,t){const s=Qp.getSharedSecret(a(e,Tf),a(t,Tf)),n=Mu(Bu,s,void 0,void 0,jf);return c(n,Tf)}(this.getPrivateKey(e),t);return this.setSymKey(n,s)})),bb(this,"setSymKey",(async(e,t)=>{this.isInitialized();const s=t||Ff(e);return await this.keychain.set(s,e),s})),bb(this,"deleteKeyPair",(async e=>{this.isInitialized(),await this.keychain.del(e)})),bb(this,"deleteSymKey",(async e=>{this.isInitialized(),await this.keychain.del(e)})),bb(this,"encode",(async(e,t,s)=>{this.isInitialized();const n=Jf(s),r=i(t);if(Xf(n))return function(e,t){const s=Wf(Lf),n=_d(Bf),r=Kf({type:s,sealed:a(e,xf),iv:n});return t===Pf?zf(r):r}(r,s?.encoding);if(Yf(n)){const t=n.senderPublicKey,s=n.receiverPublicKey;e=await this.generateSharedKey(t,s)}const o=this.getSymKey(e),{type:c,senderPublicKey:l}=n;return function(e){const t=Wf(typeof e.type<"u"?e.type:Rf);if(Hf(t)===Uf&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof e.senderPublicKey<"u"?a(e.senderPublicKey,Tf):void 0,n=typeof e.iv<"u"?a(e.iv,Tf):_d(Bf),r=a(e.symKey,Tf),i=Kf({type:t,sealed:xu(r,n).encrypt(a(e.message,xf)),iv:n,senderPublicKey:s});return e.encoding===Pf?zf(i):i}({type:c,symKey:o,message:r,senderPublicKey:l,encoding:s?.encoding})})),bb(this,"decode",(async(e,t,s)=>{this.isInitialized();const n=function(e,t){const s=Gf({encoded:e,encoding:t?.encoding});return Jf({type:Hf(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?c(s.senderPublicKey,Tf):void 0,receiverPublicKey:t?.receiverPublicKey})}(t,s);if(Xf(n)){const e=function(e,t){const{sealed:s}=Gf({encoded:e,encoding:t});return c(s,xf)}(t,s?.encoding);return r(e)}if(Yf(n)){const t=n.receiverPublicKey,s=n.senderPublicKey;e=await this.generateSharedKey(t,s)}try{const n=function(e){const t=a(e.symKey,Tf),{sealed:s,iv:n}=Gf({encoded:e.encoded,encoding:e.encoding}),r=xu(t,n).decrypt(s);if(null===r)throw new Error("Failed to decrypt");return c(r,xf)}({symKey:this.getSymKey(e),encoded:t,encoding:s?.encoding});return r(n)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}})),bb(this,"getPayloadType",((e,t=kf)=>Hf(Gf({encoded:e,encoding:t}).type))),bb(this,"getPayloadSenderPublicKey",((e,t=kf)=>{const s=Gf({encoded:e,encoding:t});return s.senderPublicKey?c(s.senderPublicKey,Tf):void 0})),this.core=e,this.logger=Nr(t,this.name),this.keychain=s||new yb(this.core,this.logger)}get context(){return Cr(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(lm)}catch{e=$f(),await this.keychain.set(lm,e)}return function(e,t="utf8"){const s=fb[t];if(!s)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?s.decoder.decode(`${s.prefix}${e}`):db(globalThis.Buffer.from(e,"utf-8"))}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Eb=Object.defineProperty,Cb=Object.defineProperties,Nb=Object.getOwnPropertyDescriptors,Ab=Object.getOwnPropertySymbols,Ib=Object.prototype.hasOwnProperty,Sb=Object.prototype.propertyIsEnumerable,_b=(e,t,s)=>t in e?Eb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Ob=(e,t,s)=>_b(e,"symbol"!=typeof t?t+"":t,s);class Tb extends Pr{constructor(e,t){super(e,t),this.logger=e,this.core=t,Ob(this,"messages",new Map),Ob(this,"messagesWithoutClientAck",new Map),Ob(this,"name","messages"),Ob(this,"version","0.3"),Ob(this,"initialized",!1),Ob(this,"storagePrefix",om),Ob(this,"init",(async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e);const t=await this.getRelayerMessagesWithoutClientAck();typeof t<"u"&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}})),Ob(this,"set",(async(e,t,s)=>{this.isInitialized();const n=qf(t);let r=this.messages.get(e);if(typeof r>"u"&&(r={}),typeof r[n]<"u")return n;if(r[n]=t,this.messages.set(e,r),s===Sm){const s=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,((e,t)=>Cb(e,Nb(t)))(((e,t)=>{for(var s in t||(t={}))Ib.call(t,s)&&_b(e,s,t[s]);if(Ab)for(var s of Ab(t))Sb.call(t,s)&&_b(e,s,t[s]);return e})({},s),{[n]:t}))}return await this.persist(),n})),Ob(this,"get",(e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t})),Ob(this,"getWithoutAck",(e=>{this.isInitialized();const t={};for(const s of e){const e=this.messagesWithoutClientAck.get(s)||{};t[s]=Object.values(e)}return t})),Ob(this,"has",((e,t)=>{this.isInitialized();return typeof this.get(e)[qf(t)]<"u"})),Ob(this,"ack",(async(e,t)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(e);if(typeof s>"u")return;delete s[qf(t)],0===Object.keys(s).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,s),await this.persist()})),Ob(this,"del",(async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()})),this.logger=Nr(e,this.name),this.core=t}get context(){return Cr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,vl(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,vl(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?El(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?El(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kb=Object.defineProperty,Pb=Object.defineProperties,xb=Object.getOwnPropertyDescriptors,Rb=Object.getOwnPropertySymbols,Ub=Object.prototype.hasOwnProperty,Lb=Object.prototype.propertyIsEnumerable,Db=(e,t,s)=>t in e?kb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Mb=(e,t)=>{for(var s in t||(t={}))Ub.call(t,s)&&Db(e,s,t[s]);if(Rb)for(var s of Rb(t))Lb.call(t,s)&&Db(e,s,t[s]);return e},Bb=(e,t)=>Pb(e,xb(t)),jb=(e,t,s)=>Db(e,"symbol"!=typeof t?t+"":t,s);class $b extends xr{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,jb(this,"events",new t),jb(this,"name","publisher"),jb(this,"queue",new Map),jb(this,"publishTimeout",s.toMiliseconds(s.ONE_MINUTE)),jb(this,"initialPublishTimeout",s.toMiliseconds(15*s.ONE_SECOND)),jb(this,"needsTransportRestart",!1),jb(this,"publish",(async(e,t,s)=>{var n,r,i,o,a;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:s}});const c=s?.ttl||hm,l=s?.prompt||!1,d=s?.tag||0,h=s?.id||E().toString(),u=eg(Qf().protocol),p={id:h,method:s?.publishMethod||u.publish,params:Mb({topic:e,message:t,ttl:c,prompt:l,tag:d,attestation:s?.attestation},s?.tvf)},f=`Failed to publish payload, please try again. id:${h} tag:${d}`;try{Pg(null==(n=p.params)?void 0:n.prompt)&&(null==(r=p.params)||delete r.prompt),Pg(null==(i=p.params)?void 0:i.tag)&&(null==(o=p.params)||delete o.tag);const a=new Promise((async e=>{const t=({id:s})=>{var n;(null==(n=p.id)?void 0:n.toString())===s.toString()&&(this.removeRequestFromQueue(s),this.relayer.events.removeListener(bm,t),e())};this.relayer.events.on(bm,t);const n=Nl(new Promise(((e,t)=>{this.rpcPublish(p,s).then(e).catch((e=>{this.logger.warn(e,e?.message),t(e)}))})),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${d}`);try{await n,this.events.removeListener(bm,t)}catch(e){this.queue.set(h,{request:p,opts:s,attempt:1}),this.logger.warn(e,e?.message)}}));this.logger.trace({type:"method",method:"publish",params:{id:h,topic:e,message:t,opts:s}}),await Nl(a,this.publishTimeout,f)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),null!=(a=s?.internal)&&a.throwOnFailedPublish)throw e}finally{this.queue.delete(h)}})),jb(this,"publishCustom",(async e=>{var t,n,r,i,o;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:e});const{payload:a,opts:c={}}=e,{attestation:l,tvf:d,publishMethod:h,prompt:u,tag:p,ttl:f=s.FIVE_MINUTES}=c,g=c.id||E().toString(),m=eg(Qf().protocol),y=h||m.publish,w={id:g,method:y,params:Mb(Bb(Mb({},a),{ttl:f,prompt:u,tag:p,attestation:l}),d)},b=`Failed to publish custom payload, please try again. id:${g} tag:${p}`;try{Pg(null==(t=w.params)?void 0:t.prompt)&&(null==(n=w.params)||delete n.prompt),Pg(null==(r=w.params)?void 0:r.tag)&&(null==(i=w.params)||delete i.tag);const e=new Promise((async e=>{const t=({id:s})=>{var n;(null==(n=w.id)?void 0:n.toString())===s.toString()&&(this.removeRequestFromQueue(s),this.relayer.events.removeListener(bm,t),e())};this.relayer.events.on(bm,t);const s=Nl(new Promise(((e,t)=>{this.rpcPublish(w,c).then(e).catch((e=>{this.logger.warn(e,e?.message),t(e)}))})),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${y} id:${g} tag:${p}`);try{await s,this.events.removeListener(bm,t)}catch(e){this.queue.set(g,{request:w,opts:c,attempt:1}),this.logger.warn(e,e?.message)}}));this.logger.trace({type:"method",method:"publish",params:{id:g,payload:a,opts:c}}),await Nl(e,this.publishTimeout,b)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),null!=(o=c?.internal)&&o.throwOnFailedPublish)throw e}finally{this.queue.delete(g)}})),jb(this,"on",((e,t)=>{this.events.on(e,t)})),jb(this,"once",((e,t)=>{this.events.once(e,t)})),jb(this,"off",((e,t)=>{this.events.off(e,t)})),jb(this,"removeListener",((e,t)=>{this.events.removeListener(e,t)})),this.relayer=e,this.logger=Nr(n,this.name),this.registerEventListeners()}get context(){return Cr(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const s=await this.relayer.request(e);return this.relayer.events.emit(bm,Mb(Mb({},e),t)),this.logger.debug("Successfully Published Payload"),s}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach((async(e,t)=>{var s;const n=e.attempt+1;this.queue.set(t,Bb(Mb({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${null==(s=e.request.params)?void 0:s.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)}))}registerEventListeners(){this.relayer.core.heartbeat.on(dn,(()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(wm);this.checkQueue()})),this.relayer.on(fm,(e=>{this.removeRequestFromQueue(e.id.toString())}))}}var Fb=Object.defineProperty,qb=(e,t,s)=>((e,t,s)=>t in e?Fb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Wb{constructor(){qb(this,"map",new Map),qb(this,"set",((e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])})),qb(this,"get",(e=>this.map.get(e)||[])),qb(this,"exists",((e,t)=>this.get(e).includes(t))),qb(this,"delete",((e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const n=s.filter((e=>e!==t));n.length?this.map.set(e,n):this.map.delete(e)})),qb(this,"clear",(()=>{this.map.clear()}))}get topics(){return Array.from(this.map.keys())}}var Hb=Object.defineProperty,zb=Object.defineProperties,Vb=Object.getOwnPropertyDescriptors,Kb=Object.getOwnPropertySymbols,Gb=Object.prototype.hasOwnProperty,Jb=Object.prototype.propertyIsEnumerable,Yb=(e,t,s)=>t in e?Hb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Xb=(e,t)=>{for(var s in t||(t={}))Gb.call(t,s)&&Yb(e,s,t[s]);if(Kb)for(var s of Kb(t))Jb.call(t,s)&&Yb(e,s,t[s]);return e},Zb=(e,t)=>zb(e,Vb(t)),Qb=(e,t,s)=>Yb(e,"symbol"!=typeof t?t+"":t,s);class ev extends Lr{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Qb(this,"subscriptions",new Map),Qb(this,"topicMap",new Wb),Qb(this,"events",new t),Qb(this,"name","subscription"),Qb(this,"version","0.3"),Qb(this,"pending",new Map),Qb(this,"cached",[]),Qb(this,"initialized",!1),Qb(this,"storagePrefix",om),Qb(this,"subscribeTimeout",s.toMiliseconds(s.ONE_MINUTE)),Qb(this,"initialSubscribeTimeout",s.toMiliseconds(15*s.ONE_SECOND)),Qb(this,"clientId"),Qb(this,"batchSubscribeTopicsLimit",500),Qb(this,"init",(async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0})),Qb(this,"subscribe",(async(e,t)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const n=Qf(t),r={topic:e,relay:n,transportType:t?.transportType};null!=(s=t?.internal)&&s.skipSubscribe||this.pending.set(e,r);const i=await this.rpcSubscribe(e,n,t);return"string"==typeof i&&(this.onSubscribe(i,r),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),i}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}})),Qb(this,"unsubscribe",(async(e,t)=>{this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)})),Qb(this,"isSubscribed",(e=>new Promise((t=>{t(this.topicMap.topics.includes(e))})))),Qb(this,"isKnownTopic",(e=>new Promise((t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some((t=>t.topic===e)))})))),Qb(this,"on",((e,t)=>{this.events.on(e,t)})),Qb(this,"once",((e,t)=>{this.events.once(e,t)})),Qb(this,"off",((e,t)=>{this.events.off(e,t)})),Qb(this,"removeListener",((e,t)=>{this.events.removeListener(e,t)})),Qb(this,"start",(async()=>{await this.onConnect()})),Qb(this,"stop",(async()=>{await this.onDisconnect()})),Qb(this,"restart",(async()=>{await this.restore(),await this.onRestart()})),Qb(this,"checkPending",(async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach((t=>{e.push(t)})),await this.batchSubscribe(e)})),Qb(this,"registerEventListeners",(()=>{this.relayer.core.heartbeat.on(dn,(async()=>{await this.checkPending()})),this.events.on(Tm,(async e=>{const t=Tm;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(km,(async e=>{const t=km;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))})),this.relayer=e,this.logger=Nr(n,this.name),this.clientId=""}get context(){return Cr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map((async s=>await this.unsubscribeById(e,s,t))))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const n=Qf(s);await this.restartToComplete({topic:e,id:t,relay:n}),await this.rpcUnsubscribe(e,t,n);const r=Xc("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,n){var r,i;const o=await this.getSubscriptionId(e);if(null!=(r=n?.internal)&&r.skipSubscribe)return o;(!n||n?.transportType===Im.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const a={method:eg(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=null==(i=n?.internal)?void 0:i.throwOnFailedPublish;try{if(n?.transportType===Im.link_mode)return setTimeout((()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch((e=>this.logger.warn(e)))}),s.toMiliseconds(s.ONE_SECOND)),o;const t=new Promise((async t=>{const s=n=>{n.topic===e&&(this.events.removeListener(Tm,s),t(n.id))};this.events.on(Tm,s);try{const n=await Nl(new Promise(((e,t)=>{this.relayer.request(a).catch((e=>{this.logger.warn(e,e?.message),t(e)})).then(e)})),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Tm,s),t(n)}catch{}})),r=await Nl(t,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!r&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return r?o:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(wm),c)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const t={method:eg(e[0].relay.protocol).batchSubscribe,params:{topics:e.map((e=>e.topic))}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await Nl(new Promise(((e,s)=>{this.relayer.request(t).then(e).catch((e=>{this.logger.warn(e),s(e)}))})),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(wm),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const t={method:eg(e[0].relay.protocol).batchFetchMessages,params:{topics:e.map((e=>e.topic))}};let s;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{s=await await Nl(new Promise(((e,s)=>{this.relayer.request(t).catch((e=>{this.logger.warn(e),s(e)})).then(e)})),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(wm)}return s}rpcUnsubscribe(e,t,s){const n={method:eg(s.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,t){this.setSubscription(e,Zb(Xb({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,Xb({},e)),this.pending.delete(e.topic)}))}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,Xb({},t)),this.topicMap.set(t.topic,e),this.events.emit(Tm,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:t}=Yc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(km,Zb(Xb({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Pm)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit(xm)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every((e=>{var t;return e.topic===(null==(t=this.subscriptions.get(e.id))?void 0:t.topic)}))){const{message:e}=Yc("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(e.length){if(!await this.rpcBatchSubscribe(e))return this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),void e.forEach((e=>{this.pending.set(e.topic,e)}));this.onBatchSubscribe(await Promise.all(e.map((async e=>Zb(Xb({},e),{id:await this.getSubscriptionId(e.topic)})))))}}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await function(e){return new Promise((t=>setTimeout(t,e)))}(s.toMiliseconds(s.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return qf(e+await this.getClientId())}}var tv=Object.defineProperty,sv=Object.getOwnPropertySymbols,nv=Object.prototype.hasOwnProperty,rv=Object.prototype.propertyIsEnumerable,iv=(e,t,s)=>t in e?tv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ov=(e,t)=>{for(var s in t||(t={}))nv.call(t,s)&&iv(e,s,t[s]);if(sv)for(var s of sv(t))rv.call(t,s)&&iv(e,s,t[s]);return e},av=(e,t,s)=>iv(e,"symbol"!=typeof t?t+"":t,s);class cv extends Rr{constructor(e){var n;super(e),av(this,"protocol","wc"),av(this,"version",2),av(this,"core"),av(this,"logger"),av(this,"events",new t),av(this,"provider"),av(this,"messages"),av(this,"subscriber"),av(this,"publisher"),av(this,"name","relayer"),av(this,"transportExplicitlyClosed",!1),av(this,"initialized",!1),av(this,"connectionAttemptInProgress",!1),av(this,"relayUrl"),av(this,"projectId"),av(this,"packageName"),av(this,"bundleId"),av(this,"hasExperiencedNetworkDisruption",!1),av(this,"pingTimeout"),av(this,"heartBeatTimeout",s.toMiliseconds(s.THIRTY_SECONDS+s.FIVE_SECONDS)),av(this,"reconnectTimeout"),av(this,"connectPromise"),av(this,"reconnectInProgress",!1),av(this,"requestsInFlight",[]),av(this,"connectTimeout",s.toMiliseconds(15*s.ONE_SECOND)),av(this,"stalledRestartInProgress",!1),av(this,"stalledRestartTimeout"),av(this,"stalledRestartBackoff",0),av(this,"stalledRestartBaseInterval",s.toMiliseconds(2*s.ONE_SECOND)),av(this,"stalledRestartMaxInterval",s.toMiliseconds(s.THIRTY_SECONDS)),av(this,"request",(async e=>{var t,s;this.logger.debug("Publishing Request Payload");const n=e.id||E().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:e.method,topic:null==(t=e.params)?void 0:t.topic},"relayer.request - publishing...");const r=`${n}:${(null==(s=e.params)?void 0:s.tag)||""}`;this.requestsInFlight.push(r);const i=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter((e=>e!==r)),i}catch(e){throw this.logger.debug(`Failed to Publish Request: ${n}`),e}})),av(this,"resetPingTimeout",(()=>{dl()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout((()=>{var e,t,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),null==(n=null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.terminate)||n.call(s)}catch(e){this.logger.warn(e,e?.message)}}),this.heartBeatTimeout))})),av(this,"onPayloadHandler",(e=>{this.onProviderPayload(e),this.resetPingTimeout()})),av(this,"onConnectHandler",(()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(gm)})),av(this,"onDisconnectHandler",(()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()})),av(this,"onProviderErrorHandler",(e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(ym,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch((e=>this.logger.warn(e)))})),av(this,"registerProviderListeners",(()=>{this.provider.on(vm,this.onPayloadHandler),this.provider.on(Em,this.onConnectHandler),this.provider.on(Cm,this.onDisconnectHandler),this.provider.on(Nm,this.onProviderErrorHandler)})),this.core=e.core,this.logger=em({logger:null!=(n=e.logger)?n:"error",name:this.name}),this.messages=new Tb(this.logger,e.core),this.subscriber=new ev(this,this.logger),this.publisher=new $b(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||um,hl()&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"&&"android"===(null==global?void 0:global.Platform.OS)?this.packageName=fl():hl()&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"&&"ios"===(null==global?void 0:global.Platform.OS)&&(this.bundleId=fl()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch((e=>this.logger.warn(e,e?.message)))}get context(){return Cr(this.logger)}get connected(){var e,t,s;return 1===(null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.readyState)||!1}get connecting(){var e,t,s;return 0===(null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.readyState)||void 0!==this.connectPromise||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Im.relay},_m)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){var s,n,r;this.isInitialized(),(null==t||!t.transportType||"relay"===t?.transportType)&&await this.toEstablishConnection();const i=typeof(null==(s=t?.internal)?void 0:s.throwOnFailedPublish)>"u"||(null==(n=t?.internal)?void 0:n.throwOnFailedPublish);let o,a=(null==(r=this.subscriber.topicMap.get(e))?void 0:r[0])||"";const c=t=>{t.topic===e&&(this.subscriber.off(Tm,c),o())};return await Promise.all([new Promise((e=>{o=e,this.subscriber.on(Tm,c)})),new Promise((async(s,n)=>{a=await this.subscriber.subscribe(e,ov({internal:{throwOnFailedPublish:i}},t)).catch((e=>{i&&n(e)}))||a,s()}))]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Nl(this.provider.disconnect(),2e3,"provider.disconnect()").catch((()=>this.onProviderDisconnect())):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(e){if(this.subscriber.hasAnyTopics){if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise((async(t,s)=>{await this.connect(e).then(t).catch(s).finally((()=>{this.connectPromise=void 0}))})),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}else this.logger.info("Starting WS connection skipped because the client has no topics to work with.")}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await Kg())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===e?.length)return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort(((e,t)=>e.publishedAt-t.publishedAt));this.logger.debug(`Batch of ${t.length} message events sorted`);for(const e of t)try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:n}=e;if(!t.sessionExists){const e={topic:n,expiry:Sl(s.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,e)}this.events.emit(pm,e),await this.recordMessageEvent(e,Sm)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise((async(e,t)=>{const s=()=>{t(new Error("Connection interrupted while trying to connect"))};this.provider.once(Cm,s),await Nl(new Promise(((e,t)=>{this.provider.connect().then(e).catch(t)})),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch((e=>{t(e)})).finally((()=>{this.provider.off(Cm,s),clearTimeout(this.reconnectTimeout)})),await new Promise((async(e,s)=>{const n=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Cm,n),await this.subscriber.start().then(e).catch(s).finally((()=>{this.provider.off(Cm,n)}))})),this.hasExperiencedNetworkDisruption=!1,e()}))}catch(e){await this.subscriber.stop();const t=e;this.logger.warn({},t.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise((e=>setTimeout(e,s.toMiliseconds(1*t)))),t++}}startPingTimeout(){var e,t,s,n,r;if(dl())try{null!=(t=null==(e=this.provider)?void 0:e.connection)&&t.socket&&(null==(r=null==(n=null==(s=this.provider)?void 0:s.connection)?void 0:n.socket)||r.on("ping",(()=>{this.resetPingTimeout()}))),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new tm(new rm(wl({sdkVersion:Am,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:s,message:n}=e;await this.messages.set(s,n,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||0===s.length)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const n=this.messages.has(t,s);return n&&this.logger.warn(`Ignoring duplicate message: ${s}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),T(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:s,message:n,publishedAt:r,attestation:i}=t.data,o={topic:s,message:n,publishedAt:r,transportType:Im.relay,attestation:i};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(ov({type:"event",event:t.id},o)),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else N(e)&&this.events.emit(fm,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Sm),this.events.emit(pm,e))}async acknowledgePayload(e){const t=k(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(vm,this.onPayloadHandler),this.provider.off(Em,this.onConnectHandler),this.provider.off(Cm,this.onDisconnectHandler),this.provider.off(Nm,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Kg();Gg((async t=>{e!==t&&(e=t,t?await this.transportOpen().catch((e=>this.logger.error(e,e?.message))):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})),this.core.heartbeat.on(dn,(async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&function(){var e;return!ul()||!l()||"visible"===(null==(e=l())?void 0:e.visibilityState)}())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}})),this.events.on(wm,(()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const e=0===this.stalledRestartBackoff?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${e?` in ${e}ms`:""}...`),this.stalledRestartTimeout=setTimeout((async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(e){this.logger.error(e,e?.message)}finally{this.stalledRestartInProgress=!1}}),e)}))}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(mm),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout((async()=>{await this.transportOpen().catch((e=>this.logger.error(e,e?.message))),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}),s.toMiliseconds(.1)))))}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void await this.connectPromise;await this.connect()}}}function lv(e){return Object.getOwnPropertySymbols(e).filter((t=>Object.prototype.propertyIsEnumerable.call(e,t)))}function dv(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const hv="[object RegExp]",uv="[object String]",pv="[object Number]",fv="[object Boolean]",gv="[object Arguments]",mv="[object Symbol]",yv="[object Date]",wv="[object Map]",bv="[object Set]",vv="[object Array]",Ev="[object Function]",Cv="[object ArrayBuffer]",Nv="[object Object]",Av="[object Error]",Iv="[object DataView]",Sv="[object Uint8Array]",_v="[object Uint8ClampedArray]",Ov="[object Uint16Array]",Tv="[object Uint32Array]",kv="[object BigUint64Array]",Pv="[object Int8Array]",xv="[object Int16Array]",Rv="[object Int32Array]",Uv="[object BigInt64Array]",Lv="[object Float32Array]",Dv="[object Float64Array]";function Mv(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}function Bv(e,t,s,n,r,i,o){const a=o(e,t,s,n,r,i);if(void 0!==a)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return e===t;case"number":return e===t||Object.is(e,t);case"object":return jv(e,t,i,o)}return jv(e,t,i,o)}function jv(e,t,s,n){if(Object.is(e,t))return!0;let r=dv(e),i=dv(t);if(r===gv&&(r=Nv),i===gv&&(i=Nv),r!==i)return!1;switch(r){case uv:return e.toString()===t.toString();case pv:return function(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}(e.valueOf(),t.valueOf());case fv:case yv:case mv:return Object.is(e.valueOf(),t.valueOf());case hv:return e.source===t.source&&e.flags===t.flags;case Ev:return e===t}const o=(s=s??new Map).get(e),a=s.get(t);if(null!=o&&null!=a)return o===t;s.set(e,t),s.set(t,e);try{switch(r){case wv:if(e.size!==t.size)return!1;for(const[r,i]of e.entries())if(!t.has(r)||!Bv(i,t.get(r),r,e,t,s,n))return!1;return!0;case bv:{if(e.size!==t.size)return!1;const r=Array.from(e.values()),i=Array.from(t.values());for(let o=0;o<r.length;o++){const a=r[o],c=i.findIndex((r=>Bv(a,r,void 0,e,t,s,n)));if(-1===c)return!1;i.splice(c,1)}return!0}case vv:case Sv:case _v:case Ov:case Tv:case kv:case Pv:case xv:case Rv:case Uv:case Lv:case Dv:if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Bv(e[r],t[r],r,e,t,s,n))return!1;return!0;case Cv:return e.byteLength===t.byteLength&&jv(new Uint8Array(e),new Uint8Array(t),s,n);case Iv:return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&jv(new Uint8Array(e),new Uint8Array(t),s,n);case Av:return e.name===t.name&&e.message===t.message;case Nv:{if(!(jv(e.constructor,t.constructor,s,n)||Mv(e)&&Mv(t)))return!1;const r=[...Object.keys(e),...lv(e)],i=[...Object.keys(t),...lv(t)];if(r.length!==i.length)return!1;for(let i=0;i<r.length;i++){const o=r[i],a=e[o];if(!Object.hasOwn(t,o))return!1;if(!Bv(a,t[o],o,e,t,s,n))return!1}return!0}default:return!1}}finally{s.delete(e),s.delete(t)}}function $v(){}function Fv(e,t){return function(e,t,s){return Bv(e,t,void 0,void 0,void 0,void 0,s)}(e,t,$v)}var qv=Object.defineProperty,Wv=Object.getOwnPropertySymbols,Hv=Object.prototype.hasOwnProperty,zv=Object.prototype.propertyIsEnumerable,Vv=(e,t,s)=>t in e?qv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Kv=(e,t)=>{for(var s in t||(t={}))Hv.call(t,s)&&Vv(e,s,t[s]);if(Wv)for(var s of Wv(t))zv.call(t,s)&&Vv(e,s,t[s]);return e},Gv=(e,t,s)=>Vv(e,"symbol"!=typeof t?t+"":t,s);class Jv extends Ur{constructor(e,t,s,n=om,r=void 0){super(e,t,s,n),this.core=e,this.logger=t,this.name=s,Gv(this,"map",new Map),Gv(this,"version","0.3"),Gv(this,"cached",[]),Gv(this,"initialized",!1),Gv(this,"getKey"),Gv(this,"storagePrefix",om),Gv(this,"recentlyDeleted",[]),Gv(this,"recentlyDeletedLimit",200),Gv(this,"init",(async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!Pg(e)?this.map.set(this.getKey(e),e):function(e){var t;return null==(t=e?.proposer)?void 0:t.publicKey}(e)?this.map.set(e.id,e):function(e){return e?.topic}(e)&&this.map.set(e.topic,e)})),this.cached=[],this.initialized=!0)})),Gv(this,"set",(async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())})),Gv(this,"get",(e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)))),Gv(this,"getAll",(e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((s=>Fv(t[s],e[s]))))):this.values))),Gv(this,"update",(async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const s=Kv(Kv({},this.getData(e)),t);this.map.set(e,s),await this.persist()})),Gv(this,"delete",(async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())})),this.logger=Nr(t,this.name),this.storagePrefix=n,this.getKey=r}get context(){return Cr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:t}=Yc("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=Yc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:e}=Yc("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Yv=Object.defineProperty,Xv=(e,t,s)=>((e,t,s)=>t in e?Yv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Zv{constructor(t,n){this.core=t,this.logger=n,Xv(this,"name","pairing"),Xv(this,"version","0.3"),Xv(this,"events",new e),Xv(this,"pairings"),Xv(this,"initialized",!1),Xv(this,"storagePrefix",om),Xv(this,"ignoredPayloadTypes",[Uf]),Xv(this,"registeredMethods",[]),Xv(this,"init",(async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))})),Xv(this,"register",(({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]})),Xv(this,"create",(async e=>{this.isInitialized();const t=$f(),n=await this.core.crypto.setSymKey(t),r=Sl(s.FIVE_MINUTES),i={protocol:"irn"},o={topic:n,expiry:r,relay:i,active:!1,methods:e?.methods},a=ug({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:t,relay:i,expiryTimestamp:r,methods:e?.methods});return this.events.emit(Um,o),this.core.expirer.set(n,r),await this.pairings.set(n,o),await this.core.relayer.subscribe(n,{transportType:e?.transportType,internal:e?.internal}),{topic:n,uri:a}})),Xv(this,"pair",(async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[Ym]}});this.isValidPair(e,t);const{topic:n,symKey:r,relay:i,expiryTimestamp:o,methods:a}=dg(e.uri);let c;if(t.props.properties.topic=n,t.addTrace(Xm),t.addTrace(Zm),this.pairings.keys.includes(n)){if(c=this.pairings.get(n),t.addTrace(sy),c.active)throw t.setError(cy),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);t.addTrace(ny)}const l=o||Sl(s.FIVE_MINUTES),d={topic:n,relay:i,expiry:l,active:!1,methods:a};this.core.expirer.set(n,l),await this.pairings.set(n,d),t.addTrace(Qm),e.activatePairing&&await this.activate({topic:n}),this.events.emit(Um,d),t.addTrace(ry),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(r,n),t.addTrace(ey);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(oy)}try{await this.core.relayer.subscribe(n,{relay:i})}catch(e){throw t.setError(ly),e}return t.addTrace(ty),d})),Xv(this,"activate",(async({topic:e})=>{this.isInitialized();const t=Sl(s.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})})),Xv(this,"ping",(async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:s,resolve:n,reject:r}=Cl();this.events.once(Ol("pairing_ping",e),(({error:e})=>{e?r(e):n()})),await s()}})),Xv(this,"updateExpiry",(async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})})),Xv(this,"updateMetadata",(async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})})),Xv(this,"getPairings",(()=>(this.isInitialized(),this.pairings.values))),Xv(this,"disconnect",(async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Xc("USER_DISCONNECTED")),await this.deletePairing(t))})),Xv(this,"formatUriFromPairing",(e=>{this.isInitialized();const{topic:t,relay:s,expiry:n,methods:r}=e,i=this.core.crypto.keychain.get(t);return ug({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:i,relay:s,expiryTimestamp:n,methods:r})})),Xv(this,"sendRequest",(async(e,t,s)=>{const n=v(t,s),r=await this.core.crypto.encode(e,n),i=Rm[t].req;return this.core.history.set(e,n),this.core.relayer.publish(e,r,i),n.id})),Xv(this,"sendResult",(async(e,t,s)=>{const n=k(e,s),r=await this.core.crypto.encode(t,n),i=(await this.core.history.get(t,e)).request.method,o=Rm[i].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(n)})),Xv(this,"sendError",(async(e,t,s)=>{const n=_(e,s),r=await this.core.crypto.encode(t,n),i=(await this.core.history.get(t,e)).request.method,o=Rm[i]?Rm[i].res:Rm.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(n)})),Xv(this,"deletePairing",(async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Xc("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])})),Xv(this,"cleanup",(async()=>{const e=this.pairings.getAll().filter((e=>_l(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))})),Xv(this,"onRelayEventRequest",(async e=>{const{topic:t,payload:s}=e;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,s);default:return await this.onUnknownRpcMethodRequest(t,s)}})),Xv(this,"onRelayEventResponse",(async e=>{const{topic:t,payload:s}=e,n=(await this.core.history.get(t,s.id)).request.method;return"wc_pairingPing"===n?this.onPairingPingResponse(t,s):this.onUnknownRpcMethodResponse(n)})),Xv(this,"onPairingPingRequest",(async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.events.emit(Mm,{id:s,topic:e})}catch(t){await this.sendError(s,e,t),this.logger.error(t)}})),Xv(this,"onPairingPingResponse",((e,t)=>{const{id:s}=t;setTimeout((()=>{P(t)?this.events.emit(Ol("pairing_ping",s),{}):C(t)&&this.events.emit(Ol("pairing_ping",s),{error:t.error})}),500)})),Xv(this,"onPairingDeleteRequest",(async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(Dm,{id:s,topic:e})}catch(t){await this.sendError(s,e,t),this.logger.error(t)}})),Xv(this,"onUnknownRpcMethodRequest",(async(e,t)=>{const{id:s,method:n}=t;try{if(this.registeredMethods.includes(n))return;const t=Xc("WC_METHOD_UNSUPPORTED",n);await this.sendError(s,e,t),this.logger.error(t)}catch(t){await this.sendError(s,e,t),this.logger.error(t)}})),Xv(this,"onUnknownRpcMethodResponse",(e=>{this.registeredMethods.includes(e)||this.logger.error(Xc("WC_METHOD_UNSUPPORTED",e))})),Xv(this,"isValidPair",((e,t)=>{var n;if(!Fg(e)){const{message:s}=Yc("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(ay),new Error(s)}if(!function(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(xg(e,!1))return!!t(e)||t(Ul(e))}catch{}return!1}(e.uri)){const{message:s}=Yc("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(ay),new Error(s)}const r=dg(e?.uri);if(null==(n=r?.relay)||!n.protocol){const{message:e}=Yc("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(ay),new Error(e)}if(null==r||!r.symKey){const{message:e}=Yc("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(ay),new Error(e)}if(null!=r&&r.expiryTimestamp&&s.toMiliseconds(r?.expiryTimestamp)<Date.now()){t.setError(dy);const{message:e}=Yc("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}})),Xv(this,"isValidPing",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)})),Xv(this,"isValidDisconnect",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)})),Xv(this,"isValidPairingTopic",(async e=>{if(!xg(e,!1)){const{message:t}=Yc("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=Yc("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(_l(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=Yc("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}})),this.core=t,this.logger=Nr(n,this.name),this.pairings=new Jv(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Cr(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(pm,(async e=>{const{topic:t,message:s,transportType:n}=e;if(this.pairings.keys.includes(t)&&n!==Im.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const e=await this.core.crypto.decode(t,s);T(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):N(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,s)}catch(e){this.logger.error(e)}}))}registerExpirerEvents(){this.core.expirer.on(Hm,(async e=>{const{topic:t}=Il(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Lm,{topic:t}))}))}}var Qv=Object.defineProperty,eE=(e,t,s)=>((e,t,s)=>t in e?Qv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class tE extends kr{constructor(e,n){super(e,n),this.core=e,this.logger=n,eE(this,"records",new Map),eE(this,"events",new t),eE(this,"name","history"),eE(this,"version","0.3"),eE(this,"cached",[]),eE(this,"initialized",!1),eE(this,"storagePrefix",om),eE(this,"init",(async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.records.set(e.id,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)})),eE(this,"set",((e,t,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:n}),this.records.has(t.id))return;const r={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:n,expiry:Sl(s.THIRTY_DAYS)};this.records.set(r.id,r),this.persist(),this.events.emit(Bm,r)})),eE(this,"resolve",(async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=C(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(jm,t))})),eE(this,"get",(async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)))),eE(this,"delete",((e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach((s=>{if(s.topic===e){if(typeof t<"u"&&s.id!==t)return;this.records.delete(s.id),this.events.emit($m,s)}})),this.persist()})),eE(this,"exists",(async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e))),eE(this,"on",((e,t)=>{this.events.on(e,t)})),eE(this,"once",((e,t)=>{this.events.once(e,t)})),eE(this,"off",((e,t)=>{this.events.off(e,t)})),eE(this,"removeListener",((e,t)=>{this.events.removeListener(e,t)})),this.logger=Nr(n,this.name)}get context(){return Cr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach((t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:v(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)})),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:t}=Yc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fm)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=Yc("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Bm,(e=>{const t=Bm;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(jm,(e=>{const t=jm;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on($m,(e=>{const t=$m;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.core.heartbeat.on(dn,(()=>{this.cleanup()}))}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach((t=>{s.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit($m,t,!1),e=!0)})),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var sE=Object.defineProperty,nE=(e,t,s)=>((e,t,s)=>t in e?sE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class rE extends Dr{constructor(e,s){super(e,s),this.core=e,this.logger=s,nE(this,"expirations",new Map),nE(this,"events",new t),nE(this,"name","expirer"),nE(this,"version","0.3"),nE(this,"cached",[]),nE(this,"initialized",!1),nE(this,"storagePrefix",om),nE(this,"init",(async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.expirations.set(e.target,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)})),nE(this,"has",(e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}})),nE(this,"set",((e,t)=>{this.isInitialized();const s=this.formatTarget(e),n={target:s,expiry:t};this.expirations.set(s,n),this.checkExpiry(s,n),this.events.emit(qm,{target:s,expiration:n})})),nE(this,"get",(e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)})),nE(this,"del",(e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),s=this.getExpiration(t);this.expirations.delete(t),this.events.emit(Wm,{target:t,expiration:s})}})),nE(this,"on",((e,t)=>{this.events.on(e,t)})),nE(this,"once",((e,t)=>{this.events.once(e,t)})),nE(this,"off",((e,t)=>{this.events.off(e,t)})),nE(this,"removeListener",((e,t)=>{this.events.removeListener(e,t)})),this.logger=Nr(s,this.name)}get context(){return Cr(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if("string"==typeof e)return function(e){return Al("topic",e)}(e);if("number"==typeof e)return function(e){return Al("id",e)}(e);const{message:t}=Yc("UNKNOWN_TYPE","Target type: "+typeof e);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(zm)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=Yc("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:t}=Yc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:n}=t;s.toMiliseconds(n)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Hm,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(dn,(()=>this.checkExpirations())),this.events.on(qm,(e=>{const t=qm;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Hm,(e=>{const t=Hm;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Wm,(e=>{const t=Wm;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var iE=Object.defineProperty,oE=(e,t,s)=>((e,t,s)=>t in e?iE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class aE extends Mr{constructor(e,t,n){super(e,t,n),this.core=e,this.logger=t,this.store=n,oE(this,"name","verify-api"),oE(this,"abortController"),oE(this,"isDevEnv"),oE(this,"verifyUrlV3",Gm),oE(this,"storagePrefix",om),oE(this,"version",2),oE(this,"publicKey"),oE(this,"fetchPromise"),oE(this,"init",(async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&s.toMiliseconds(null==(e=this.publicKey)?void 0:e.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))})),oE(this,"register",(async e=>{if(!ul()||this.isDevEnv)return;const t=window.location.origin,{id:n,decryptedId:r}=e,i=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${n}&decryptedId=${r}`;try{const e=l(),t=this.startAbortTimer(5*s.ONE_SECOND),r=await new Promise(((s,r)=>{const o=()=>{window.removeEventListener("message",c),e.body.removeChild(a),r("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=i,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const c=r=>{if(r.data&&"string"==typeof r.data)try{const i=JSON.parse(r.data);if("verify_attestation"===i.type){if(uc(i.attestation).payload.id!==n)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),s(null===i.attestation?"":i.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(a),window.addEventListener("message",c,{signal:this.abortController.signal})}));return this.logger.debug(r,"jwt attestation"),r}catch(e){this.logger.warn(e)}return""})),oE(this,"resolve",(async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:s,encryptedId:n}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if(uc(t).payload.id!==n)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!s)return;const r=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(s,r)})),oE(this,"fetchAttestation",(async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const n=this.startAbortTimer(5*s.ONE_SECOND),r=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(n),200===r.status?await r.json():void 0})),oE(this,"getVerifyUrl",(e=>{let t=e||Km;return Jm.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${Km}`),t=Km),t})),oE(this,"fetchPublicKey",(async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(s.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}})),oE(this,"persistPublicKey",(async e=>{this.logger.debug(e,"persisting public key to local storage"),await this.store.setItem(this.storeKey,e),this.publicKey=e})),oE(this,"removePublicKey",(async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0})),oE(this,"isValidJwtAttestation",(async e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}const s=await this.fetchAndPersistPublicKey();try{if(s)return this.validateAttestation(e,s)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}})),oE(this,"getPublicKey",(async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey())),oE(this,"fetchAndPersistPublicKey",(async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise((async e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))}));const e=await this.fetchPromise;return this.fetchPromise=void 0,e})),oE(this,"validateAttestation",((e,t)=>{const n=Zf(e,t.publicKey),r={hasExpired:s.toMiliseconds(n.exp)<Date.now(),payload:n};if(r.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:r.payload.origin,isScam:r.payload.isScam,isVerified:r.payload.isVerified}})),this.logger=Nr(t,this.name),this.abortController=new AbortController,this.isDevEnv=Rl(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Cr(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout((()=>this.abortController.abort()),s.toMiliseconds(e))}}var cE=Object.defineProperty,lE=(e,t,s)=>((e,t,s)=>t in e?cE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class dE extends Br{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,lE(this,"context","echo"),lE(this,"registerDeviceToken",(async e=>{const{clientId:t,token:s,notificationType:n,enableEncrypted:r=!1}=e,i=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:n,token:s,always_raw:r})})})),this.logger=Nr(t,this.context)}}var hE=Object.defineProperty,uE=Object.getOwnPropertySymbols,pE=Object.prototype.hasOwnProperty,fE=Object.prototype.propertyIsEnumerable,gE=(e,t,s)=>t in e?hE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,mE=(e,t)=>{for(var s in t||(t={}))pE.call(t,s)&&gE(e,s,t[s]);if(uE)for(var s of uE(t))fE.call(t,s)&&gE(e,s,t[s]);return e},yE=(e,t,s)=>gE(e,"symbol"!=typeof t?t+"":t,s);class wE extends jr{constructor(e,t,n=!0){super(e,t,n),this.core=e,this.logger=t,yE(this,"context","event-client"),yE(this,"storagePrefix",om),yE(this,"storageVersion",.1),yE(this,"events",new Map),yE(this,"shouldPersist",!1),yE(this,"init",(async()=>{if(!Rl())try{const e={eventId:xl(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:yl(this.core.relayer.protocol,this.core.relayer.version,Am)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}})),yE(this,"createEvent",(e=>{const{event:t="ERROR",type:s="",properties:{topic:n,trace:r}}=e,i=xl(),o=this.core.projectId||"",a=Date.now(),c=mE({eventId:i,timestamp:a,props:{event:t,type:s,properties:{topic:n,trace:r}},bundleId:o,domain:this.getAppDomain()},this.setMethods(i));return this.telemetryEnabled&&(this.events.set(i,c),this.shouldPersist=!0),c})),yE(this,"getEvent",(e=>{const{eventId:t,topic:s}=e;if(t)return this.events.get(t);const n=Array.from(this.events.values()).find((e=>e.props.properties.topic===s));return n?mE(mE({},n),this.setMethods(n.eventId)):void 0})),yE(this,"deleteEvent",(e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0})),yE(this,"setEventListeners",(()=>{this.core.heartbeat.on(dn,(async()=>{this.shouldPersist&&await this.persist(),this.events.forEach((e=>{s.fromMiliseconds(Date.now())-s.fromMiliseconds(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)}))}))})),yE(this,"setMethods",(e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)}))),yE(this,"addTrace",((e,t)=>{const s=this.events.get(e);s&&(s.props.properties.trace.push(t),this.events.set(e,s),this.shouldPersist=!0)})),yE(this,"setError",((e,t)=>{const s=this.events.get(e);s&&(s.props.type=t,s.timestamp=Date.now(),this.events.set(e,s),this.shouldPersist=!0)})),yE(this,"persist",(async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1})),yE(this,"restore",(async()=>{try{const e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach((e=>{this.events.set(e.eventId,mE(mE({},e),this.setMethods(e.eventId)))}))}catch(e){this.logger.warn(e)}})),yE(this,"submit",(async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,s]of this.events)s.props.type&&e.push(s);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}})),yE(this,"sendEvent",(async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Am}${t}`,{method:"POST",body:JSON.stringify(e)})})),yE(this,"getAppDomain",(()=>ml().url)),this.logger=Nr(t,this.context),this.telemetryEnabled=n,n?this.restore().then((async()=>{await this.submit(),this.setEventListeners()})):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var bE=Object.defineProperty,vE=Object.getOwnPropertySymbols,EE=Object.prototype.hasOwnProperty,CE=Object.prototype.propertyIsEnumerable,NE=(e,t,s)=>t in e?bE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,AE=(e,t)=>{for(var s in t||(t={}))EE.call(t,s)&&NE(e,s,t[s]);if(vE)for(var s of vE(t))CE.call(t,s)&&NE(e,s,t[s]);return e},IE=(e,t,s)=>NE(e,"symbol"!=typeof t?t+"":t,s);class SE extends _r{constructor(e){var s;super(e),IE(this,"protocol","wc"),IE(this,"version",2),IE(this,"name",im),IE(this,"relayUrl"),IE(this,"projectId"),IE(this,"customStoragePrefix"),IE(this,"events",new t),IE(this,"logger"),IE(this,"heartbeat"),IE(this,"relayer"),IE(this,"crypto"),IE(this,"storage"),IE(this,"history"),IE(this,"expirer"),IE(this,"pairing"),IE(this,"verify"),IE(this,"echoClient"),IE(this,"linkModeSupportedApps"),IE(this,"eventClient"),IE(this,"initialized",!1),IE(this,"logChunkController"),IE(this,"on",((e,t)=>this.events.on(e,t))),IE(this,"once",((e,t)=>this.events.once(e,t))),IE(this,"off",((e,t)=>this.events.off(e,t))),IE(this,"removeListener",((e,t)=>this.events.removeListener(e,t))),IE(this,"dispatchEnvelope",(({topic:e,message:t,sessionExists:s})=>{if(!e||!t)return;const n={topic:e,message:t,publishedAt:Date.now(),transportType:Im.link_mode};this.relayer.onLinkMessageEvent(n,{sessionExists:s})}));const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(e){console.warn("Failed to copy global core",e)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||um,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=function(e){return Er(vr({},e),{level:e?.level||Yn})}({level:"string"==typeof e?.logger&&e.logger?e.logger:am,name:im}),{logger:i,chunkLoggerController:o}=Ar({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,null!=(s=this.logChunkController)&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var e,t;null!=(e=this.logChunkController)&&e.downloadLogsBlobInBrowser&&(null==(t=this.logChunkController)||t.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Nr(i,this.name),this.heartbeat=new hn,this.crypto=new vb(this,this.logger,e?.keychain),this.history=new tE(this,this.logger),this.expirer=new rE(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new _n(AE(AE({},cm),e?.storageOptions)),this.relayer=new cv({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Zv(this,this.logger),this.verify=new aE(this,this.logger,this.storage),this.echoClient=new dE(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new wE(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new SE(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",s),t}get context(){return Cr(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return null==(e=this.logChunkController)?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Om,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Om)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[s]} times.`),globalThis[t]}catch(e){return void console.warn("Failed to get global WalletConnect core",e)}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${(null==(t=e.opts)?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(e){console.warn("Failed to set global WalletConnect core",e)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&"true"===process.env.DISABLE_GLOBAL_CORE}catch{return!0}}}const _E=SE,OE="client",TE=`wc@2:${OE}:`,kE=OE,PE="error",xE="WALLETCONNECT_DEEPLINK_CHOICE",RE="Proposal expired",UE=s.SEVEN_DAYS,LE={wc_sessionPropose:{req:{ttl:s.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:s.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:s.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:s.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:s.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:s.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:s.ONE_DAY,prompt:!1,tag:1104},res:{ttl:s.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:s.ONE_DAY,prompt:!1,tag:1106},res:{ttl:s.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:3*s.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:3*s.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:s.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:s.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:s.ONE_DAY,prompt:!1,tag:1112},res:{ttl:s.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:s.ONE_DAY,prompt:!1,tag:1114},res:{ttl:s.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:s.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:s.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:s.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:s.FIVE_MINUTES,prompt:!1,tag:1119}}},DE={min:s.FIVE_MINUTES,max:s.SEVEN_DAYS},ME="IDLE",BE="ACTIVE",jE={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},$E=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],FE="wc@1.5:auth:",qE=`${FE}:PUB_KEY`;var WE=Object.defineProperty,HE=Object.defineProperties,zE=Object.getOwnPropertyDescriptors,VE=Object.getOwnPropertySymbols,KE=Object.prototype.hasOwnProperty,GE=Object.prototype.propertyIsEnumerable,JE=(e,t,s)=>t in e?WE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,YE=(e,t)=>{for(var s in t||(t={}))KE.call(t,s)&&JE(e,s,t[s]);if(VE)for(var s of VE(t))GE.call(t,s)&&JE(e,s,t[s]);return e},XE=(e,t)=>HE(e,zE(t)),ZE=(e,t,s)=>JE(e,"symbol"!=typeof t?t+"":t,s);class QE extends Wr{constructor(t){super(t),ZE(this,"name","engine"),ZE(this,"events",new e),ZE(this,"initialized",!1),ZE(this,"requestQueue",{state:ME,queue:[]}),ZE(this,"sessionRequestQueue",{state:ME,queue:[]}),ZE(this,"emittedSessionRequests",new Ll({limit:500})),ZE(this,"requestQueueDelay",s.ONE_SECOND),ZE(this,"expectedPairingMethodMap",new Map),ZE(this,"recentlyDeletedMap",new Map),ZE(this,"recentlyDeletedLimit",200),ZE(this,"relayMessageCache",[]),ZE(this,"pendingSessions",new Map),ZE(this,"init",(async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(LE)}),this.initialized=!0,setTimeout((async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()}),s.toMiliseconds(this.requestQueueDelay)))})),ZE(this,"connect",(async e=>{var t;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=XE(YE({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=function(e,t){var s,n,r,i,o,a;const c=_g(e),l=_g(t),d={},h=Object.keys(c).concat(Object.keys(l));for(const e of h)d[e]={chains:Tl(null==(s=c[e])?void 0:s.chains,null==(n=l[e])?void 0:n.chains),methods:Tl(null==(r=c[e])?void 0:r.methods,null==(i=l[e])?void 0:i.methods),events:Tl(null==(o=c[e])?void 0:o.events,null==(a=l[e])?void 0:a.events)};return d}(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l,authentication:d,walletPay:h}=n,u=(null==(t=d?.[0])?void 0:t.ttl)||LE.wc_sessionPropose.req.ttl||s.FIVE_MINUTES;this.validateRequestExpiry(u);let p,f=r,g=!1;try{if(f){const e=this.client.core.pairing.pairings.get(f);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),g=e.active}}catch(e){throw this.client.logger.error(`connect() -> pairing.get(${f}) failed`),e}if(!f||!g){const{topic:e,uri:t}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});f=e,p=t}if(!f){const{message:e}=Yc("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(e)}const m=await this.client.core.crypto.generateKeyPair(),y=Sl(u),w=YE(XE(YE(YE({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:"irn"}],proposer:{publicKey:m,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:f},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:x()}),(d||h)&&{requests:{authentication:d?.map((e=>{const{domain:t,chains:s,nonce:n,uri:r,exp:i,nbf:o,type:a,statement:c,requestId:l,resources:d,signatureTypes:h}=e;return{domain:t,chains:s,nonce:n,type:a??"caip122",aud:r,version:"1",iat:(new Date).toISOString(),exp:i,nbf:o,statement:c,requestId:l,resources:d,signatureTypes:h}})),walletPay:h}}),b=Ol("session_connect",w.id),{reject:v,resolve:E,done:C}=Cl(u,RE),N=({id:e})=>{e===w.id&&(this.client.events.off("proposal_expire",N),this.pendingSessions.delete(w.id),this.events.emit(b,{error:{message:RE,code:0}}))};return this.client.events.on("proposal_expire",N),this.events.once(b,(({error:e,session:t})=>{this.client.events.off("proposal_expire",N),e?v(e):t&&E(t)})),await this.setProposal(w.id,w),await this.sendProposeSession({proposal:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:w.id}}}).catch((e=>{throw this.deleteProposal(w.id),e})),{uri:p,approval:C}})),ZE(this,"pair",(async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(e){throw this.client.logger.error("pair() failed"),e}})),ZE(this,"approve",(async e=>{var t,s,n;const r=this.client.core.eventClient.createEvent({properties:{topic:null==(t=e?.id)?void 0:t.toString(),trace:[uy]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw r.setError(Ey),e}try{await this.isValidProposalId(e?.id)}catch(t){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),r.setError(Iy),t}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(Ay),e}const{id:i,relayProtocol:o,namespaces:a,sessionProperties:c,scopedProperties:l,sessionConfig:d,proposalRequestsResponses:h}=e,u=this.client.proposal.get(i);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:p,proposer:f,requiredNamespaces:g,optionalNamespaces:m}=u;let y=null==(s=this.client.core.eventClient)?void 0:s.getEvent({topic:p});y||(y=null==(n=this.client.core.eventClient)?void 0:n.createEvent({type:uy,properties:{topic:p,trace:[uy,py]}}));const w=await this.client.core.crypto.generateKeyPair(),b=f.publicKey,v=await this.client.core.crypto.generateSharedKey(w,b),E=XE(YE(YE(YE({relay:{protocol:o??"irn"},namespaces:a,controller:{publicKey:w,metadata:this.client.metadata},expiry:Sl(UE)},c&&{sessionProperties:c}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),{proposalRequestsResponses:h}),C=Im.relay;y.addTrace(fy);try{await this.client.core.relayer.subscribe(v,{transportType:C,internal:{skipSubscribe:!0}})}catch(e){throw y.setError(Ny),e}y.addTrace(gy);const N=XE(YE({},E),{topic:v,requiredNamespaces:g,optionalNamespaces:m,pairingTopic:p,acknowledged:!1,self:E.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:w,transportType:Im.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(v,N),y.addTrace(yy);try{await this.sendApproveSession({sessionTopic:v,proposal:u,pairingProposalResponse:{relay:{protocol:o??"irn"},responderPublicKey:w},sessionSettleRequest:E,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:YE({correlationId:i},this.getTVFApproveParams(N))}}),y.addTrace(my)}catch(e){throw this.client.logger.error(e),this.client.session.delete(v,Xc("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(v),e}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:f.metadata}),await this.deleteProposal(i),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(v,Sl(UE)),{topic:v,acknowledged:()=>Promise.resolve(this.client.session.get(v))}})),ZE(this,"reject",(async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(e){throw this.client.logger.error("reject() -> isValidReject() failed"),e}const{id:t,reason:s}=e;let n;try{n=this.client.proposal.get(t).pairingTopic}catch(e){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),e}n&&await this.sendError({id:t,topic:n,error:s,rpcOpts:LE.wc_sessionPropose.reject}),await this.deleteProposal(t)})),ZE(this,"update",(async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(e){throw this.client.logger.error("update() -> isValidUpdate() failed"),e}const{topic:t,namespaces:n}=e,{done:r,resolve:i,reject:o}=Cl(s.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),a=x(),c=E().toString(),l=this.client.session.get(t).namespaces;return this.events.once(Ol("session_update",a),(({error:e})=>{e?o(e):i()})),await this.client.session.update(t,{namespaces:n}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch((e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:l}),o(e)})),{acknowledged:r}})),ZE(this,"extend",(async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(e){throw this.client.logger.error("extend() -> isValidExtend() failed"),e}const{topic:t}=e,n=x(),{done:r,resolve:i,reject:o}=Cl(s.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Ol("session_extend",n),(({error:e})=>{e?o(e):i()})),await this.setExpiry(t,Sl(UE)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch((e=>{o(e)})),{acknowledged:r}})),ZE(this,"request",(async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}const{chainId:t,request:s,topic:n,expiry:r=LE.wc_sessionRequest.req.ttl}=e,i=this.client.session.get(n);i?.transportType===Im.relay&&await this.confirmOnlineStateOrThrow();const o=x(),a=E().toString(),{done:c,resolve:l,reject:d}=Cl(r,"Request expired. Please try again.");this.events.once(Ol("session_request",o),(({error:e,result:t})=>{e?d(e):l(t)}));const h="wc_sessionRequest",u=this.getAppLinkIfEnabled(i.peer.metadata,i.transportType);if(u)return await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:n,method:h,params:{request:XE(YE({},s),{expiryTimestamp:Sl(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0,appLink:u}).catch((e=>d(e))),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:t,id:o}),await c();const p={request:XE(YE({},s),{expiryTimestamp:Sl(r)}),chainId:t};return await Promise.all([new Promise((async e=>{await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:n,method:h,params:p,expiry:r,throwOnFailedPublish:!0,tvf:this.getTVFParams(o,p)}).catch((e=>d(e))),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:t,id:o}),e()})),new Promise((async e=>{var t;if(null==(t=i.sessionConfig)||!t.disableDeepLink){const e=await async function(e,t){let s="";try{if(ul()&&(s=localStorage.getItem(t),s))return s;s=await e.getItem(t)}catch(e){console.error(e)}return s}(this.client.core.storage,xE);await kl({id:o,topic:n,wcDeepLink:e})}e()})),c()]).then((e=>e[2]))})),ZE(this,"respond",(async e=>{var t,s;this.isInitialized();const n=this.client.core.eventClient.createEvent({properties:{topic:e?.topic||(null==(s=null==(t=e?.response)?void 0:t.id)?void 0:s.toString()),trace:[wy]}});try{await this.isValidRespond(e)}catch(e){throw n.addTrace(e?.message),n.setError(Sy),e}n.addTrace(by);const{topic:r,response:i}=e,{id:o}=i,a=this.client.session.get(r);a.transportType===Im.relay&&await this.confirmOnlineStateOrThrow();const c=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);try{n.addTrace(vy),P(i)?await this.sendResult({id:o,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:c}):C(i)&&await this.sendError({id:o,topic:r,error:i.error,appLink:c}),this.cleanupAfterResponse(e)}catch(e){throw n.addTrace(e?.message),n.setError(_y),e}})),ZE(this,"ping",(async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(e){throw this.client.logger.error("ping() -> isValidPing() failed"),e}const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=x(),n=E().toString(),{done:r,resolve:i,reject:o}=Cl(s.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Ol("session_ping",e),(({error:e})=>{e?o(e):i()})),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:n}),r()])}else this.client.core.pairing.pairings.keys.includes(t)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:t}))})),ZE(this,"emit",(async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:s,chainId:n}=e,r=E().toString(),i=x();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:i})})),ZE(this,"disconnect",(async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Xc("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=Yc("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}})),ZE(this,"find",(e=>(this.isInitialized(),this.client.session.getAll().filter((t=>function(e,t){const{requiredNamespaces:s}=t,n=Object.keys(e.namespaces),r=Object.keys(s);let i=!0;return!!bl(r,n)&&(n.forEach((t=>{const{accounts:n,methods:r,events:o}=e.namespaces[t],a=Ng(n),c=s[t];bl(Kc(t,c),a)&&bl(c.methods,r)&&bl(c.events,o)||(i=!1)})),i)}(t,e)))))),ZE(this,"getPendingSessionRequests",(()=>this.client.pendingRequest.getAll())),ZE(this,"authenticate",(async(e,t)=>{var s;this.isInitialized(),this.isValidAuthenticate(e);const n=t&&this.client.core.linkModeSupportedApps.includes(t)&&(null==(s=this.client.metadata.redirect)?void 0:s.linkMode),r=n?Im.link_mode:Im.relay;r===Im.relay&&await this.confirmOnlineStateOrThrow();const{chains:i,statement:o="",uri:a,domain:c,nonce:l,type:d,exp:h,nbf:u,methods:p=[],expiry:f}=e,g=[...e.resources||[]],{topic:m,uri:y}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:y}});const w=await this.client.core.crypto.generateKeyPair(),b=Ff(w);if(await Promise.all([this.client.auth.authKeys.set(qE,{responseTopic:b,publicKey:w}),this.client.auth.pairingTopics.set(b,{topic:b,pairingTopic:m})]),await this.client.core.relayer.subscribe(b,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${m}`),p.length>0){const{namespace:e}=Vc(i[0]);let t=Jh(e,"request",p);Qh(g)&&(t=Yh(t,g.pop())),g.push(t)}const E=f&&f>LE.wc_sessionAuthenticate.req.ttl?f:LE.wc_sessionAuthenticate.req.ttl,C={authPayload:{type:d??"caip122",chains:i,statement:o,aud:a,domain:c,version:"1",nonce:l,iat:(new Date).toISOString(),exp:h,nbf:u,resources:g},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:Sl(E)},N={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:i,methods:[...new Set(["personal_sign",...p])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:Sl(LE.wc_sessionPropose.req.ttl),id:x()},{done:A,resolve:I,reject:S}=Cl(E,"Request expired"),_=x(),O=Ol("session_connect",N.id),T=Ol("session_request",_),k=async({error:e,session:t})=>{this.events.off(T,P),e?S(e):t&&I({session:t})},P=async e=>{var s,n,i;if(await this.deletePendingAuthRequest(_,{message:"fulfilled",code:0}),e.error){const t=Xc("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(O,k),S(e.error.message))}await this.deleteProposal(N.id),this.events.off(O,k);const{cacaos:o,responder:a}=e.result,c=[],l=[];for(const e of o){await Wh({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),S(Xc("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:t}=e,s=Qh(t.resources),n=[Fh(t.iss)],r=qh(t.iss);if(s){const e=Xh(s),t=Zh(s);c.push(...e),n.push(...t)}for(const e of n)l.push(`${e}:${r}`)}const d=await this.client.core.crypto.generateSharedKey(w,a.publicKey);let h;c.length>0&&(h={topic:d,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:a,controller:a.publicKey,expiry:Sl(UE),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:Og([...new Set(c)],[...new Set(l)]),transportType:r},await this.client.core.relayer.subscribe(d,{transportType:r}),await this.client.session.set(d,h),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:a.metadata}),h=this.client.session.get(d)),null!=(s=this.client.metadata.redirect)&&s.linkMode&&null!=(n=a.metadata.redirect)&&n.linkMode&&null!=(i=a.metadata.redirect)&&i.universal&&t&&(this.client.core.addLinkModeSupportedApp(a.metadata.redirect.universal),this.client.session.update(d,{transportType:Im.link_mode})),I({auths:o,session:h})};let R;this.events.once(O,k),this.events.once(T,P);try{if(n){const e=v("wc_sessionAuthenticate",C,_);this.client.core.history.set(m,e);const s=await this.client.core.crypto.encode("",e,{type:Lf,encoding:Pf});R=pg(t,m,s)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:C,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:_}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:N,expiry:LE.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:N.id})])}catch(e){throw this.events.off(O,k),this.events.off(T,P),e}return await this.setProposal(N.id,N),await this.setAuthRequest(_,{request:XE(YE({},C),{verifyContext:{}}),pairingTopic:m,transportType:r}),{uri:R??y,response:A}})),ZE(this,"approveSessionAuthenticate",(async e=>{const{id:t,auths:s}=e,n=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[Oy]}});try{this.isInitialized()}catch(e){throw n.setError(Ly),e}const r=this.getPendingAuthRequest(t);if(!r)throw n.setError(jy),new Error(`Could not find pending auth request with id ${t}`);const i=r.transportType||Im.relay;i===Im.relay&&await this.confirmOnlineStateOrThrow();const o=r.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ff(o),l={type:Uf,receiverPublicKey:o,senderPublicKey:a},d=[],h=[];for(const e of s){if(!await Wh({cacao:e,projectId:this.client.core.projectId})){n.setError(Dy);const e=Xc("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:c,error:e,encodeOpts:l}),new Error(e.message)}n.addTrace(ky);const{p:s}=e,r=Qh(s.resources),i=[Fh(s.iss)],o=qh(s.iss);if(r){const e=Xh(r),t=Zh(r);d.push(...e),i.push(...t)}for(const e of i)h.push(`${e}:${o}`)}const u=await this.client.core.crypto.generateSharedKey(a,o);let p;if(n.addTrace(Ty),d?.length>0){p={topic:u,acknowledged:!0,self:{publicKey:a,metadata:this.client.metadata},peer:{publicKey:o,metadata:r.requester.metadata},controller:o,expiry:Sl(UE),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:Og([...new Set(d)],[...new Set(h)]),transportType:i},n.addTrace(xy);try{await this.client.core.relayer.subscribe(u,{transportType:i})}catch(e){throw n.setError(My),e}n.addTrace(Ry),await this.client.session.set(u,p),n.addTrace(Py),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}n.addTrace(Uy);try{await this.sendResult({topic:c,id:t,result:{cacaos:s,responder:{publicKey:a,metadata:this.client.metadata}},encodeOpts:l,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(r.requester.metadata,i)})}catch(e){throw n.setError(By),e}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:r.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:p}})),ZE(this,"rejectSessionAuthenticate",(async e=>{this.isInitialized();const{id:t,reason:s}=e,n=this.getPendingAuthRequest(t);if(!n)throw new Error(`Could not find pending auth request with id ${t}`);n.transportType===Im.relay&&await this.confirmOnlineStateOrThrow();const r=n.requester.publicKey,i=await this.client.core.crypto.generateKeyPair(),o=Ff(r),a={type:Uf,receiverPublicKey:r,senderPublicKey:i};await this.sendError({id:t,topic:o,error:s,encodeOpts:a,rpcOpts:LE.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.deleteProposal(t)})),ZE(this,"formatAuthMessage",(e=>{this.isInitialized();const{request:t,iss:s}=e;return Hh(t,s)})),ZE(this,"processRelayMessageCache",(()=>{setTimeout((async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}}),50)})),ZE(this,"cleanupDuplicatePairings",(async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter((s=>{var n,r;return(null==(n=s.peerMetadata)?void 0:n.url)&&(null==(r=s.peerMetadata)?void 0:r.url)===e.peer.metadata.url&&s.topic&&s.topic!==t.topic}));if(0===s.length)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map((e=>this.client.core.pairing.disconnect({topic:e.topic})))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}})),ZE(this,"deleteSession",(async e=>{var t;const{topic:s,expirerHasDeleted:n=!1,emitEvent:r=!0,id:i=0}=e,{self:o}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,Xc("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(o.publicKey)&&await this.client.core.crypto.deleteKeyPair(o.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(xE).catch((e=>this.client.logger.warn(e))),s===(null==(t=this.sessionRequestQueue.queue[0])?void 0:t.topic)&&(this.sessionRequestQueue.state=ME),await Promise.all(this.getPendingSessionRequests().filter((e=>e.topic===s)).map((e=>this.deletePendingSessionRequest(e.id,Xc("USER_DISCONNECTED"))))),r&&this.client.events.emit("session_delete",{id:i,topic:s})})),ZE(this,"deleteProposal",(async(e,t)=>{if(t)try{const t=this.client.proposal.get(e),s=this.client.core.eventClient.getEvent({topic:t.pairingTopic});s?.setError(Cy)}catch{}await Promise.all([this.client.proposal.delete(e,Xc("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")})),ZE(this,"deletePendingSessionRequest",(async(e,t,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter((t=>t.id!==e)),s&&(this.sessionRequestQueue.state=ME,this.client.events.emit("session_request_expire",{id:e}))})),ZE(this,"deletePendingAuthRequest",(async(e,t,s=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)])})),ZE(this,"setExpiry",(async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))})),ZE(this,"setProposal",(async(e,t)=>{this.client.core.expirer.set(e,Sl(LE.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)})),ZE(this,"setAuthRequest",(async(e,t)=>{const{request:s,pairingTopic:n,transportType:r=Im.relay}=t;this.client.core.expirer.set(e,s.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:e,pairingTopic:n,verifyContext:s.verifyContext,transportType:r})})),ZE(this,"setPendingSessionRequest",(async e=>{const{id:t,topic:s,params:n,verifyContext:r}=e,i=n.request.expiryTimestamp||Sl(LE.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,i),await this.client.pendingRequest.set(t,{id:t,topic:s,params:n,verifyContext:r})})),ZE(this,"sendRequest",(async e=>{const{topic:t,method:s,params:n,expiry:r,relayRpcId:i,clientRpcId:o,throwOnFailedPublish:a,appLink:c,tvf:l,publishOpts:d={}}=e,h=v(s,n,o);let u;const p=!!c;try{const e=p?Pf:kf;u=await this.client.core.crypto.encode(t,h,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),e}let f;if($E.includes(s)){const e=qf(JSON.stringify(h)),t=qf(u);f=await this.client.core.verify.register({id:t,decryptedId:e})}const g=YE(YE({},LE[s].req),d);if(g.attestation=f,r&&(g.ttl=r),i&&(g.id=i),this.client.core.history.set(t,h),p){const e=pg(c,t,u);await global.Linking.openURL(e,this.client.name)}else g.tvf=XE(YE({},l),{correlationId:h.id}),a?(g.internal=XE(YE({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,u,g)):this.client.core.relayer.publish(t,u,g).catch((e=>this.client.logger.error(e)));return h.id})),ZE(this,"sendProposeSession",(async e=>{const{proposal:t,publishOpts:s}=e,n=v("wc_sessionPropose",t,t.id);this.client.core.history.set(t.pairingTopic,n);const r=await this.client.core.crypto.encode(t.pairingTopic,n,{encoding:kf}),i=qf(JSON.stringify(n)),o=qf(r),a=await this.client.core.verify.register({id:o,decryptedId:i});await this.client.core.relayer.publishCustom({payload:{pairingTopic:t.pairingTopic,sessionProposal:r},opts:XE(YE({},s),{publishMethod:"wc_proposeSession",attestation:a})})})),ZE(this,"sendApproveSession",(async e=>{const{sessionTopic:t,pairingProposalResponse:s,proposal:n,sessionSettleRequest:r,publishOpts:i}=e,o=k(n.id,s),a=await this.client.core.crypto.encode(n.pairingTopic,o,{encoding:kf}),c=v("wc_sessionSettle",r,i?.id),l=await this.client.core.crypto.encode(t,c,{encoding:kf});this.client.core.history.set(t,c),await this.client.core.relayer.publishCustom({payload:{sessionTopic:t,pairingTopic:n.pairingTopic,sessionProposalResponse:a,sessionSettlementRequest:l},opts:XE(YE({},i),{publishMethod:"wc_approveSession"})})})),ZE(this,"sendResult",(async e=>{const{id:t,topic:s,result:n,throwOnFailedPublish:r,encodeOpts:i,appLink:o}=e,a=k(t,n);let c;const l=o&&typeof(null==global?void 0:global.Linking)<"u";try{const e=l?Pf:kf;c=await this.client.core.crypto.encode(s,a,XE(YE({},i||{}),{encoding:e}))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),e}let d,h;try{d=await this.client.core.history.get(s,t);const e=d.request;try{h=this.getTVFParams(t,e.params,n)}catch(e){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${e?.message}`)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${t}) failed`),e}if(l){const e=pg(o,s,c);await global.Linking.openURL(e,this.client.name)}else{const e=d.request.method,n=LE[e].res;n.tvf=XE(YE({},h),{correlationId:t}),r?(n.internal=XE(YE({},n.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,c,n)):this.client.core.relayer.publish(s,c,n).catch((e=>this.client.logger.error(e)))}await this.client.core.history.resolve(a)})),ZE(this,"sendError",(async e=>{const{id:t,topic:s,error:n,encodeOpts:r,rpcOpts:i,appLink:o}=e,a=_(t,n);let c;const l=o&&typeof(null==global?void 0:global.Linking)<"u";try{const e=l?Pf:kf;c=await this.client.core.crypto.encode(s,a,XE(YE({},r||{}),{encoding:e}))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),e}let d;try{d=await this.client.core.history.get(s,t)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${s}, ${t}) failed`),e}if(l){const e=pg(o,s,c);await global.Linking.openURL(e,this.client.name)}else{const e=d.request.method,t=i||LE[e].res;this.client.core.relayer.publish(s,c,t)}await this.client.core.history.resolve(a)})),ZE(this,"cleanup",(async()=>{const e=[],t=[];this.client.session.getAll().forEach((t=>{let s=!1;_l(t.expiry)&&(s=!0),this.client.core.crypto.keychain.has(t.topic)||(s=!0),s&&e.push(t.topic)})),this.client.proposal.getAll().forEach((e=>{_l(e.expiryTimestamp)&&t.push(e.id)})),await Promise.all([...e.map((e=>this.deleteSession({topic:e}))),...t.map((e=>this.deleteProposal(e)))])})),ZE(this,"onProviderMessageEvent",(async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)})),ZE(this,"onRelayEventRequest",(async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()})),ZE(this,"processRequestsQueue",(async()=>{if(this.requestQueue.state!==BE){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=BE;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=ME}else this.client.logger.info("Request queue already active, skipping...")})),ZE(this,"processRequest",(async e=>{const{topic:t,payload:s,attestation:n,transportType:r,encryptedId:i}=e,o=s.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:o}))switch(o){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:s,attestation:n,encryptedId:i});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,s);case"wc_sessionPing":return await this.onSessionPingRequest(t,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:s,attestation:n,encryptedId:i,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(t,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:s,attestation:n,encryptedId:i,transportType:r});default:return this.client.logger.info(`Unsupported request method ${o}`)}})),ZE(this,"onRelayEventResponse",(async e=>{const{topic:t,payload:s,transportType:n}=e,r=(await this.client.core.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}})),ZE(this,"onRelayEventUnknownPayload",(e=>{const{topic:t}=e,{message:s}=Yc("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)})),ZE(this,"shouldIgnorePairingRequest",(e=>{const{topic:t,requestMethod:s}=e,n=this.expectedPairingMethodMap.get(t);return!(!n||n.includes(s))&&!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)})),ZE(this,"onSessionProposeRequest",(async e=>{const{topic:t,payload:s,attestation:n,encryptedId:r}=e,{params:i,id:o}=s;try{const e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(console.warn("No listener for session_proposal event"),e?.setError(hy)),this.isValidConnect(YE({},s.params));const a=i.expiryTimestamp||Sl(LE.wc_sessionPropose.req.ttl),c=YE({id:o,pairingTopic:t,expiryTimestamp:a,attestation:n,encryptedId:r},i);await this.setProposal(o,c);const l=await this.getVerifyContext({attestationId:n,hash:qf(JSON.stringify(s)),encryptedId:r,metadata:c.proposer.metadata});e?.addTrace(iy),this.client.events.emit("session_proposal",{id:o,params:c,verifyContext:l})}catch(e){await this.sendError({id:o,topic:t,error:e,rpcOpts:LE.wc_sessionPropose.autoReject}),this.client.logger.error(e)}})),ZE(this,"onSessionProposeResponse",(async(e,t,s)=>{const{id:n}=t;if(P(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const i=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:i});const o=i.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:o});const a=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(n,{sessionTopic:c,pairingTopic:e,proposalId:n,publicKey:o});const l=await this.client.core.relayer.subscribe(c,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:e})}else if(C(t)){await this.deleteProposal(n);const e=Ol("session_connect",n);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}})),ZE(this,"onSessionSettleRequest",(async(e,t)=>{const{id:s,params:n}=t;try{this.isValidSessionSettleRequest(n);const{relay:s,controller:r,expiry:i,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:l,proposalRequestsResponses:d}=t.params,h=[...this.pendingSessions.values()].find((t=>t.sessionTopic===e));if(!h)return this.client.logger.error(`Pending session not found for topic ${e}`);const u=this.client.proposal.get(h.proposalId),p=XE(YE(YE(YE({topic:e,relay:s,expiry:i,namespaces:o,acknowledged:!0,pairingTopic:h.pairingTopic,requiredNamespaces:u.requiredNamespaces,optionalNamespaces:u.optionalNamespaces,controller:r.publicKey,self:{publicKey:h.publicKey,metadata:this.client.metadata},peer:{publicKey:r.publicKey,metadata:r.metadata}},a&&{sessionProperties:a}),c&&{scopedProperties:c}),l&&{sessionConfig:l}),{transportType:Im.relay,authentication:d?.authentication,walletPayResult:d?.walletPay});await this.client.session.set(p.topic,p),await this.setExpiry(p.topic,p.expiry),await this.client.core.pairing.updateMetadata({topic:h.pairingTopic,metadata:p.peer.metadata}),this.pendingSessions.delete(h.proposalId),this.deleteProposal(h.proposalId,!1),this.cleanupDuplicatePairings(p),await this.sendResult({id:t.id,topic:e,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:p}),this.events.emit(Ol("session_connect",h.proposalId),{session:p})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}})),ZE(this,"onSessionSettleResponse",(async(e,t)=>{const{id:s}=t;P(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Ol("session_approve",s),{})):C(t)&&(await this.client.session.delete(e,Xc("USER_DISCONNECTED")),this.events.emit(Ol("session_approve",s),{error:t.error}))})),ZE(this,"onSessionUpdateRequest",(async(e,t)=>{const{params:s,id:n}=t;try{const t=`${e}_session_update`,r=Yg.get(t);if(r&&this.isRequestOutOfSync(r,n))return this.client.logger.warn(`Discarding out of sync request - ${n}`),void this.sendError({id:n,topic:e,error:Xc("INVALID_UPDATE_REQUEST")});this.isValidUpdate(YE({topic:e},s));try{Yg.set(t,n),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:e,result:!0})}catch(e){throw Yg.delete(t),e}this.client.events.emit("session_update",{id:n,topic:e,params:s})}catch(t){await this.sendError({id:n,topic:e,error:t}),this.client.logger.error(t)}})),ZE(this,"isRequestOutOfSync",((e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3))),ZE(this,"onSessionUpdateResponse",((e,t)=>{const{id:s}=t,n=Ol("session_update",s);if(0===this.events.listenerCount(n))throw new Error(`emitting ${n} without any listeners`);P(t)?this.events.emit(Ol("session_update",s),{}):C(t)&&this.events.emit(Ol("session_update",s),{error:t.error})})),ZE(this,"onSessionExtendRequest",(async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Sl(UE)),await this.sendResult({id:s,topic:e,result:!0}),this.client.events.emit("session_extend",{id:s,topic:e})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}})),ZE(this,"onSessionExtendResponse",((e,t)=>{const{id:s}=t,n=Ol("session_extend",s);if(0===this.events.listenerCount(n))throw new Error(`emitting ${n} without any listeners`);P(t)?this.events.emit(Ol("session_extend",s),{}):C(t)&&this.events.emit(Ol("session_extend",s),{error:t.error})})),ZE(this,"onSessionPingRequest",(async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:e})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}})),ZE(this,"onSessionPingResponse",((e,t)=>{const{id:s}=t,n=Ol("session_ping",s);setTimeout((()=>{if(0===this.events.listenerCount(n))throw new Error(`emitting ${n} without any listeners 2176`);P(t)?this.events.emit(Ol("session_ping",s),{}):C(t)&&this.events.emit(Ol("session_ping",s),{error:t.error})}),500)})),ZE(this,"onSessionDeleteRequest",(async(e,t)=>{const{id:s}=t;try{await this.isValidDisconnect({topic:e,reason:t.params}),this.cleanupPendingSentRequestsForTopic({topic:e,error:Xc("USER_DISCONNECTED")}),await this.deleteSession({topic:e,id:s})}catch(e){this.client.logger.error(e)}})),ZE(this,"onSessionRequest",(async e=>{var t,s,n;const{topic:r,payload:i,attestation:o,encryptedId:a,transportType:c}=e,{id:l,params:d}=i;try{await this.isValidRequest(YE({topic:r},d));const e=this.client.session.get(r),i={id:l,topic:r,params:d,verifyContext:await this.getVerifyContext({attestationId:o,hash:qf(JSON.stringify(v("wc_sessionRequest",d,l))),encryptedId:a,metadata:e.peer.metadata,transportType:c})};await this.setPendingSessionRequest(i),c===Im.link_mode&&null!=(t=e.peer.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(null==(s=e.peer.metadata.redirect)?void 0:s.universal),null!=(n=this.client.signConfig)&&n.disableRequestQueue?this.emitSessionRequest(i):(this.addSessionRequestToSessionRequestQueue(i),this.processSessionRequestQueue())}catch(e){await this.sendError({id:l,topic:r,error:e}),this.client.logger.error(e)}})),ZE(this,"onSessionRequestResponse",((e,t)=>{const{id:s}=t,n=Ol("session_request",s);if(0===this.events.listenerCount(n))throw new Error(`emitting ${n} without any listeners`);P(t)?this.events.emit(Ol("session_request",s),{result:t.result}):C(t)&&this.events.emit(Ol("session_request",s),{error:t.error})})),ZE(this,"onSessionEventRequest",(async(e,t)=>{const{id:s,params:n}=t;try{const t=`${e}_session_event_${n.event.name}`,r=Yg.get(t);if(r&&this.isRequestOutOfSync(r,s))return void this.client.logger.info(`Discarding out of sync request - ${s}`);this.isValidEmit(YE({topic:e},n)),this.client.events.emit("session_event",{id:s,topic:e,params:n}),Yg.set(t,s)}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}})),ZE(this,"onSessionAuthenticateResponse",((e,t)=>{const{id:s}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),P(t)?this.events.emit(Ol("session_request",s),{result:t.result}):C(t)&&this.events.emit(Ol("session_request",s),{error:t.error})})),ZE(this,"onSessionAuthenticateRequest",(async e=>{var t;const{topic:s,payload:n,attestation:r,encryptedId:i,transportType:o}=e;try{const{requester:e,authPayload:a,expiryTimestamp:c}=n.params,l=await this.getVerifyContext({attestationId:r,hash:qf(JSON.stringify(n)),encryptedId:i,metadata:e.metadata,transportType:o}),d={requester:e,pairingTopic:s,id:n.id,authPayload:a,verifyContext:l,expiryTimestamp:c};await this.setAuthRequest(n.id,{request:d,pairingTopic:s,transportType:o}),o===Im.link_mode&&null!=(t=e.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:l})}catch(e){this.client.logger.error(e);const t=n.params.requester.publicKey,r=await this.client.core.crypto.generateKeyPair(),i=this.getAppLinkIfEnabled(n.params.requester.metadata,o),a={type:Uf,receiverPublicKey:t,senderPublicKey:r};await this.sendError({id:n.id,topic:s,error:e,encodeOpts:a,rpcOpts:LE.wc_sessionAuthenticate.autoReject,appLink:i})}})),ZE(this,"addSessionRequestToSessionRequestQueue",(e=>{this.sessionRequestQueue.queue.push(e)})),ZE(this,"cleanupAfterResponse",(e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout((()=>{this.sessionRequestQueue.state=ME,this.processSessionRequestQueue()}),s.toMiliseconds(this.requestQueueDelay))})),ZE(this,"cleanupPendingSentRequestsForTopic",(({topic:e,error:t})=>{const s=this.client.core.history.pending;s.length>0&&s.filter((t=>t.topic===e&&"wc_sessionRequest"===t.request.method)).forEach((e=>{this.events.emit(Ol("session_request",e.request.id),{error:t})}))})),ZE(this,"processSessionRequestQueue",(()=>{if(this.sessionRequestQueue.state===BE)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.emitSessionRequest(e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")})),ZE(this,"emitSessionRequest",(e=>{this.emittedSessionRequests.has(e.id)?this.client.logger.warn({id:e.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${e.id}`):(this.sessionRequestQueue.state=BE,this.emittedSessionRequests.add(e.id),this.client.events.emit("session_request",e))})),ZE(this,"onPairingCreated",(e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find((t=>t.pairingTopic===e.topic));t&&this.onSessionProposeRequest({topic:e.topic,payload:v("wc_sessionPropose",XE(YE({},t),{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties}),t.id),attestation:t.attestation,encryptedId:t.encryptedId})})),ZE(this,"isValidConnect",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:r,scopedProperties:i,relays:o}=e;if(Pg(t)||await this.isValidPairingTopic(t),!function(e,t){let s=!1;return t&&!e?s=!0:e&&Tg(e)&&e.length&&e.forEach((e=>{s=$g(e)})),s}(o,!0)){const{message:e}=Yc("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(s&&!Pg(s)&&0!==kg(s)){const e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(e):this.client.logger.warn(e),this.validateNamespaces(s,"requiredNamespaces")}if(n&&!Pg(n)&&0!==kg(n)&&this.validateNamespaces(n,"optionalNamespaces"),r&&!Pg(r)&&this.validateSessionProps(r,"sessionProperties"),i&&!Pg(i)){this.validateSessionProps(i,"scopedProperties");const e=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(i).every((t=>e.includes(t.split(":")[0]))))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(i)}, required/optional namespaces: ${JSON.stringify(e)}`)}})),ZE(this,"validateNamespaces",((e,t)=>{const s=function(e,t,s){let n=null;if(e&&kg(e)){const r=Bg(e,t);r&&(n=r);const i=Dg(e,t,s);i&&(n=i)}else n=Yc("MISSING_OR_INVALID",`${t}, ${s} should be an object with data`);return n}(e,"connect()",t);if(s)throw new Error(s.message)})),ZE(this,"isValidApprove",(async e=>{if(!Fg(e))throw new Error(Yc("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:n,sessionProperties:r,scopedProperties:i}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const o=this.client.proposal.get(t),a=jg(s,"approve()");if(a)throw new Error(a.message);const c=zg(o.requiredNamespaces,s,"approve()");if(c)throw new Error(c.message);if(!xg(n,!0)){const{message:e}=Yc("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(e)}if(r&&!Pg(r)&&this.validateSessionProps(r,"sessionProperties"),i&&!Pg(i)){this.validateSessionProps(i,"scopedProperties");const e=new Set(Object.keys(s));if(!Object.keys(i).every((t=>e.has(t.split(":")[0]))))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(i)}, approved namespaces: ${Array.from(e).join(", ")}`)}})),ZE(this,"isValidReject",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:s}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!function(e){return!!(e&&"object"==typeof e&&e.code&&Rg(e.code,!1)&&e.message&&xg(e.message,!1))}(s)){const{message:e}=Yc("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(e)}})),ZE(this,"isValidSessionSettleRequest",(e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:s,namespaces:n,expiry:r}=e;if(!$g(t)){const{message:e}=Yc("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const i=function(e,t){let s=null;return xg(e?.publicKey,!1)||(s=Yc("MISSING_OR_INVALID",`${t} controller public key should be a string`)),s}(s,"onSessionSettleRequest()");if(i)throw new Error(i.message);const o=jg(n,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(_l(r)){const{message:e}=Yc("EXPIRED","onSessionSettleRequest()");throw new Error(e)}})),ZE(this,"isValidUpdate",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:s}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const n=this.client.session.get(t),r=jg(s,"update()");if(r)throw new Error(r.message);const i=zg(n.requiredNamespaces,s,"update()");if(i)throw new Error(i.message)})),ZE(this,"isValidExtend",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)})),ZE(this,"isValidRequest",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:s,chainId:n,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:i}=this.client.session.get(t);if(!qg(i,n)){const{message:e}=Yc("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(e)}if(!function(e){return!(Pg(e)||!xg(e.method,!1))}(s)){const{message:e}=Yc("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(e)}if(!Wg(i,n,s.method)){const{message:e}=Yc("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(e)}this.validateRequestExpiry(r)})),ZE(this,"isValidRespond",(async e=>{var t;if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:s,response:n}=e;try{await this.isValidSessionTopic(s)}catch(s){throw null!=(t=e?.response)&&t.id&&this.cleanupAfterResponse(e),s}if(!function(e){return!(Pg(e)||Pg(e.result)&&Pg(e.error)||!Rg(e.id,!1)||!xg(e.jsonrpc,!1))}(n)){const{message:e}=Yc("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(e)}const r=this.client.pendingRequest.get(n.id);if(r.topic!==s){const{message:e}=Yc("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${r.topic}, received topic: ${s}`);throw new Error(e)}})),ZE(this,"isValidPing",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)})),ZE(this,"isValidEmit",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:s,chainId:n}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!qg(r,n)){const{message:e}=Yc("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(e)}if(!function(e){return!(Pg(e)||!xg(e.name,!1))}(s)){const{message:e}=Yc("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}if(!Hg(r,n,s.name)){const{message:e}=Yc("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}})),ZE(this,"isValidDisconnect",(async e=>{if(!Fg(e)){const{message:t}=Yc("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)})),ZE(this,"isValidAuthenticate",(e=>{const{chains:t,uri:s,domain:n,nonce:r}=e;if(!Array.isArray(t)||0===t.length)throw new Error("chains is required and must be a non-empty array");if(!xg(s,!1))throw new Error("uri is required parameter");if(!xg(n,!1))throw new Error("domain is required parameter");if(!xg(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map((e=>Vc(e).namespace)))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:i}=Vc(t[0]);if("eip155"!==i)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")})),ZE(this,"getVerifyContext",(async e=>{const{attestationId:t,hash:s,encryptedId:n,metadata:r,transportType:i}=e,o={verified:{verifyUrl:r.verifyUrl||Km,validation:"UNKNOWN",origin:r.url||""}};try{if(i===Im.link_mode){const e=this.getAppLinkIfEnabled(r,i);return o.verified.validation=e&&new URL(e).origin===new URL(r.url).origin?"VALID":"INVALID",o}const e=await this.client.core.verify.resolve({attestationId:t,hash:s,encryptedId:n,verifyUrl:r.verifyUrl});e&&(o.verified.origin=e.origin,o.verified.isScam=e.isScam,o.verified.validation=e.origin===new URL(r.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.warn(e)}return this.client.logger.debug(`Verify context: ${JSON.stringify(o)}`),o})),ZE(this,"validateSessionProps",((e,t)=>{Object.values(e).forEach(((s,n)=>{if(null==s){const{message:r}=Yc("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${s} for key ${Object.keys(e)[n]}`);throw new Error(r)}}))})),ZE(this,"getPendingAuthRequest",(e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0})),ZE(this,"addToRecentlyDeleted",((e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;for(const s of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(s)}}})),ZE(this,"checkRecentlyDeleted",(e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=Yc("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}})),ZE(this,"isLinkModeEnabled",((e,t)=>{var s,n,r,i,o,a,c,l,d;return!(!e||t!==Im.link_mode)&&(!0===(null==(n=null==(s=this.client.metadata)?void 0:s.redirect)?void 0:n.linkMode)&&void 0!==(null==(i=null==(r=this.client.metadata)?void 0:r.redirect)?void 0:i.universal)&&""!==(null==(a=null==(o=this.client.metadata)?void 0:o.redirect)?void 0:a.universal)&&void 0!==(null==(c=e?.redirect)?void 0:c.universal)&&""!==(null==(l=e?.redirect)?void 0:l.universal)&&!0===(null==(d=e?.redirect)?void 0:d.linkMode)&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof(null==global?void 0:global.Linking)<"u")})),ZE(this,"getAppLinkIfEnabled",((e,t)=>{var s;return this.isLinkModeEnabled(e,t)?null==(s=e?.redirect)?void 0:s.universal:void 0})),ZE(this,"handleLinkModeMessage",(({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=Pl(e,"topic")||"",s=decodeURIComponent(Pl(e,"wc_ev")||""),n=this.client.session.keys.includes(t);n&&this.client.session.update(t,{transportType:Im.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:n})})),ZE(this,"registerLinkModeListeners",(async()=>{var e;if(Rl()||hl()&&null!=(e=this.client.metadata.redirect)&&e.linkMode){const e=null==global?void 0:global.Linking;if(typeof e<"u"){e.addEventListener("url",this.handleLinkModeMessage,this.client.name);const t=await e.getInitialURL();t&&setTimeout((()=>{this.handleLinkModeMessage({url:t})}),50)}}})),ZE(this,"getTVFApproveParams",(e=>{try{const t=Ag(e.namespaces),s=function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...e.methods)})),[...new Set(t)]}(e.namespaces),n=function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...e.events)})),[...new Set(t)]}(e.namespaces),r=e.sessionProperties;return{approvedChains:t,approvedMethods:s,approvedEvents:n,sessionProperties:r,scopedProperties:e.scopedProperties}}catch(e){return this.client.logger.warn(e,"Error getting TVF approve params"),{}}})),ZE(this,"getTVFParams",((e,t,s)=>{var n,r,i;if(null==(n=t.request)||!n.method)return{};const o={correlationId:e,rpcMethods:[t.request.method],chainId:t.chainId};try{const e=this.extractTxHashesFromResult(t.request,s);o.txHashes=e,o.contractAddresses=this.isValidContractData(t.request.params)?[null==(i=null==(r=t.request.params)?void 0:r[0])?void 0:i.to]:[]}catch(e){this.client.logger.warn(e,"Error getting TVF params")}return o})),ZE(this,"isValidContractData",(e=>{var t;if(!e)return!1;try{const s=e?.data||(null==(t=e?.[0])?void 0:t.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return!!/^[0-9a-fA-F]*$/.test(n)&&n.length%2==0}catch{}return!1})),ZE(this,"extractTxHashesFromResult",((e,t)=>{var s;try{if(!t)return[];const n=e.method,r=jE[n];if("sui_signTransaction"===n)return[Ah(t.transactionBytes)];if("near_signTransaction"===n)return[Ih(t)];if("near_signTransactions"===n)return t.map((e=>Ih(e)));if("xrpl_signTransactionFor"===n||"xrpl_signTransaction"===n)return[null==(s=t.tx_json)?void 0:s.hash];if("polkadot_signTransaction"===n)return[Qg({transaction:e.params.transactionPayload,signature:t.signature})];if("algo_signTxn"===n)return Tg(t)?t.map((e=>Sh(e))):[Sh(t)];if("cosmos_signDirect"===n)return[Oh(t)];if("wallet_sendCalls"===n)return function(e){var t,s;const n=[];try{if("string"==typeof e)return n.push(e),n;if("object"!=typeof e)return n;null!=e&&e.id&&n.push(e.id);const r=null==(s=null==(t=e?.capabilities)?void 0:t.caip345)?void 0:s.transactionHashes;r&&n.push(...r)}catch(e){console.warn("getWalletSendCallsHashes failed: ",e)}return n}(t);if("string"==typeof t)return[t];const i=t[r.key];if(Tg(i))return"solana_signAllTransactions"===n?i.map((e=>function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);const n=s[0];if(0===n)throw new Error("No signatures found");const r=1+64*n;if(s.length<r)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const i=Buffer.from(e,"base64").slice(1,65);return Bc.encode(i)}(e))):i;if("string"==typeof i)return[i]}catch(e){this.client.logger.warn(e,"Error extracting tx hashes from result")}return[]}))}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[e,s]of Object.entries(t))for(const t of s)try{await this.onProviderMessageEvent({topic:e,message:t,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${e}, message: ${t}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=Yc("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(pm,(e=>{this.onProviderMessageEvent(e)}))}async onRelayMessage(e){const{topic:t,message:s,attestation:n,transportType:r}=e,{publicKey:i}=this.client.auth.authKeys.keys.includes(qE)?this.client.auth.authKeys.get(qE):{responseTopic:void 0,publicKey:void 0};try{const e=await this.client.core.crypto.decode(t,s,{receiverPublicKey:i,encoding:r===Im.link_mode?Pf:kf});T(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:n,transportType:r,encryptedId:qf(s)})):N(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:r}),this.client.core.history.delete(t,e.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(e)}`),await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:r})),await this.client.core.relayer.messages.ack(t,s)}catch(e){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${s}`),this.client.logger.error(e)}}registerExpirerEvents(){this.client.core.expirer.on(Hm,(async e=>{const{topic:t,id:s}=Il(e.target);return s&&this.client.pendingRequest.keys.includes(s)?await this.deletePendingSessionRequest(s,Yc("EXPIRED"),!0):s&&this.client.auth.requests.keys.includes(s)?await this.deletePendingAuthRequest(s,Yc("EXPIRED"),!0):void(t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s})))}))}registerPairingEvents(){this.client.core.pairing.events.on(Um,(e=>this.onPairingCreated(e))),this.client.core.pairing.events.on(Dm,(e=>{this.addToRecentlyDeleted(e.topic,"pairing")}))}isValidPairingTopic(e){if(!xg(e,!1)){const{message:t}=Yc("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=Yc("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(_l(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=Yc("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!xg(e,!1)){const{message:t}=Yc("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=Yc("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(_l(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=Yc("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=Yc("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else{if(!this.client.core.pairing.pairings.keys.includes(e)){if(xg(e,!1)){const{message:t}=Yc("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=Yc("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if(!function(e){return"number"==typeof e}(e)){const{message:t}=Yc("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=Yc("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(_l(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=Yc("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}validateRequestExpiry(e){if(e&&!function(e,t){return Rg(e,!1)&&e<=t.max&&e>=t.min}(e,DE)){const{message:t}=Yc("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${DE.min} and ${DE.max}`);throw new Error(t)}}}class eC extends Jv{constructor(e,t){super(e,t,"proposal",TE),this.core=e,this.logger=t}}class tC extends Jv{constructor(e,t){super(e,t,"session",TE),this.core=e,this.logger=t}}class sC extends Jv{constructor(e,t){super(e,t,"request",TE,(e=>e.id)),this.core=e,this.logger=t}}class nC extends Jv{constructor(e,t){super(e,t,"authKeys",FE,(()=>qE)),this.core=e,this.logger=t}}class rC extends Jv{constructor(e,t){super(e,t,"pairingTopics",FE),this.core=e,this.logger=t}}class iC extends Jv{constructor(e,t){super(e,t,"requests",FE,(e=>e.id)),this.core=e,this.logger=t}}var oC=Object.defineProperty,aC=(e,t,s)=>((e,t,s)=>t in e?oC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class cC{constructor(e,t){this.core=e,this.logger=t,aC(this,"authKeys"),aC(this,"pairingTopics"),aC(this,"requests"),this.authKeys=new nC(this.core,this.logger),this.pairingTopics=new rC(this.core,this.logger),this.requests=new iC(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var lC=Object.defineProperty,dC=(e,t,s)=>((e,t,s)=>t in e?lC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class hC extends qr{constructor(e){super(e),dC(this,"protocol","wc"),dC(this,"version",2),dC(this,"name",kE),dC(this,"metadata"),dC(this,"core"),dC(this,"logger"),dC(this,"events",new t),dC(this,"engine"),dC(this,"session"),dC(this,"proposal"),dC(this,"pendingRequest"),dC(this,"auth"),dC(this,"signConfig"),dC(this,"on",((e,t)=>this.events.on(e,t))),dC(this,"once",((e,t)=>this.events.once(e,t))),dC(this,"off",((e,t)=>this.events.off(e,t))),dC(this,"removeListener",((e,t)=>this.events.removeListener(e,t))),dC(this,"removeAllListeners",(e=>this.events.removeAllListeners(e))),dC(this,"connect",(async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"pair",(async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"approve",(async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"reject",(async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"update",(async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"extend",(async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"request",(async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"respond",(async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"ping",(async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"emit",(async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"disconnect",(async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"find",(e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"getPendingSessionRequests",(()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}})),dC(this,"authenticate",(async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"formatAuthMessage",(e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"approveSessionAuthenticate",(async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}})),dC(this,"rejectSessionAuthenticate",(async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}})),this.name=e?.name||kE,this.metadata=gl(e?.metadata),this.signConfig=e?.signConfig;const s=em({logger:e?.logger||PE,name:this.name});this.logger=s,this.core=e?.core||new _E(e),this.session=new tC(this.core,this.logger),this.proposal=new eC(this.core,this.logger),this.pendingRequest=new sC(this.core,this.logger),this.engine=new QE(this),this.auth=new cC(this.core,this.logger)}static async init(e){const t=new hC(e);return await t.initialize(),t}get context(){return Cr(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const uC=hC;var pC=Object.defineProperty,fC=Object.defineProperties,gC=Object.getOwnPropertyDescriptors,mC=Object.getOwnPropertySymbols,yC=Object.prototype.hasOwnProperty,wC=Object.prototype.propertyIsEnumerable,bC=(e,t,s)=>t in e?pC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,vC=(e,t)=>{for(var s in t||(t={}))yC.call(t,s)&&bC(e,s,t[s]);if(mC)for(var s of mC(t))wC.call(t,s)&&bC(e,s,t[s]);return e},EC=(e,t)=>fC(e,gC(t));const CC={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"};class NC{constructor(e,s=!1){if(this.url=e,this.disableProviderPing=s,this.events=new t,this.isAvailable=!1,this.registering=!1,!R(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=s}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const t=i(e),s=await(await D(this.url,EC(vC({},CC),{body:t}))).json();this.onPayload({data:s})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!R(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return t(new Error("HTTP connection is missing or invalid"));e()}))}))}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=i({id:1,jsonrpc:"2.0",method:"test",params:[]});await D(e,EC(vC({},CC),{body:t}))}this.onOpen()}catch(e){const t=this.parseError(e);throw this.events.emit("register_error",t),this.onClose(),t}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const t="string"==typeof e.data?r(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const s=this.parseError(t),n=s.message||s.toString(),r=_(e,n);this.events.emit("payload",r)}parseError(e,t=this.url){return O(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}}function AC(e){return null!=e&&"function"!=typeof e&&function(e){return Number.isSafeInteger(e)&&e>=0}(e.length)}function IC(e){return"__proto__"===e}function SC(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function _C(e){return Object.getOwnPropertySymbols(e).filter((t=>Object.prototype.propertyIsEnumerable.call(e,t)))}function OC(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const TC="[object RegExp]",kC="[object String]",PC="[object Number]",xC="[object Boolean]",RC="[object Arguments]",UC="[object Symbol]",LC="[object Date]",DC="[object Map]",MC="[object Set]",BC="[object Array]",jC="[object ArrayBuffer]",$C="[object Object]",FC="[object DataView]",qC="[object Uint8Array]",WC="[object Uint8ClampedArray]",HC="[object Uint16Array]",zC="[object Uint32Array]",VC="[object Int8Array]",KC="[object Int16Array]",GC="[object Int32Array]",JC="[object Float32Array]",YC="[object Float64Array]";function XC(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function ZC(e,t,s,n=new Map,r=void 0){const i=r?.(e,t,s,n);if(void 0!==i)return i;if(SC(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){const t=new Array(e.length);n.set(e,t);for(let i=0;i<e.length;i++)t[i]=ZC(e[i],i,s,n,r);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){const t=new Map;n.set(e,t);for(const[i,o]of e)t.set(i,ZC(o,i,s,n,r));return t}if(e instanceof Set){const t=new Set;n.set(e,t);for(const i of e)t.add(ZC(i,void 0,s,n,r));return t}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(XC(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);n.set(e,t);for(let i=0;i<e.length;i++)t[i]=ZC(e[i],i,s,n,r);return t}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return n.set(e,t),QC(t,e,s,n,r),t}if(typeof File<"u"&&e instanceof File){const t=new File([e],e.name,{type:e.type});return n.set(e,t),QC(t,e,s,n,r),t}if(typeof Blob<"u"&&e instanceof Blob){const t=new Blob([e],{type:e.type});return n.set(e,t),QC(t,e,s,n,r),t}if(e instanceof Error){const t=new e.constructor;return n.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,QC(t,e,s,n,r),t}if(e instanceof Boolean){const t=new Boolean(e.valueOf());return n.set(e,t),QC(t,e,s,n,r),t}if(e instanceof Number){const t=new Number(e.valueOf());return n.set(e,t),QC(t,e,s,n,r),t}if(e instanceof String){const t=new String(e.valueOf());return n.set(e,t),QC(t,e,s,n,r),t}if("object"==typeof e&&function(e){switch(OC(e)){case RC:case BC:case jC:case FC:case xC:case LC:case JC:case YC:case VC:case KC:case GC:case DC:case PC:case $C:case TC:case MC:case kC:case UC:case qC:case WC:case HC:case zC:return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return n.set(e,t),QC(t,e,s,n,r),t}return e}function QC(e,t,s=e,n,r){const i=[...Object.keys(t),..._C(t)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=ZC(t[a],a,s,n,r))}}function eN(e,t){return function(e,t){return ZC(e,void 0,e,new Map,t)}(e,((s,n,r,i)=>{const o=t?.(s,n,r,i);if(void 0!==o)return o;if("object"==typeof e){if(OC(e)===$C&&"function"!=typeof e.constructor){const t={};return i.set(e,t),QC(t,e,r,i),t}switch(Object.prototype.toString.call(e)){case PC:case kC:case xC:{const t=new e.constructor(e?.valueOf());return QC(t,e),t}case RC:{const t={};return QC(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}}))}function tN(e){return eN(e)}function sN(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===OC(e)}function nN(e){return"object"==typeof e&&null!==e}function rN(e){return nN(e)&&AC(e)}function iN(){}function oN(e){return XC(e)}function aN(e){if("object"!=typeof e||null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;if("[object Object]"!==Object.prototype.toString.call(e)){const t=e[Symbol.toStringTag];return!(null==t||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable)&&e.toString()===`[object ${t}]`}let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function cN(e,t,s,n){if(SC(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(n.has(t))return function(e){if(SC(e))return e;if(Array.isArray(e)||XC(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e);if(null==t)return Object.assign(Object.create(t),e);const s=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new s(e);if(e instanceof RegExp){const t=new s(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new s(e.buffer.slice(0));if(e instanceof Error){let t;return t=e instanceof AggregateError?new s(e.errors,e.message,{cause:e.cause}):new s(e.message,{cause:e.cause}),t.stack=e.stack,Object.assign(t,e),t}if(typeof File<"u"&&e instanceof File)return new s([e],e.name,{type:e.type,lastModified:e.lastModified});if("object"==typeof e){const s=Object.create(t);return Object.assign(s,e)}return e}(n.get(t));if(n.set(t,e),Array.isArray(t)){t=t.slice();for(let e=0;e<t.length;e++)t[e]=t[e]??void 0}const r=[...Object.keys(t),..._C(t)];for(let i=0;i<r.length;i++){const o=r[i];if(IC(o))continue;let a=t[o],c=e[o];if(sN(a)&&(a={...a}),sN(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=tN(a)),Array.isArray(a))if(Array.isArray(c)){const e=[],t=Reflect.ownKeys(c);for(let s=0;s<t.length;s++){const n=t[s];e[n]=c[n]}c=e}else if(rN(c)){const e=[];for(let t=0;t<c.length;t++)e[t]=c[t];c=e}else c=[];const l=s(c,a,o,e,t,n);void 0!==l?e[o]=l:Array.isArray(a)||nN(c)&&nN(a)&&(aN(c)||aN(a)||oN(c)||oN(a))?e[o]=cN(c,a,s,n):null==c&&aN(a)?e[o]=cN({},a,s,n):null==c&&oN(a)?e[o]=tN(a):(void 0===c||void 0!==a)&&(e[o]=a)}return e}function lN(e,...t){return function(e,...t){const s=t.slice(0,-1),n=t[t.length-1];let r=e;for(let e=0;e<s.length;e++)r=cN(r,s[e],n,new Map);return r}(e,...t,iN)}const dN="error",hN="universal_provider",uN=`wc@2:${hN}:`,pN="https://rpc.walletconnect.org/v1/",fN="generic",gN=`${pN}bundler`,mN="call_status",yN="default_chain_changed";var wN=Object.defineProperty,bN=Object.defineProperties,vN=Object.getOwnPropertyDescriptors,EN=Object.getOwnPropertySymbols,CN=Object.prototype.hasOwnProperty,NN=Object.prototype.propertyIsEnumerable,AN=(e,t,s)=>t in e?wN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,IN=(e,t)=>{for(var s in t||(t={}))CN.call(t,s)&&AN(e,s,t[s]);if(EN)for(var s of EN(t))NN.call(t,s)&&AN(e,s,t[s]);return e},SN=(e,t)=>bN(e,vN(t));function _N(e,t,s){var n;const r=Vc(e);return(null==(n=t.rpcMap)?void 0:n[r.reference])||`${pN}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function ON(e){return e.map((e=>`${e.split(":")[0]}:${e.split(":")[1]}`))}function TN(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>{var s,n;return(null==(s=t?.chains)?void 0:s.length)&&(null==(n=t?.chains)?void 0:n.length)>0})))}function kN(e={},t={}){return lN(TN(PN(e)),TN(PN(t)))}function PN(e){var t,s,n,r,i;const o={};if(!kg(e))return o;for(const[a,c]of Object.entries(e)){const e=Ig(a)?[a]:c.chains,l=c.methods||[],d=c.events||[],h=c.rpcMap||{},u=Sg(a);o[u]=SN(IN(IN({},o[u]),c),{chains:Tl(e,null==(t=o[u])?void 0:t.chains),methods:Tl(l,null==(s=o[u])?void 0:s.methods),events:Tl(d,null==(n=o[u])?void 0:n.events)}),(kg(h)||kg((null==(r=o[u])?void 0:r.rpcMap)||{}))&&(o[u].rpcMap=IN(IN({},h),null==(i=o[u])?void 0:i.rpcMap))}return o}function xN(e){return e.includes(":")?e.split(":")[2]:e}function RN(e){const t={};for(const[s,n]of Object.entries(e)){const e=n.methods||[],r=n.events||[],i=n.accounts||[],o=Ig(s)?[s]:n.chains?n.chains:ON(n.accounts);t[s]={chains:o,methods:e,events:r,accounts:i}}return t}function UN(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}const LN={},DN=e=>LN[e],MN=(e,t)=>{LN[e]=t};var BN=Object.defineProperty,jN=Object.getOwnPropertySymbols,$N=Object.prototype.hasOwnProperty,FN=Object.prototype.propertyIsEnumerable,qN=(e,t,s)=>t in e?BN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,WN=(e,t)=>{for(var s in t||(t={}))$N.call(t,s)&&qN(e,s,t[s]);if(jN)for(var s of jN(t))FN.call(t,s)&&qN(e,s,t[s]);return e};const HN="eip155",zN=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],VN=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,KN=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,GN=e=>Object.keys(e).filter((e=>zN.includes(e))).reduce(((t,s)=>(t[s]=JN(e[s]),t)),{}),JN=e=>"string"==typeof e&&function(e){try{const t=JSON.parse(e);return"object"==typeof t&&null!==t&&!Array.isArray(t)}catch{return!1}}(e)?JSON.parse(e):e;var YN=Object.defineProperty,XN=(e,t,s)=>((e,t,s)=>t in e?YN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let ZN;class QN{constructor(e){XN(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,t){return await this.storage.setItem(e,t)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return ZN||(ZN=new QN(e)),ZN}}var eA=Object.defineProperty,tA=Object.defineProperties,sA=Object.getOwnPropertyDescriptors,nA=Object.getOwnPropertySymbols,rA=Object.prototype.hasOwnProperty,iA=Object.prototype.propertyIsEnumerable,oA=(e,t,s)=>t in e?eA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;async function aA(e,t){const s=Vc(e.result.capabilities.caip345.caip2),n=e.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(n.map((e=>async function(e,t,s){return await s(parseInt(e)).request(v("eth_getTransactionReceipt",[t]))}(s.reference,e,t)))),i=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)).filter((e=>e));r.filter((e=>"rejected"===e.status)).forEach((e=>console.warn("Failed to fetch transaction receipt:",e.reason)));const o=!i.length||i.some((e=>!e)),a=i.every((e=>"0x1"===e?.status)),c=i.every((e=>"0x0"===e?.status)),l=i.some((e=>"0x0"===e?.status));let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:i,status:d}}async function cA({sendCalls:e,storage:t}){const s=await t.getItem(mN);await t.setItem(mN,((e,t)=>tA(e,sA(t)))(((e,t)=>{for(var s in t||(t={}))rA.call(t,s)&&oA(e,s,t[s]);if(nA)for(var s of nA(t))iA.call(t,s)&&oA(e,s,t[s]);return e})({},s),{[e.result.id]:{request:e.request,result:e.result,expiry:Sl(86400)}}))}async function lA({resultId:e,storage:t}){const s=await t.getItem(mN),n=s?.[e];if(n&&!_l(n.expiry))return n;await async function({resultId:e,storage:t}){const s=await t.getItem(mN);if(s){delete s[e],await t.setItem(mN,s);for(const e in s)_l(s[e].expiry)&&delete s[e];await t.setItem(mN,s)}}({resultId:e,storage:t})}var dA=Object.defineProperty,hA=Object.defineProperties,uA=Object.getOwnPropertyDescriptors,pA=Object.getOwnPropertySymbols,fA=Object.prototype.hasOwnProperty,gA=Object.prototype.propertyIsEnumerable,mA=(e,t,s)=>t in e?dA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,yA=(e,t)=>{for(var s in t||(t={}))fA.call(t,s)&&mA(e,s,t[s]);if(pA)for(var s of pA(t))gA.call(t,s)&&mA(e,s,t[s]);return e},wA=(e,t)=>hA(e,uA(t)),bA=(e,t,s)=>mA(e,"symbol"!=typeof t?t+"":t,s);class vA{constructor(e){bA(this,"name","eip155"),bA(this,"client"),bA(this,"chainId"),bA(this,"namespace"),bA(this,"httpProviders"),bA(this,"events"),bA(this,"storage"),this.namespace=e.namespace,this.events=DN("events"),this.client=DN("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=QN.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t);const s=this.chainId;this.chainId=parseInt(e),this.events.emit(yN,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${s}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const s=t||_N(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new tm(new NC(s,DN("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach((t=>{var s;const n=parseInt(function(e){return e.includes(":")?e.split(":")[1]:e}(t));e[n]=this.createHttpProvider(n,null==(s=this.namespace.rpcMap)?void 0:s[t])})),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter((e=>e.split(":")[1]===this.chainId.toString())).map((e=>e.split(":")[2])))]:[]}getHttpProvider(e){const t=e||this.chainId;return this.httpProviders[t]||(this.httpProviders=wA(yA({},this.httpProviders),{[t]:this.createHttpProvider(t)}),this.httpProviders[t])}async handleSwitchChain(e){var t,s;let n=e.request.params?null==(t=e.request.params[0])?void 0:t.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const r=parseInt(n,16);if(this.isChainApproved(r))this.setDefaultChain(`${r}`);else{if(!this.namespace.methods.includes("wallet_switchEthereumChain"))throw new Error(`Failed to switch to chain 'eip155:${r}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:null==(s=this.namespace.chains)?void 0:s[0]}),this.setDefaultChain(`${r}`)}return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,s,n,r,i;const o=null==(s=null==(t=e.request)?void 0:t.params)?void 0:s[0],a=(null==(r=null==(n=e.request)?void 0:n.params)?void 0:r[1])||[];if(!o)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const c=this.client.session.get(e.topic),l=(null==(i=c?.sessionProperties)?void 0:i.capabilities)||{},d=`${o}${a.length>0?a.join(","):`0x${this.chainId.toString(16)}`}`,h=l?.[d];if(h)return h;let u;try{u=((e,t,s)=>{const{sessionProperties:n={},scopedProperties:r={}}=e,i={};if(!kg(r)&&!kg(n))return;const o=GN(n);for(const e of s){const s=VN(e);if(!s)continue;i[KN(s)]=o;const n=r?.[`${HN}:${s}`];if(n){const e=n?.[`${HN}:${s}:${t}`];i[KN(s)]=WN(WN({},i[KN(s)]),GN(e||n))}}for(const[e,t]of Object.entries(i))0===Object.keys(t).length&&delete i[e];return Object.keys(i).length>0?i:void 0})(c,o,a)}catch(e){console.warn("Failed to extract capabilities from session",e)}if(u)return u;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:wA(yA({},c.sessionProperties||{}),{capabilities:wA(yA({},l||{}),{[d]:p})})})}catch(e){console.warn("Failed to update session with capabilities",e)}return p}async getCallStatus(e){var t,s,n;const r=this.client.session.get(e.topic),i=null==(t=r.sessionProperties)?void 0:t.bundler_name;if(i){const t=this.getBundlerUrl(e.chainId,i);try{return await this.getUserOperationReceipt(t,e)}catch(e){console.warn("Failed to fetch call status from bundler",e,t)}}const o=null==(s=r.sessionProperties)?void 0:s.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(e){console.warn("Failed to fetch call status from custom bundler",e,o)}const a=await lA({resultId:null==(n=e.request.params)?void 0:n[0],storage:this.storage});if(a)try{return await aA(a,this.getHttpProvider.bind(this))}catch(e){console.warn("Failed to fetch call status from stored send calls",e,a)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var s;const n=new URL(e),r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v("eth_getUserOperationReceipt",[null==(s=t.request.params)?void 0:s[0]]))});if(!r.ok)throw new Error(`Failed to fetch user operation receipt - ${r.status}`);return await r.json()}getBundlerUrl(e,t){return`${gN}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}async sendCalls(e){var t,s,n;const r=await this.client.request(e),i=null==(t=e.request.params)?void 0:t[0],o=r?.id,a=r?.capabilities||{},c=null==(s=a?.caip345)?void 0:s.caip2,l=null==(n=a?.caip345)?void 0:n.transactionHashes;return!o||!c||!(null!=l&&l.length)||await cA({sendCalls:{request:i,result:r},storage:this.storage}),r}}var EA=Object.defineProperty,CA=(e,t,s)=>((e,t,s)=>t in e?EA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class NA{constructor(e){CA(this,"name",fN),CA(this,"client"),CA(this,"httpProviders"),CA(this,"events"),CA(this,"namespace"),CA(this,"chainId"),this.namespace=e.namespace,this.events=DN("events"),this.client=DN("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t);const s=this.chainId;this.chainId=e,this.events.emit(yN,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${s}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return Vc(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter((e=>e.split(":")[1]===this.chainId.toString())).map((e=>e.split(":")[2])))]:[]}createHttpProviders(){var e,t;const s={};return null==(t=null==(e=this.namespace)?void 0:e.accounts)||t.forEach((e=>{var t,n;const r=Vc(e),i=null==(n=null==(t=this.namespace)?void 0:t.rpcMap)?void 0:n[`${r.namespace}:${r.reference}`];s[r.reference]=this.createHttpProvider(e,i)})),s}getHttpProvider(e){const t=Vc(e).reference,s=this.httpProviders[t];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||_N(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new tm(new NC(s,DN("disableProviderPing")))}}var AA=Object.defineProperty,IA=Object.defineProperties,SA=Object.getOwnPropertyDescriptors,_A=Object.getOwnPropertySymbols,OA=Object.prototype.hasOwnProperty,TA=Object.prototype.propertyIsEnumerable,kA=(e,t,s)=>t in e?AA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,PA=(e,t)=>{for(var s in t||(t={}))OA.call(t,s)&&kA(e,s,t[s]);if(_A)for(var s of _A(t))TA.call(t,s)&&kA(e,s,t[s]);return e},xA=(e,t)=>IA(e,SA(t)),RA=(e,t,s)=>kA(e,"symbol"!=typeof t?t+"":t,s);class UA{constructor(t){var s,n;RA(this,"client"),RA(this,"namespaces"),RA(this,"optionalNamespaces"),RA(this,"sessionProperties"),RA(this,"scopedProperties"),RA(this,"events",new e),RA(this,"rpcProviders",{}),RA(this,"session"),RA(this,"providerOpts"),RA(this,"logger"),RA(this,"uri"),RA(this,"disableProviderPing",!1),RA(this,"connectParams"),this.providerOpts=t,this.logger=em({logger:null!=(s=t.logger)?s:dN,name:null!=(n=this.providerOpts.name)?n:hN}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(e){const t=new UA(e);return await t.initialize(),t}async request(e,t,s){const[n,r]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:PA({},e),chainId:`${n}:${r}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,n){const r=(new Date).getTime();this.request(e,s,n).then((e=>t(null,k(r,e)))).catch((e=>t(e,void 0)))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:null==(e=this.session)?void 0:e.topic,reason:Xc("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:n}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const r=await n();if(this.session=r.session,this.session){const e=RN(this.session.namespaces);this.namespaces=kN(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return r}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){var t,s;const{uri:n,approval:r}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:null==(t=this.connectParams)?void 0:t.authentication,walletPay:null==(s=this.connectParams)?void 0:s.walletPay});n&&(this.uri=n,this.events.emit("display_uri",n));const i=await r();this.session=i;const o=RN(i.namespaces);return this.namespaces=kN(this.namespaces,o),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[s,n]=this.validateChain(e),r=this.getProvider(s);r?r.setDefaultChain(n,t):this.session&&this.logger.warn(`Provider for namespace '${s}' not found in setDefaultChain`)}catch(e){if(!/Please call connect/.test(e.message))throw e}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(!Tg(t))return;for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}catch(e){this.logger.warn(e,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await uC.init({core:this.providerOpts.core,logger:this.providerOpts.logger||dN,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(s){throw this.logger.error(s,"Failed to get session"),new Error(`The provided session: ${null==(t=null==(e=this.providerOpts)?void 0:e.session)?void 0:t.topic} doesn't exist in the Sign client`)}else{const e=this.client.session.getAll();this.session=e[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map((e=>Sg(e))))];MN("client",this.client),MN("events",this.events),MN("disableProviderPing",this.disableProviderPing),e.forEach((e=>{if(!this.session)return;const t=function(e,t){const s=Object.keys(t.namespaces).filter((t=>t.includes(e)));if(!s.length)return[];const n=[];return s.forEach((e=>{const s=t.namespaces[e].accounts;n.push(...s)})),n}(e,this.session);if(0===t?.length)return;const s=ON(t),n=kN(this.namespaces,this.optionalNamespaces),r=xA(PA({},n[e]),{accounts:t,chains:s});if("eip155"===e)this.rpcProviders[e]=new vA({namespace:r});else this.rpcProviders[e]=new NA({namespace:r})}))}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",(e=>{var t;const{topic:s}=e;s===(null==(t=this.session)?void 0:t.topic)&&this.events.emit("session_ping",e)})),this.client.on("session_event",(e=>{var t;const{params:s,topic:n}=e;if(n!==(null==(t=this.session)?void 0:t.topic))return;const{event:r}=s;if("accountsChanged"===r.name){const e=r.data;e&&Tg(e)&&this.events.emit("accountsChanged",e.map(xN))}else if("chainChanged"===r.name){const e=s.chainId,t=s.event.data,n=Sg(e),r=UN(e)!==UN(t)?`${n}:${UN(t)}`:e;this.onChainChanged({currentCaipChainId:r})}else this.events.emit(r.name,r.data);this.events.emit("session_event",e)})),this.client.on("session_update",(({topic:e,params:t})=>{var s,n;if(e!==(null==(s=this.session)?void 0:s.topic))return;const{namespaces:r}=t,i=null==(n=this.client)?void 0:n.session.get(e);this.session=xA(PA({},i),{namespaces:r}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})})),this.client.on("session_delete",(async e=>{var t;e.topic===(null==(t=this.session)?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",xA(PA({},Xc("USER_DISCONNECTED")),{data:e.topic})))})),this.on(yN,(e=>{this.onChainChanged(xA(PA({},e),{internal:!0}))}))}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[fN]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach((e=>{var t;this.getProvider(e).updateNamespace(null==(t=this.session)?void 0:t.namespaces[e])}))}setNamespaces(e){const{namespaces:t={},optionalNamespaces:s={},sessionProperties:n,scopedProperties:r}=e;this.optionalNamespaces=kN(t,s),this.sessionProperties=n,this.scopedProperties=r}validateChain(e){const[t,s]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map((e=>Sg(e))).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const n=Sg(Object.keys(this.namespaces)[0]);return[n,this.rpcProviders[n].getDefaultChain()]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:t,internal:s=!1}){if(!this.namespaces)return;const[n,r]=this.validateChain(e);if(r){if(this.updateNamespaceChain(n,r),s)this.events.emit("chainChanged",r),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:t});else{const e=this.getProvider(n);e?e.setDefaultChain(r):this.session&&this.logger.warn(`Provider for namespace '${n}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:t,previousCaipChainId:s}){var n,r;try{if(s===t)return;const i=null==(r=null==(n=this.session)?void 0:n.namespaces[e])?void 0:r.accounts;if(!i)return;const o=i.filter((e=>e.includes(`${t}:`))).map(xN);if(!Tg(o))return;this.events.emit("accountsChanged",o)}catch(e){this.logger.warn(e,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,n={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=n}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var s;const n=(null==(s=this.session)?void 0:s.topic)||"";await this.client.core.storage.setItem(`${uN}/${e}${n}`,t)}async getFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${uN}/${e}${s}`)}async deleteFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${uN}/${e}${s}`)}async cleanupStorage(){var e;try{if((null==(e=this.client)?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const e of t)e.startsWith(uN)&&await this.client.core.storage.removeItem(e)}catch(e){this.logger.warn(e,"Failed to cleanup storage")}}}const LA=2147483648,DA={convertEVMChainIdToCoinType(e){if(e>=LA)throw new Error("Invalid chainId");return(LA|e)>>>0}},MA=xe({suggestions:[],loading:!1}),BA={state:MA,subscribe:e=>Re(MA,(()=>e(MA))),subscribeKey:(e,t)=>De(MA,e,t),async resolveName(e){try{return await Mt.lookupEnsName(e)}catch(e){const t=e;throw new Error(t?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(e){try{return await Mt.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{MA.loading=!0,MA.suggestions=[];const t=await Mt.getEnsNameSuggestions(e);return MA.suggestions=t.suggestions||[],MA.suggestions}catch(e){const t=jA.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{MA.loading=!1}},async getNamesForAddress(e){try{if(!Qs.state.activeCaipNetwork)return[];const t=We.getEnsFromCacheForAddress(e);if(t)return t;const s=await Mt.reverseLookupEnsName({address:e});return We.updateEnsCache({address:e,ens:s,timestamp:Date.now()}),s}catch(e){const t=jA.parseEnsApiError(e,"Error fetching names for address");throw new Error(t)}},async registerName(e){const t=Qs.state.activeCaipNetwork,s=Qs.getAccountData(t?.chainNamespace)?.address,n=bs.getAuthConnector();if(!t)throw new Error("Network not found");if(!s||!n)throw new Error("Address or auth connector not found");MA.loading=!0;try{const n=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});hs.pushTransactionStack({onCancel(){hs.replace("RegisterAccountName")}});const r=await Us.signMessage(n);MA.loading=!1;const i=t.id;if(!i)throw new Error("Network not found");const o=DA.convertEVMChainIdToCoinType(Number(i));await Mt.registerEnsName({coinType:o,address:s,signature:r,message:n}),Qs.setAccountProp("profileName",e,t.chainNamespace),We.updateEnsCache({address:s,ens:[{name:e,registered_at:(new Date).toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),hs.replace("RegisterAccountNameSuccess")}catch(t){const s=jA.parseEnsApiError(t,`Error registering name ${e}`);throw hs.replace("RegisterAccountName"),new Error(s)}finally{MA.loading=!1}},validateName:e=>/^[a-zA-Z0-9-]{4,}$/u.test(e),parseEnsApiError(e,t){const s=e;return s?.reasons?.[0]?.description||t}},jA=Ht(BA);function $A(e){try{return new URL(e)}catch{return null}}function FA(e,t){if(t.includes("://")){const s=$A(t);return!!s&&s.origin===e}const{host:s,port:n}=function(e){const t=e.split("/"),s=t.length>0&&void 0!==t[0]?t[0]:"",n=s.lastIndexOf(":");return-1===n?{host:s}:{host:s.slice(0,n),port:s.slice(n+1)}}(t),r=e.indexOf("://");if(-1!==r){const t=r+3;let i=e.indexOf("/",t);-1===i&&(i=e.length);const o=e.slice(t,i);if(void 0!==n)return`${s}:${n}`===o;return s===o.split(":")[0]}const i=$A(e);return!!i&&(void 0!==n?s===i.hostname&&n===(i.port||void 0):s===i.hostname)}function qA(e,t,s){let n,r=s;const i=r.indexOf("://");-1!==i&&(n=r.slice(0,i),r=r.slice(i+3));const o=r.indexOf("/");-1!==o&&(r=r.slice(0,o));let a,c=r;const l=c.lastIndexOf(":");-1!==l&&(a=c.slice(l+1),c=c.slice(0,l));const d=c.split(".");for(const e of d)if(e.includes("*")&&"*"!==e)return!1;const h=e.protocol.replace(/:$/u,"");if(n&&n!==h)return!1;if(void 0!==a&&"*"!==a&&a!==e.port)return!1;const u=function(e){const t=e.indexOf("://");if(-1===t)return null;const s=e.slice(0,t),n=t+3;let r=e.indexOf("/",n);-1===r&&(r=e.length);const i=e.slice(n,r),o=i.lastIndexOf(":");return-1===o?{scheme:s,host:i}:{scheme:s,host:i.slice(0,o),port:i.slice(o+1)}}(t),p=(u?u.host:e.hostname).split(".");if(d.length!==p.length)return!1;for(let e=d.length-1;e>=0;e-=1){const t=d[e],s=p[e];if("*"!==t&&t!==s)return!1}return!0}const WA={ton:["ton_sendMessage","ton_signData"],solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"],tron:["tron_signMessage","tron_signTransaction"]},HA={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace:e=>WA[e]||[],createDefaultNamespace(e){return{methods:this.getMethodsByChainNamespace(e),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(e,t){if(!t)return{...e};const s={...e},n=new Set;if(t.methods&&Object.keys(t.methods).forEach((e=>n.add(e))),t.chains&&Object.keys(t.chains).forEach((e=>n.add(e))),t.events&&Object.keys(t.events).forEach((e=>n.add(e))),t.rpcMap&&Object.keys(t.rpcMap).forEach((e=>{const[t]=e.split(":");t&&n.add(t)})),n.forEach((e=>{s[e]||(s[e]=this.createDefaultNamespace(e))})),t.methods&&Object.entries(t.methods).forEach((([e,t])=>{s[e]&&(s[e].methods=t)})),t.chains&&Object.entries(t.chains).forEach((([e,t])=>{s[e]&&(s[e].chains=t)})),t.events&&Object.entries(t.events).forEach((([e,t])=>{s[e]&&(s[e].events=t)})),t.rpcMap){const e=new Set;Object.entries(t.rpcMap).forEach((([t,n])=>{const[r,i]=t.split(":");r&&i&&s[r]&&(s[r].rpcMap||(s[r].rpcMap={}),e.has(r)||(s[r].rpcMap={},e.add(r)),s[r].rpcMap[i]=n)}))}return s},createNamespaces(e,t){const s=e.reduce(((e,t)=>{const{id:s,chainNamespace:n,rpcUrls:r}=t,i=r.default.http[0];e[n]||(e[n]=this.createDefaultNamespace(n));const o=`${n}:${s}`,a=e[n];switch(a.chains.push(o),o){case"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":a.chains.push("solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ");break;case"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":a.chains.push("solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K")}return a?.rpcMap&&i&&(a.rpcMap[s]=i),e}),{});return this.applyNamespaceOverrides(s,t)},resolveReownName:async e=>{const t=await jA.resolveName(e),s=t?.addresses?Object.values(t.addresses):[];return s[0]?.address||!1},getChainsFromNamespaces:(e={})=>Object.values(e).flatMap((e=>{const t=e.chains||[],s=e.accounts.map((e=>{const[t,s]=e.split(":");return`${t}:${s}`}));return Array.from(new Set([...t,...s]))})),isSessionEventData:e=>"object"==typeof e&&null!==e&&"id"in e&&"topic"in e&&"params"in e&&"object"==typeof e.params&&null!==e.params&&"chainId"in e.params&&"event"in e.params&&"object"==typeof e.params.event&&null!==e.params.event,isUserRejectedRequestError(e){try{if("object"==typeof e&&null!==e){const t=e,s="number"==typeof t.code,n=s&&t.code===HA.RPC_ERROR_CODE.USER_REJECTED_METHODS,r=s&&t.code===HA.RPC_ERROR_CODE.USER_REJECTED;return n||r}return!1}catch{return!1}},isOriginAllowed(e,t,s){const n=[...t,...s];if(0===t.length)return!0;const r=$A(e);if(!r)return n.some((t=>!t.includes("*")&&t===e));if("localhost"===r.hostname||"127.0.0.1"===r.hostname)return!0;for(const t of n)if(t.includes("*")){if(qA(r,e,t))return!0}else if(FA(e,t))return!0;return!1},listenWcProvider({universalProvider:e,namespace:t,onConnect:s,onDisconnect:n,onAccountsChanged:r,onChainChanged:i,onDisplayUri:o}){s&&e.on("connect",(()=>{const n=HA.getWalletConnectAccounts(e,t);s(n)})),n&&e.on("disconnect",(()=>{n()})),r&&e.on("accountsChanged",(s=>{try{const n=e.session?.namespaces?.[t]?.accounts||[],i=e.rpcProviders?.[t]?.getDefaultChain(),o=s.map((e=>{const s=n.find((s=>s.includes(`${t}:${i}:${e}`)));if(!s)return;const{chainId:r,chainNamespace:o}=oe.parseCaipAddress(s);return{address:e,chainId:r,chainNamespace:o}})).filter((e=>void 0!==e));o.length>0&&r(o)}catch(e){console.warn("Failed to parse accounts for namespace on accountsChanged event",t,s,e)}})),i&&e.on("chainChanged",(e=>{i(e)})),o&&e.on("display_uri",(e=>{o(e)}))},getWalletConnectAccounts(e,t){const s=new Set,n=e?.session?.namespaces?.[t]?.accounts?.map((e=>oe.parseCaipAddress(e))).filter((({address:e})=>!s.has(e.toLowerCase())&&(s.add(e.toLowerCase()),!0)));return n&&n.length>0?n:[]}},zA=[B.CONNECTOR_ID.AUTH,B.CONNECTOR_ID.WALLET_CONNECT];class VA{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=e=>Qs.getCaipNetworks(e),this.getConnectorId=e=>bs.getConnectorId(e),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:e,chainId:t}){const s=this.getCaipNetworks().filter((e=>e.chainNamespace===this.namespace)).find((e=>e.id.toString()===t?.toString()));e&&s&&this.addConnection({connectorId:B.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:s})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:B.CONNECTOR_ID.AUTH,type:"AUTH",name:B.CONNECTOR_NAMES.AUTH,provider:e,imageId:void 0,chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter((e=>!t.has(e.id)&&(t.add(e.id),!0))),this.emit("connectors",this.availableConnectors)}addConnection(...e){const t=new Set;this.availableConnections=[...e,...this.availableConnections].filter((e=>!t.has(e.connectorId.toLowerCase())&&(t.add(e.connectorId.toLowerCase()),!0))),this.emit("connections",this.availableConnections)}deleteConnection(e){this.availableConnections=this.availableConnections.filter((t=>t.connectorId.toLowerCase()!==e.toLowerCase())),this.emit("connections",this.availableConnections)}clearConnections(e=!1){this.availableConnections=[],e&&this.emit("connections",this.availableConnections)}setStatus(e,t){Qs.setAccountProp("status",e,t)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(t)}off(e,t){const s=this.eventListeners.get(e);s&&s.delete(t)}removeAllEventListeners(){this.eventListeners.forEach((e=>{e.clear()}))}emit(e,t){const s=this.eventListeners.get(e);s&&s.forEach((e=>e(t)))}async connectWalletConnect(e){try{const e=this.getWalletConnectConnector();return{clientId:(await e.connectWalletConnect()).clientId}}catch(e){if(HA.isUserRejectedRequestError(e))throw new le(e);throw e}}async switchNetwork(e){const{caipNetwork:t}=e,s=Hs.getProviderId(t.chainNamespace),n=Hs.getProvider(t.chainNamespace);if(!n)throw new Error("Provider not found");if("WALLET_CONNECT"!==s){if("AUTH"===s){const e=bs.getAuthConnector()?.provider;if(!e)throw new Error("Auth provider not found");const s=Ns(t.chainNamespace);await e.switchNetwork({chainId:t.caipNetworkId});const n=await e.getUser({chainId:t.caipNetworkId,preferredAccountType:s});this.emit("switchNetwork",n)}}else{n.setDefaultChain(t.caipNetworkId)}}getWalletConnectConnector(){const e=this.connectors.find((e=>"walletConnect"===e.id));if(!e)throw new Error("WalletConnectConnector not found");return e}onConnect(e,t){if(e.length>0){const{address:s,chainId:n}=He.getAccount(e[0]),r=this.getCaipNetworks().filter((e=>e.chainNamespace===this.namespace)).find((e=>e.id.toString()===n?.toString())),i=this.connectors.find((e=>e.id===t));s&&(this.emit("accountChanged",{address:s,chainId:n,connector:i}),this.addConnection({connectorId:t,accounts:e.map((e=>{const{address:t}=He.getAccount(e);return{address:t}})),caipNetwork:r}))}}onAccountsChanged(e,t,s=!0){if(e.length>0){const{address:s}=He.getAccount(e[0]),n=this.getConnection({connectorId:t,connections:this.connections,connectors:this.connectors});s&&this.getConnectorId(B.CHAIN.EVM)?.toLowerCase()===t.toLowerCase()&&this.emit("accountChanged",{address:s,chainId:n?.caipNetwork?.id,connector:n?.connector}),this.addConnection({connectorId:t,accounts:e.map((e=>{const{address:t}=He.getAccount(e);return{address:t}})),caipNetwork:n?.caipNetwork})}else s&&this.onDisconnect(t)}onDisconnect(e){this.removeProviderListeners(e),this.deleteConnection(e),this.getConnectorId(B.CHAIN.EVM)?.toLowerCase()===e.toLowerCase()&&this.emitFirstAvailableConnection(),0===this.connections.length&&this.emit("disconnect")}onChainChanged(e,t){const s="string"==typeof e&&e.startsWith("0x")?parseInt(e,16).toString():e.toString(),n=this.getConnection({connectorId:t,connections:this.connections,connectors:this.connectors}),r=this.getCaipNetworks().filter((e=>e.chainNamespace===this.namespace)).find((e=>e.id.toString()===s));n&&this.addConnection({connectorId:t,accounts:n.accounts,caipNetwork:r}),this.getConnectorId(B.CHAIN.EVM)?.toLowerCase()===t.toLowerCase()&&this.emit("switchNetwork",{chainId:s})}listenProviderEvents(e,t){if(zA.includes(e))return;const s=t=>this.onAccountsChanged(t,e),n=t=>this.onChainChanged(t,e),r=()=>this.onDisconnect(e);this.providerHandlers[e]||(t.on("disconnect",r),t.on("accountsChanged",s),t.on("chainChanged",n),this.providerHandlers[e]={provider:t,disconnect:r,accountsChanged:s,chainChanged:n})}removeProviderListeners(e){if(this.providerHandlers[e]){const{provider:t,disconnect:s,accountsChanged:n,chainChanged:r}=this.providerHandlers[e];t.removeListener("disconnect",s),t.removeListener("accountsChanged",n),t.removeListener("chainChanged",r),this.providerHandlers[e]=null}}emitFirstAvailableConnection(){const e=this.getConnection({connections:this.connections,connectors:this.connectors});if(e){const[t]=e.accounts;this.emit("accountChanged",{address:t?.address,chainId:e.caipNetwork?.id,connector:e.connector})}}getConnection({address:e,connectorId:t,connections:s,connectors:n}){if(t){const r=s.find((e=>e.connectorId.toLowerCase()===t.toLowerCase()));if(!r)return null;const i=n.find((e=>e.id.toLowerCase()===r.connectorId.toLowerCase())),o=e?r.accounts.find((t=>t.address.toLowerCase()===e.toLowerCase())):r.accounts[0];return{...r,account:o,connector:i}}const r=s.find((e=>e.accounts.length>0&&n.some((t=>t.id.toLowerCase()===e.connectorId.toLowerCase()))));if(r){const[e]=r.accounts,t=n.find((e=>e.id.toLowerCase()===r.connectorId.toLowerCase()));return{...r,account:e,connector:t}}return null}}let KA=null;const GA={getSIWX:()=>kt.state.siwx,async initializeIfEnabled(e=Qs.getActiveCaipAddress()){const t=kt.state.siwx;if(!t||!e)return;const[s,n,r]=e.split(":");if(Qs.checkIfSupportedNetwork(s,`${s}:${n}`))try{if(kt.state.remoteFeatures?.emailCapture){const e=Qs.getAccountData(s)?.user;return void await sn.open({view:"DataCapture",data:{email:e?.email??void 0}})}KA&&await KA;if((await t.getSessions(`${s}:${n}`,r)).length)return;await sn.open({view:"SIWXSignMessage"})}catch(e){console.error("SIWXUtil:initializeIfEnabled",e),ss.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(e)}),await(Us._getClient()?.disconnect().catch(console.error)),hs.reset("Connect"),Rt.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(e=Qs.getActiveCaipAddress()){if(!kt.state.siwx)return!0;if(!e)return!0;const{chainNamespace:t,chainId:s,address:n}=oe.parseCaipAddress(e),r=`${t}:${s}`;return(await GA.getSessions({address:n,caipNetworkId:r})).length>0},async requestSignMessage(){const e=kt.state.siwx,t=He.getPlainAddress(Qs.getActiveCaipAddress()),s=As();if(!e)throw new Error("SIWX is not enabled");if(!t)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");try{const n=await e.createMessage({chainId:s.caipNetworkId,accountAddress:t}),r=n.toString();let i="";if(e.signMessage)i=await e.signMessage({message:r,chainId:s.caipNetworkId,accountAddress:t});else{bs.getConnectorId(s.chainNamespace)===B.CONNECTOR_ID.AUTH&&hs.pushTransactionStack({}),i=await Us.signMessage(r)||""}await e.addSession({data:n,message:r,signature:i}),Qs.setLastConnectedSIWECaipNetwork(s),sn.close(),ss.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(e){sn.state.open&&"ApproveTransaction"!==hs.state.view||await sn.open({view:"SIWXSignMessage"}),Rt.showError("Error signing message"),ss.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(e)}),console.error("SWIXUtil:requestSignMessage",e)}},async cancelSignMessage(){try{const e=this.getSIWX(),t=e?.getRequired?.();if(t){const t=Qs.getLastConnectedSIWECaipNetwork();if(t){const s=await(e?.getSessions(t?.caipNetworkId,He.getPlainAddress(Qs.getActiveCaipAddress())||""));s&&s.length>0?await Qs.switchActiveNetwork(t):await Us.disconnect()}else await Us.disconnect()}else sn.close();sn.close(),ss.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){const e=this.getSIWX(),t=Qs.getAllRequestedCaipNetworks(),s=[];return await Promise.all(t.map((async t=>{const n=await(e?.getSessions(t.caipNetworkId,He.getPlainAddress(Qs.getActiveCaipAddress())||""));n&&s.push(...n)}))),s},async getSessions(e){const t=kt.state.siwx;let s=e?.address;if(!s){const e=Qs.getActiveCaipAddress();s=He.getPlainAddress(e)}let n=e?.caipNetworkId;if(!n){const e=Qs.getActiveCaipNetwork();n=e?.caipNetworkId}return t&&s&&n?t.getSessions(n,s):[]},async isSIWXCloseDisabled(){const e=this.getSIWX();if(e){const t="ApproveTransaction"===hs.state.view,s="SIWXSignMessage"===hs.state.view;if(t||s)return e.getRequired?.()&&0===(await this.getSessions()).length}return!1},async authConnectorAuthenticate({authConnector:e,chainId:t,socialUri:s,preferredAccountType:n,chainNamespace:r}){const i=GA.getSIWX(),o=As();if(!i||!r.includes(B.CHAIN.EVM)||kt.state.remoteFeatures?.emailCapture){const r=await e.connect({chainId:t,socialUri:s,preferredAccountType:n});return{address:r.address,chainId:r.chainId,accounts:r.accounts}}const a=`${r}:${t}`,c=await i.createMessage({chainId:a,accountAddress:"<<AccountAddress>>"}),l={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},d=await e.connect({chainId:t,socialUri:s,siwxMessage:l,preferredAccountType:n});if(l.accountAddress=d.address,l.serializedMessage=d.message||"",d.signature&&d.message){const e=GA.addEmbeddedWalletSession(l,d.message,d.signature);await e}return Qs.setLastConnectedSIWECaipNetwork(o),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(e,t,s){if(KA)return KA;const n=GA.getSIWX();return n?(KA=n.addSession({data:e,message:t,signature:s}).finally((()=>{KA=null})),KA):Promise.resolve()},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:s}){const n=GA.getSIWX(),r=As(),i=new Set(t.map((e=>e.split(":")[0])));if(!n||1!==i.size||!i.has("eip155"))return!1;const o=await n.createMessage({chainId:As()?.caipNetworkId||"",accountAddress:""}),a=await e.authenticate({nonce:o.nonce,domain:o.domain,uri:o.uri,exp:o.expirationTime,iat:o.issuedAt,nbf:o.notBefore,requestId:o.requestId,version:o.version,resources:o.resources,statement:o.statement,chainId:o.chainId,methods:s,chains:[o.chainId,...t.filter((e=>e!==o.chainId))]});Rt.showLoading("Authenticating...",{autoClose:!1});const c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:a.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"};if(Qs.setAccountProp("connectedWalletInfo",c,Array.from(i)[0]),a?.auths?.length){const t=a.auths.map((t=>{const s=e.client.formatAuthMessage({request:t.p,iss:t.p.iss});return{data:{...t.p,accountAddress:t.p.iss.split(":").slice(-1).join(""),chainId:t.p.iss.split(":").slice(2,4).join(":"),uri:t.p.aud??"",version:t.p.version||o.version,expirationTime:t.p.exp,issuedAt:t.p.iat,notBefore:t.p.nbf},message:s,signature:t.s.s,cacao:t}}));try{await n.setSessions(t),r&&Qs.setLastConnectedSIWECaipNetwork(r),ss.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:GA.getSIWXEventProperties()})}catch(t){throw console.error("SIWX:universalProviderAuth - failed to set sessions",t),ss.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:GA.getSIWXEventProperties(t)}),await e.disconnect().catch(console.error),t}finally{Rt.hide()}}return!0},getSIWXEventProperties(e){const t=Qs.state.activeChain;if(!t)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:Qs.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:Ns(t)===Ye.ACCOUNT_TYPES.SMART_ACCOUNT,message:e?He.parseError(e):void 0}},async clearSessions(){const e=this.getSIWX();e&&await e.setSessions([])}};class JA{constructor({provider:e,namespace:t}){this.id=B.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=Qs.getCaipNetworks.bind(Qs),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=t}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const e=this.getCaipNetworks(),t=kt.state.universalProviderConfigOverride,s=HA.createNamespaces(e,t);await this.provider.connect({optionalNamespaces:s})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map((e=>e.caipNetworkId));return GA.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:YA})}}const YA=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],XA=xe({message:"",variant:"info",open:!1}),ZA=Ht({state:XA,subscribeKey:(e,t)=>De(XA,e,t),open(e,t){const{debug:s}=kt.state,{code:n,displayMessage:r,debugMessage:i}=e;if(r&&s&&(XA.message=r,XA.variant=t,XA.open=!0),i){if(!B.IS_DEVELOPMENT)return;const e="function"==typeof i?i():i,s=n?{code:n}:void 0;"error"===t?console.error(e,s):"warning"===t?console.warn(e,s):console.info(e,s)}},warn(e,t,s){XA.open=!0,XA.message=e,XA.variant="warning",t&&console.warn(t,s)},close(){XA.open=!1,XA.message="",XA.variant="info"}}),QA=globalThis,eI=QA.ShadowRoot&&(void 0===QA.ShadyCSS||QA.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,tI=Symbol(),sI=new WeakMap;class nI{constructor(e,t,s){if(this._$cssResult$=!0,s!==tI)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(eI&&void 0===e){const s=void 0!==t&&1===t.length;s&&(e=sI.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),s&&sI.set(t,e))}return e}toString(){return this.cssText}}const rI=e=>new nI("string"==typeof e?e:e+"",void 0,tI),iI=(e,...t)=>{const s=1===e.length?e[0]:t.reduce(((t,s,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[n+1]),e[0]);return new nI(s,e,tI)},oI=eI?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const s of e.cssRules)t+=s.cssText;return rI(t)})(e):e
3
+ /**
4
+ * @license
5
+ * Copyright 2017 Google LLC
6
+ * SPDX-License-Identifier: BSD-3-Clause
7
+ */,{is:aI,defineProperty:cI,getOwnPropertyDescriptor:lI,getOwnPropertyNames:dI,getOwnPropertySymbols:hI,getPrototypeOf:uI}=Object,pI=globalThis,fI=pI.trustedTypes,gI=fI?fI.emptyScript:"",mI=pI.reactiveElementPolyfillSupport,yI=(e,t)=>e,wI={toAttribute(e,t){switch(t){case Boolean:e=e?gI:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let s=e;switch(t){case Boolean:s=null!==e;break;case Number:s=null===e?null:Number(e);break;case Object:case Array:try{s=JSON.parse(e)}catch(e){s=null}}return s}},bI=(e,t)=>!aI(e,t),vI={attribute:!0,type:String,converter:wI,reflect:!1,useDefault:!1,hasChanged:bI};Symbol.metadata??=Symbol("metadata"),pI.litPropertyMetadata??=new WeakMap;class EI extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=vI){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const s=Symbol(),n=this.getPropertyDescriptor(e,s,t);void 0!==n&&cI(this.prototype,e,n)}}static getPropertyDescriptor(e,t,s){const{get:n,set:r}=lI(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const i=n?.call(this);r?.call(this,t),this.requestUpdate(e,i,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??vI}static _$Ei(){if(this.hasOwnProperty(yI("elementProperties")))return;const e=uI(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(yI("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(yI("properties"))){const e=this.properties,t=[...dI(e),...hI(e)];for(const s of t)this.createProperty(s,e[s])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,s]of t)this.elementProperties.set(e,s)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const s=this._$Eu(e,t);void 0!==s&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const s=new Set(e.flat(1/0).reverse());for(const e of s)t.unshift(oI(e))}else void 0!==e&&t.push(oI(e));return t}static _$Eu(e,t){const s=t.attribute;return!1===s?void 0:"string"==typeof s?s:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const s of t.keys())this.hasOwnProperty(s)&&(e.set(s,this[s]),delete this[s]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(eI)e.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(const s of t){const t=document.createElement("style"),n=QA.litNonce;void 0!==n&&t.setAttribute("nonce",n),t.textContent=s.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,s){this._$AK(e,s)}_$ET(e,t){const s=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,s);if(void 0!==n&&!0===s.reflect){const r=(void 0!==s.converter?.toAttribute?s.converter:wI).toAttribute(t,s.type);this._$Em=e,null==r?this.removeAttribute(n):this.setAttribute(n,r),this._$Em=null}}_$AK(e,t){const s=this.constructor,n=s._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=s.getPropertyOptions(n),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:wI;this._$Em=n;const i=r.fromAttribute(t,e.type);this[n]=i??this._$Ej?.get(n)??i,this._$Em=null}}requestUpdate(e,t,s,n=!1,r){if(void 0!==e){const i=this.constructor;if(!1===n&&(r=this[e]),s??=i.getPropertyOptions(e),!((s.hasChanged??bI)(r,t)||s.useDefault&&s.reflect&&r===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,s))))return;this.C(e,t,s)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:s,reflect:n,wrapped:r},i){s&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,i??t??this[e]),!0!==r||void 0!==i)||(this._$AL.has(e)||(this.hasUpdated||s||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,s]of e){const{wrapped:e}=s,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,s,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach((e=>this._$ET(e,this[e]))),this._$EM()}updated(e){}firstUpdated(e){}}EI.elementStyles=[],EI.shadowRootOptions={mode:"open"},EI[yI("elementProperties")]=new Map,EI[yI("finalized")]=new Map,mI?.({ReactiveElement:EI}),(pI.reactiveElementVersions??=[]).push("2.1.2");
8
+ /**
9
+ * @license
10
+ * Copyright 2017 Google LLC
11
+ * SPDX-License-Identifier: BSD-3-Clause
12
+ */
13
+ const CI=globalThis,NI=CI.trustedTypes,AI=NI?NI.createPolicy("lit-html",{createHTML:e=>e}):void 0,II="$lit$",SI=`lit$${Math.random().toFixed(9).slice(2)}$`,_I="?"+SI,OI=`<${_I}>`,TI=document,kI=()=>TI.createComment(""),PI=e=>null===e||"object"!=typeof e&&"function"!=typeof e,xI=Array.isArray,RI="[ \t\n\f\r]",UI=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,LI=/-->/g,DI=/>/g,MI=RegExp(`>|${RI}(?:([^\\s"'>=/]+)(${RI}*=${RI}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),BI=/'/g,jI=/"/g,$I=/^(?:script|style|textarea|title)$/i,FI=e=>(t,...s)=>({_$litType$:e,strings:t,values:s}),qI=FI(1),WI=FI(2),HI=Symbol.for("lit-noChange"),zI=Symbol.for("lit-nothing"),VI=new WeakMap,KI=TI.createTreeWalker(TI,129);function GI(e,t){if(!xI(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==AI?AI.createHTML(t):t}const JI=(e,t)=>{const s=e.length-1,n=[];let r,i=2===t?"<svg>":3===t?"<math>":"",o=UI;for(let t=0;t<s;t++){const s=e[t];let a,c,l=-1,d=0;for(;d<s.length&&(o.lastIndex=d,c=o.exec(s),null!==c);)d=o.lastIndex,o===UI?"!--"===c[1]?o=LI:void 0!==c[1]?o=DI:void 0!==c[2]?($I.test(c[2])&&(r=RegExp("</"+c[2],"g")),o=MI):void 0!==c[3]&&(o=MI):o===MI?">"===c[0]?(o=r??UI,l=-1):void 0===c[1]?l=-2:(l=o.lastIndex-c[2].length,a=c[1],o=void 0===c[3]?MI:'"'===c[3]?jI:BI):o===jI||o===BI?o=MI:o===LI||o===DI?o=UI:(o=MI,r=void 0);const h=o===MI&&e[t+1].startsWith("/>")?" ":"";i+=o===UI?s+OI:l>=0?(n.push(a),s.slice(0,l)+II+s.slice(l)+SI+h):s+SI+(-2===l?t:h)}return[GI(e,i+(e[s]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),n]};class YI{constructor({strings:e,_$litType$:t},s){let n;this.parts=[];let r=0,i=0;const o=e.length-1,a=this.parts,[c,l]=JI(e,t);if(this.el=YI.createElement(c,s),KI.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(n=KI.nextNode())&&a.length<o;){if(1===n.nodeType){if(n.hasAttributes())for(const e of n.getAttributeNames())if(e.endsWith(II)){const t=l[i++],s=n.getAttribute(e).split(SI),o=/([.?@])?(.*)/.exec(t);a.push({type:1,index:r,name:o[2],strings:s,ctor:"."===o[1]?tS:"?"===o[1]?sS:"@"===o[1]?nS:eS}),n.removeAttribute(e)}else e.startsWith(SI)&&(a.push({type:6,index:r}),n.removeAttribute(e));if($I.test(n.tagName)){const e=n.textContent.split(SI),t=e.length-1;if(t>0){n.textContent=NI?NI.emptyScript:"";for(let s=0;s<t;s++)n.append(e[s],kI()),KI.nextNode(),a.push({type:2,index:++r});n.append(e[t],kI())}}}else if(8===n.nodeType)if(n.data===_I)a.push({type:2,index:r});else{let e=-1;for(;-1!==(e=n.data.indexOf(SI,e+1));)a.push({type:7,index:r}),e+=SI.length-1}r++}}static createElement(e,t){const s=TI.createElement("template");return s.innerHTML=e,s}}function XI(e,t,s=e,n){if(t===HI)return t;let r=void 0!==n?s._$Co?.[n]:s._$Cl;const i=PI(t)?void 0:t._$litDirective$;return r?.constructor!==i&&(r?._$AO?.(!1),void 0===i?r=void 0:(r=new i(e),r._$AT(e,s,n)),void 0!==n?(s._$Co??=[])[n]=r:s._$Cl=r),void 0!==r&&(t=XI(e,r._$AS(e,t.values),r,n)),t}class ZI{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:s}=this._$AD,n=(e?.creationScope??TI).importNode(t,!0);KI.currentNode=n;let r=KI.nextNode(),i=0,o=0,a=s[0];for(;void 0!==a;){if(i===a.index){let t;2===a.type?t=new QI(r,r.nextSibling,this,e):1===a.type?t=new a.ctor(r,a.name,a.strings,this,e):6===a.type&&(t=new rS(r,this,e)),this._$AV.push(t),a=s[++o]}i!==a?.index&&(r=KI.nextNode(),i++)}return KI.currentNode=TI,n}p(e){let t=0;for(const s of this._$AV)void 0!==s&&(void 0!==s.strings?(s._$AI(e,s,t),t+=s.strings.length-2):s._$AI(e[t])),t++}}class QI{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,s,n){this.type=2,this._$AH=zI,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=s,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=XI(this,e,t),PI(e)?e===zI||null==e||""===e?(this._$AH!==zI&&this._$AR(),this._$AH=zI):e!==this._$AH&&e!==HI&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>xI(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==zI&&PI(this._$AH)?this._$AA.nextSibling.data=e:this.T(TI.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:s}=e,n="number"==typeof s?this._$AC(e):(void 0===s.el&&(s.el=YI.createElement(GI(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new ZI(n,this),s=e.u(this.options);e.p(t),this.T(s),this._$AH=e}}_$AC(e){let t=VI.get(e.strings);return void 0===t&&VI.set(e.strings,t=new YI(e)),t}k(e){xI(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let s,n=0;for(const r of e)n===t.length?t.push(s=new QI(this.O(kI()),this.O(kI()),this,this.options)):s=t[n],s._$AI(r),n++;n<t.length&&(this._$AR(s&&s._$AB.nextSibling,n),t.length=n)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){const t=e.nextSibling;e.remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}}class eS{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,s,n,r){this.type=1,this._$AH=zI,this._$AN=void 0,this.element=e,this.name=t,this._$AM=n,this.options=r,s.length>2||""!==s[0]||""!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=zI}_$AI(e,t=this,s,n){const r=this.strings;let i=!1;if(void 0===r)e=XI(this,e,t,0),i=!PI(e)||e!==this._$AH&&e!==HI,i&&(this._$AH=e);else{const n=e;let o,a;for(e=r[0],o=0;o<r.length-1;o++)a=XI(this,n[s+o],t,o),a===HI&&(a=this._$AH[o]),i||=!PI(a)||a!==this._$AH[o],a===zI?e=zI:e!==zI&&(e+=(a??"")+r[o+1]),this._$AH[o]=a}i&&!n&&this.j(e)}j(e){e===zI?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class tS extends eS{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===zI?void 0:e}}class sS extends eS{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==zI)}}class nS extends eS{constructor(e,t,s,n,r){super(e,t,s,n,r),this.type=5}_$AI(e,t=this){if((e=XI(this,e,t,0)??zI)===HI)return;const s=this._$AH,n=e===zI&&s!==zI||e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive,r=e!==zI&&(s===zI||n);n&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class rS{constructor(e,t,s){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(e){XI(this,e)}}const iS=CI.litHtmlPolyfillSupport;iS?.(YI,QI),(CI.litHtmlVersions??=[]).push("3.3.3");const oS=globalThis;
14
+ /**
15
+ * @license
16
+ * Copyright 2017 Google LLC
17
+ * SPDX-License-Identifier: BSD-3-Clause
18
+ */class aS extends EI{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,s)=>{const n=s?.renderBefore??t;let r=n._$litPart$;if(void 0===r){const e=s?.renderBefore??null;n._$litPart$=r=new QI(t.insertBefore(kI(),e),e,void 0,s??{})}return r._$AI(e),r})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return HI}}aS._$litElement$=!0,aS.finalized=!0,oS.litElementHydrateSupport?.({LitElement:aS});const cS=oS.litElementPolyfillSupport;cS?.({LitElement:aS}),(oS.litElementVersions??=[]).push("4.2.2");const lS={core:{backgroundAccentPrimary:"#0988F0",backgroundAccentCertified:"#C7B994",backgroundWalletKit:"#FFB800",backgroundAppKit:"#FF573B",backgroundCloud:"#0988F0",backgroundDocumentation:"#008847",backgroundSuccess:"rgba(48, 164, 107, 0.20)",backgroundError:"rgba(223, 74, 52, 0.20)",backgroundWarning:"rgba(243, 161, 63, 0.20)",textAccentPrimary:"#0988F0",textAccentCertified:"#C7B994",textWalletKit:"#FFB800",textAppKit:"#FF573B",textCloud:"#0988F0",textDocumentation:"#008847",textSuccess:"#30A46B",textError:"#DF4A34",textWarning:"#F3A13F",borderAccentPrimary:"#0988F0",borderSecondary:"#C7B994",borderSuccess:"#30A46B",borderError:"#DF4A34",borderWarning:"#F3A13F",foregroundAccent010:"rgba(9, 136, 240, 0.1)",foregroundAccent020:"rgba(9, 136, 240, 0.2)",foregroundAccent040:"rgba(9, 136, 240, 0.4)",foregroundAccent060:"rgba(9, 136, 240, 0.6)",foregroundSecondary020:"rgba(199, 185, 148, 0.2)",foregroundSecondary040:"rgba(199, 185, 148, 0.4)",foregroundSecondary060:"rgba(199, 185, 148, 0.6)",iconAccentPrimary:"#0988F0",iconAccentCertified:"#C7B994",iconSuccess:"#30A46B",iconError:"#DF4A34",iconWarning:"#F3A13F",glass010:"rgba(255, 255, 255, 0.1)",zIndex:"9999"},dark:{overlay:"rgba(0, 0, 0, 0.50)",backgroundPrimary:"#202020",backgroundInvert:"#FFFFFF",textPrimary:"#FFFFFF",textSecondary:"#9A9A9A",textTertiary:"#BBBBBB",textInvert:"#202020",borderPrimary:"#2A2A2A",borderPrimaryDark:"#363636",borderSecondary:"#4F4F4F",foregroundPrimary:"#252525",foregroundSecondary:"#2A2A2A",foregroundTertiary:"#363636",iconDefault:"#9A9A9A",iconInverse:"#FFFFFF"},light:{overlay:"rgba(230 , 230, 230, 0.5)",backgroundPrimary:"#FFFFFF",borderPrimaryDark:"#E9E9E9",backgroundInvert:"#202020",textPrimary:"#202020",textSecondary:"#9A9A9A",textTertiary:"#6C6C6C",textInvert:"#FFFFFF",borderPrimary:"#E9E9E9",borderSecondary:"#D0D0D0",foregroundPrimary:"#F3F3F3",foregroundSecondary:"#E9E9E9",foregroundTertiary:"#D0D0D0",iconDefault:"#9A9A9A",iconInverse:"#202020"}},dS={colors:{black:"#202020",white:"#FFFFFF",white010:"rgba(255, 255, 255, 0.1)",accent010:"rgba(9, 136, 240, 0.1)",accent020:"rgba(9, 136, 240, 0.2)",accent030:"rgba(9, 136, 240, 0.3)",accent040:"rgba(9, 136, 240, 0.4)",accent050:"rgba(9, 136, 240, 0.5)",accent060:"rgba(9, 136, 240, 0.6)",accent070:"rgba(9, 136, 240, 0.7)",accent080:"rgba(9, 136, 240, 0.8)",accent090:"rgba(9, 136, 240, 0.9)",accent100:"rgba(9, 136, 240, 1.0)",accentSecondary010:"rgba(199, 185, 148, 0.1)",accentSecondary020:"rgba(199, 185, 148, 0.2)",accentSecondary030:"rgba(199, 185, 148, 0.3)",accentSecondary040:"rgba(199, 185, 148, 0.4)",accentSecondary050:"rgba(199, 185, 148, 0.5)",accentSecondary060:"rgba(199, 185, 148, 0.6)",accentSecondary070:"rgba(199, 185, 148, 0.7)",accentSecondary080:"rgba(199, 185, 148, 0.8)",accentSecondary090:"rgba(199, 185, 148, 0.9)",accentSecondary100:"rgba(199, 185, 148, 1.0)",productWalletKit:"#FFB800",productAppKit:"#FF573B",productCloud:"#0988F0",productDocumentation:"#008847",neutrals050:"#F6F6F6",neutrals100:"#F3F3F3",neutrals200:"#E9E9E9",neutrals300:"#D0D0D0",neutrals400:"#BBB",neutrals500:"#9A9A9A",neutrals600:"#6C6C6C",neutrals700:"#4F4F4F",neutrals800:"#363636",neutrals900:"#2A2A2A",neutrals1000:"#252525",semanticSuccess010:"rgba(48, 164, 107, 0.1)",semanticSuccess020:"rgba(48, 164, 107, 0.2)",semanticSuccess030:"rgba(48, 164, 107, 0.3)",semanticSuccess040:"rgba(48, 164, 107, 0.4)",semanticSuccess050:"rgba(48, 164, 107, 0.5)",semanticSuccess060:"rgba(48, 164, 107, 0.6)",semanticSuccess070:"rgba(48, 164, 107, 0.7)",semanticSuccess080:"rgba(48, 164, 107, 0.8)",semanticSuccess090:"rgba(48, 164, 107, 0.9)",semanticSuccess100:"rgba(48, 164, 107, 1.0)",semanticError010:"rgba(223, 74, 52, 0.1)",semanticError020:"rgba(223, 74, 52, 0.2)",semanticError030:"rgba(223, 74, 52, 0.3)",semanticError040:"rgba(223, 74, 52, 0.4)",semanticError050:"rgba(223, 74, 52, 0.5)",semanticError060:"rgba(223, 74, 52, 0.6)",semanticError070:"rgba(223, 74, 52, 0.7)",semanticError080:"rgba(223, 74, 52, 0.8)",semanticError090:"rgba(223, 74, 52, 0.9)",semanticError100:"rgba(223, 74, 52, 1.0)",semanticWarning010:"rgba(243, 161, 63, 0.1)",semanticWarning020:"rgba(243, 161, 63, 0.2)",semanticWarning030:"rgba(243, 161, 63, 0.3)",semanticWarning040:"rgba(243, 161, 63, 0.4)",semanticWarning050:"rgba(243, 161, 63, 0.5)",semanticWarning060:"rgba(243, 161, 63, 0.6)",semanticWarning070:"rgba(243, 161, 63, 0.7)",semanticWarning080:"rgba(243, 161, 63, 0.8)",semanticWarning090:"rgba(243, 161, 63, 0.9)",semanticWarning100:"rgba(243, 161, 63, 1.0)"},fontFamily:{regular:"KHTeka",mono:"KHTekaMono"},fontWeight:{regular:"400",medium:"500"},textSize:{h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},typography:{"h1-regular-mono":{lineHeight:"50px",letterSpacing:"-3px"},"h1-regular":{lineHeight:"50px",letterSpacing:"-1px"},"h1-medium":{lineHeight:"50px",letterSpacing:"-0.84px"},"h2-regular-mono":{lineHeight:"44px",letterSpacing:"-2.64px"},"h2-regular":{lineHeight:"44px",letterSpacing:"-0.88px"},"h2-medium":{lineHeight:"44px",letterSpacing:"-0.88px"},"h3-regular-mono":{lineHeight:"38px",letterSpacing:"-2.28px"},"h3-regular":{lineHeight:"38px",letterSpacing:"-0.76px"},"h3-medium":{lineHeight:"38px",letterSpacing:"-0.76px"},"h4-regular-mono":{lineHeight:"32px",letterSpacing:"-1.92px"},"h4-regular":{lineHeight:"32px",letterSpacing:"-0.32px"},"h4-medium":{lineHeight:"32px",letterSpacing:"-0.32px"},"h5-regular-mono":{lineHeight:"26px",letterSpacing:"-1.56px"},"h5-regular":{lineHeight:"26px",letterSpacing:"-0.26px"},"h5-medium":{lineHeight:"26px",letterSpacing:"-0.26px"},"h6-regular-mono":{lineHeight:"20px",letterSpacing:"-1.2px"},"h6-regular":{lineHeight:"20px",letterSpacing:"-0.6px"},"h6-medium":{lineHeight:"20px",letterSpacing:"-0.6px"},"lg-regular-mono":{lineHeight:"16px",letterSpacing:"-0.96px"},"lg-regular":{lineHeight:"18px",letterSpacing:"-0.16px"},"lg-medium":{lineHeight:"18px",letterSpacing:"-0.16px"},"md-regular-mono":{lineHeight:"14px",letterSpacing:"-0.84px"},"md-regular":{lineHeight:"16px",letterSpacing:"-0.14px"},"md-medium":{lineHeight:"16px",letterSpacing:"-0.14px"},"sm-regular-mono":{lineHeight:"12px",letterSpacing:"-0.72px"},"sm-regular":{lineHeight:"14px",letterSpacing:"-0.12px"},"sm-medium":{lineHeight:"14px",letterSpacing:"-0.12px"}},tokens:{core:lS.core,theme:lS.dark},borderRadius:{1:"4px",2:"8px",10:"10px",3:"12px",4:"16px",6:"24px",5:"20px",8:"32px",16:"64px",20:"80px",32:"128px",64:"256px",128:"512px",round:"9999px"},spacing:{0:"0px","01":"2px",1:"4px",2:"8px",3:"12px",4:"16px",5:"20px",6:"24px",7:"28px",8:"32px",9:"36px",10:"40px",12:"48px",14:"56px",16:"64px",20:"80px",32:"128px",64:"256px"},durations:{xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},easings:{"ease-out-power-2":"cubic-bezier(0.23, 0.09, 0.08, 1.13)","ease-out-power-1":"cubic-bezier(0.12, 0.04, 0.2, 1.06)","ease-in-power-2":"cubic-bezier(0.92, -0.13, 0.77, 0.91)","ease-in-power-1":"cubic-bezier(0.88, -0.06, 0.8, 0.96)","ease-inout-power-2":"cubic-bezier(0.77, 0.09, 0.23, 1.13)","ease-inout-power-1":"cubic-bezier(0.88, 0.04, 0.12, 1.06)"}},hS="--apkt";function uS(e){if(!e)return{};const t={};return t["font-family"]=e["--apkt-font-family"]??e["--w3m-font-family"]??"KHTeka",t.accent=e["--apkt-accent"]??e["--w3m-accent"]??"#0988F0",t["color-mix"]=e["--apkt-color-mix"]??e["--w3m-color-mix"]??"#000",t["color-mix-strength"]=e["--apkt-color-mix-strength"]??e["--w3m-color-mix-strength"]??0,t["font-size-master"]=e["--apkt-font-size-master"]??e["--w3m-font-size-master"]??"10px",t["border-radius-master"]=e["--apkt-border-radius-master"]??e["--w3m-border-radius-master"]??"4px",void 0!==e["--apkt-z-index"]?t["z-index"]=e["--apkt-z-index"]:void 0!==e["--w3m-z-index"]&&(t["z-index"]=e["--w3m-z-index"]),t}const pS={createCSSVariables(e){const t={},s={};return function e(t,s,n=""){for(const[r,i]of Object.entries(t)){const t=n?`${n}-${r}`:r;i&&"object"==typeof i&&Object.keys(i).length?(s[r]={},e(i,s[r],t)):"string"==typeof i&&(s[r]=`${hS}-${t}`)}}(e,t),function e(t,s){for(const[n,r]of Object.entries(t))r&&"object"==typeof r?(s[n]={},e(r,s[n])):"string"==typeof r&&(s[n]=`var(${r})`)}(t,s),{cssVariables:t,cssVariablesVarPrefix:s}},assignCSSVariables(e,t){const s={};return function e(t,n,r){for(const[i,o]of Object.entries(t)){const t=r?`${r}-${i}`:i,a=n[i];o&&"object"==typeof o?e(o,a,t):"string"==typeof a&&(s[`${hS}-${t}`]=a)}}(e,t),s},createRootStyles(e,t){const s={...dS,tokens:{...dS.tokens,theme:"light"===e?lS.light:lS.dark}},{cssVariables:n}=pS.createCSSVariables(s),r=pS.assignCSSVariables(n,s),i=pS.generateW3MVariables(t),o=pS.generateW3MOverrides(t),a=pS.generateScaledVariables(t),c=pS.generateBaseVariables(r),l={...r,...c,...i,...o,...a},d=pS.applyColorMixToVariables(t,l),h={...l,...d};return`:root {${Object.entries(h).map((([e,t])=>`${e}:${t.replace("/[:;{}</>]/g","")};`)).join("")}}`},generateW3MVariables(e){if(!e)return{};const t=uS(e),s={};return s["--w3m-font-family"]=t["font-family"],s["--w3m-accent"]=t.accent,s["--w3m-color-mix"]=t["color-mix"],s["--w3m-color-mix-strength"]=`${t["color-mix-strength"]}%`,s["--w3m-font-size-master"]=t["font-size-master"],s["--w3m-border-radius-master"]=t["border-radius-master"],s},generateW3MOverrides(e){if(!e)return{};const t=uS(e),s={};if(e["--apkt-accent"]||e["--w3m-accent"]){const e=t.accent;s["--apkt-tokens-core-iconAccentPrimary"]=e,s["--apkt-tokens-core-borderAccentPrimary"]=e,s["--apkt-tokens-core-textAccentPrimary"]=e,s["--apkt-tokens-core-backgroundAccentPrimary"]=e}return(e["--apkt-font-family"]||e["--w3m-font-family"])&&(s["--apkt-fontFamily-regular"]=t["font-family"]),void 0!==t["z-index"]&&(s["--apkt-tokens-core-zIndex"]=`${t["z-index"]}`),s},generateScaledVariables(e){if(!e)return{};const t=uS(e),s={};if(e["--apkt-font-size-master"]||e["--w3m-font-size-master"]){const e=parseFloat(t["font-size-master"].replace("px",""));s["--apkt-textSize-h1"]=5*Number(e)+"px",s["--apkt-textSize-h2"]=4.4*Number(e)+"px",s["--apkt-textSize-h3"]=3.8*Number(e)+"px",s["--apkt-textSize-h4"]=3.2*Number(e)+"px",s["--apkt-textSize-h5"]=2.6*Number(e)+"px",s["--apkt-textSize-h6"]=2*Number(e)+"px",s["--apkt-textSize-large"]=1.6*Number(e)+"px",s["--apkt-textSize-medium"]=1.4*Number(e)+"px",s["--apkt-textSize-small"]=1.2*Number(e)+"px"}if(e["--apkt-border-radius-master"]||e["--w3m-border-radius-master"]){const e=parseFloat(t["border-radius-master"].replace("px",""));s["--apkt-borderRadius-1"]=`${Number(e)}px`,s["--apkt-borderRadius-2"]=2*Number(e)+"px",s["--apkt-borderRadius-3"]=3*Number(e)+"px",s["--apkt-borderRadius-4"]=4*Number(e)+"px",s["--apkt-borderRadius-5"]=5*Number(e)+"px",s["--apkt-borderRadius-6"]=6*Number(e)+"px",s["--apkt-borderRadius-8"]=8*Number(e)+"px",s["--apkt-borderRadius-16"]=16*Number(e)+"px",s["--apkt-borderRadius-20"]=20*Number(e)+"px",s["--apkt-borderRadius-32"]=32*Number(e)+"px",s["--apkt-borderRadius-64"]=64*Number(e)+"px",s["--apkt-borderRadius-128"]=128*Number(e)+"px"}return s},generateColorMixCSS(e,t){if(!e?.["--w3m-color-mix"]||!e["--w3m-color-mix-strength"])return"";const s=e["--w3m-color-mix"],n=e["--w3m-color-mix-strength"];if(!n||0===n)return"";const r=Object.keys(t||{}).filter((e=>{const t=e.includes("-tokens-core-background")||e.includes("-tokens-core-text")||e.includes("-tokens-core-border")||e.includes("-tokens-core-foreground")||e.includes("-tokens-core-icon")||e.includes("-tokens-theme-background")||e.includes("-tokens-theme-text")||e.includes("-tokens-theme-border")||e.includes("-tokens-theme-foreground")||e.includes("-tokens-theme-icon"),s=e.includes("-borderRadius-")||e.includes("-spacing-")||e.includes("-textSize-")||e.includes("-fontFamily-")||e.includes("-fontWeight-")||e.includes("-typography-")||e.includes("-duration-")||e.includes("-ease-")||e.includes("-path-")||e.includes("-width-")||e.includes("-height-")||e.includes("-visual-size-")||e.includes("-modal-width")||e.includes("-cover");return t&&!s}));if(0===r.length)return"";return` @supports (background: color-mix(in srgb, white 50%, black)) {\n :root {\n ${r.map((e=>{const r=t?.[e]||"";return r.includes("color-mix")||r.startsWith("#")||r.startsWith("rgb")?`${e}: color-mix(in srgb, ${s} ${n}%, ${r});`:`${e}: color-mix(in srgb, ${s} ${n}%, var(${e}-base, ${r}));`})).join("")}\n }\n }`},generateBaseVariables(e){const t={},s=e["--apkt-tokens-theme-backgroundPrimary"];s&&(t["--apkt-tokens-theme-backgroundPrimary-base"]=s);const n=e["--apkt-tokens-core-backgroundAccentPrimary"];return n&&(t["--apkt-tokens-core-backgroundAccentPrimary-base"]=n),t},applyColorMixToVariables(e,t){const s={};t?.["--apkt-tokens-theme-backgroundPrimary"]&&(s["--apkt-tokens-theme-backgroundPrimary"]="var(--apkt-tokens-theme-backgroundPrimary-base)"),t?.["--apkt-tokens-core-backgroundAccentPrimary"]&&(s["--apkt-tokens-core-backgroundAccentPrimary"]="var(--apkt-tokens-core-backgroundAccentPrimary-base)");const n=uS(e),r=n["color-mix"],i=n["color-mix-strength"];if(!i||0===i)return s;const o=Object.keys(t||{}).filter((e=>{const t=e.includes("-tokens-core-background")||e.includes("-tokens-core-text")||e.includes("-tokens-core-border")||e.includes("-tokens-core-foreground")||e.includes("-tokens-core-icon")||e.includes("-tokens-theme-background")||e.includes("-tokens-theme-text")||e.includes("-tokens-theme-border")||e.includes("-tokens-theme-foreground")||e.includes("-tokens-theme-icon")||e.includes("-tokens-theme-overlay"),s=e.includes("-borderRadius-")||e.includes("-spacing-")||e.includes("-textSize-")||e.includes("-fontFamily-")||e.includes("-fontWeight-")||e.includes("-typography-")||e.includes("-duration-")||e.includes("-ease-")||e.includes("-path-")||e.includes("-width-")||e.includes("-height-")||e.includes("-visual-size-")||e.includes("-modal-width")||e.includes("-cover");return t&&!s}));return 0===o.length||o.forEach((e=>{const n=t?.[e]||"";e.endsWith("-base")||("--apkt-tokens-theme-backgroundPrimary"===e||"--apkt-tokens-core-backgroundAccentPrimary"===e?s[e]=`color-mix(in srgb, ${r} ${i}%, var(${e}-base))`:n.includes("color-mix")||n.startsWith("#")||n.startsWith("rgb")?s[e]=`color-mix(in srgb, ${r} ${i}%, ${n})`:s[e]=`color-mix(in srgb, ${r} ${i}%, var(${e}-base, ${n}))`)})),s}},{cssVariablesVarPrefix:fS}=pS.createCSSVariables(dS);function gS(e,...t){return iI(e,...t.map((e=>rI("function"==typeof e?e(fS):e))))}let mS,yS,wS,bS,vS;const ES={"KHTeka-500-woff2":"https://fonts.reown.com/KHTeka-Medium.woff2","KHTeka-400-woff2":"https://fonts.reown.com/KHTeka-Regular.woff2","KHTeka-300-woff2":"https://fonts.reown.com/KHTeka-Light.woff2","KHTekaMono-400-woff2":"https://fonts.reown.com/KHTekaMono-Regular.woff2","KHTeka-500-woff":"https://fonts.reown.com/KHTeka-Light.woff","KHTeka-400-woff":"https://fonts.reown.com/KHTeka-Regular.woff","KHTeka-300-woff":"https://fonts.reown.com/KHTeka-Light.woff","KHTekaMono-400-woff":"https://fonts.reown.com/KHTekaMono-Regular.woff"};function CS(e,t="dark"){mS&&document.head.removeChild(mS),mS=document.createElement("style"),mS.textContent=pS.createRootStyles(t,e),document.head.appendChild(mS)}function NS(e,t="dark"){vS=e,yS=document.createElement("style"),wS=document.createElement("style"),bS=document.createElement("style"),yS.textContent=IS(e).core.cssText,wS.textContent=IS(e).dark.cssText,bS.textContent=IS(e).light.cssText,document.head.appendChild(yS),document.head.appendChild(wS),document.head.appendChild(bS),CS(e,t),AS(t);if(!(e?.["--apkt-font-family"]||e?.["--w3m-font-family"]))for(const[e,t]of Object.entries(ES)){const s=document.createElement("link");s.rel="preload",s.href=t,s.as="font",s.type=e.includes("woff2")?"font/woff2":"font/woff",s.crossOrigin="anonymous",document.head.appendChild(s)}AS(t)}function AS(e="dark"){wS&&bS&&mS&&("light"===e?(CS(vS,e),wS.removeAttribute("media"),bS.media="enabled"):(CS(vS,e),bS.removeAttribute("media"),wS.media="enabled"))}function IS(e){const t=Boolean(e?.["--apkt-font-family"]||e?.["--w3m-font-family"]);return{core:iI`
19
+ ${t?iI``:iI`
20
+ @font-face {
21
+ font-family: 'KHTeka';
22
+ src:
23
+ url(${rI(ES["KHTeka-400-woff2"])}) format('woff2'),
24
+ url(${rI(ES["KHTeka-400-woff"])}) format('woff');
25
+ font-weight: 400;
26
+ font-style: normal;
27
+ font-display: swap;
28
+ }
29
+
30
+ @font-face {
31
+ font-family: 'KHTeka';
32
+ src:
33
+ url(${rI(ES["KHTeka-300-woff2"])}) format('woff2'),
34
+ url(${rI(ES["KHTeka-300-woff"])}) format('woff');
35
+ font-weight: 300;
36
+ font-style: normal;
37
+ }
38
+
39
+ @font-face {
40
+ font-family: 'KHTekaMono';
41
+ src:
42
+ url(${rI(ES["KHTekaMono-400-woff2"])}) format('woff2'),
43
+ url(${rI(ES["KHTekaMono-400-woff"])}) format('woff');
44
+ font-weight: 400;
45
+ font-style: normal;
46
+ }
47
+
48
+ @font-face {
49
+ font-family: 'KHTeka';
50
+ src:
51
+ url(${rI(ES["KHTeka-400-woff2"])}) format('woff2'),
52
+ url(${rI(ES["KHTeka-400-woff"])}) format('woff');
53
+ font-weight: 400;
54
+ font-style: normal;
55
+ }
56
+ `}
57
+
58
+ @keyframes w3m-shake {
59
+ 0% {
60
+ transform: scale(1) rotate(0deg);
61
+ }
62
+ 20% {
63
+ transform: scale(1) rotate(-1deg);
64
+ }
65
+ 40% {
66
+ transform: scale(1) rotate(1.5deg);
67
+ }
68
+ 60% {
69
+ transform: scale(1) rotate(-1.5deg);
70
+ }
71
+ 80% {
72
+ transform: scale(1) rotate(1deg);
73
+ }
74
+ 100% {
75
+ transform: scale(1) rotate(0deg);
76
+ }
77
+ }
78
+ @keyframes w3m-iframe-fade-out {
79
+ 0% {
80
+ opacity: 1;
81
+ }
82
+ 100% {
83
+ opacity: 0;
84
+ }
85
+ }
86
+ @keyframes w3m-iframe-zoom-in {
87
+ 0% {
88
+ transform: translateY(50px);
89
+ opacity: 0;
90
+ }
91
+ 100% {
92
+ transform: translateY(0px);
93
+ opacity: 1;
94
+ }
95
+ }
96
+ @keyframes w3m-iframe-zoom-in-mobile {
97
+ 0% {
98
+ transform: scale(0.95);
99
+ opacity: 0;
100
+ }
101
+ 100% {
102
+ transform: scale(1);
103
+ opacity: 1;
104
+ }
105
+ }
106
+ :root {
107
+ --apkt-modal-width: 370px;
108
+
109
+ --apkt-visual-size-inherit: inherit;
110
+ --apkt-visual-size-sm: 40px;
111
+ --apkt-visual-size-md: 55px;
112
+ --apkt-visual-size-lg: 80px;
113
+
114
+ --apkt-path-network-sm: path(
115
+ 'M15.4 2.1a5.21 5.21 0 0 1 5.2 0l11.61 6.7a5.21 5.21 0 0 1 2.61 4.52v13.4c0 1.87-1 3.59-2.6 4.52l-11.61 6.7c-1.62.93-3.6.93-5.22 0l-11.6-6.7a5.21 5.21 0 0 1-2.61-4.51v-13.4c0-1.87 1-3.6 2.6-4.52L15.4 2.1Z'
116
+ );
117
+
118
+ --apkt-path-network-md: path(
119
+ 'M43.4605 10.7248L28.0485 1.61089C25.5438 0.129705 22.4562 0.129705 19.9515 1.61088L4.53951 10.7248C2.03626 12.2051 0.5 14.9365 0.5 17.886V36.1139C0.5 39.0635 2.03626 41.7949 4.53951 43.2752L19.9515 52.3891C22.4562 53.8703 25.5438 53.8703 28.0485 52.3891L43.4605 43.2752C45.9637 41.7949 47.5 39.0635 47.5 36.114V17.8861C47.5 14.9365 45.9637 12.2051 43.4605 10.7248Z'
120
+ );
121
+
122
+ --apkt-path-network-lg: path(
123
+ 'M78.3244 18.926L50.1808 2.45078C45.7376 -0.150261 40.2624 -0.150262 35.8192 2.45078L7.6756 18.926C3.23322 21.5266 0.5 26.3301 0.5 31.5248V64.4752C0.5 69.6699 3.23322 74.4734 7.6756 77.074L35.8192 93.5492C40.2624 96.1503 45.7376 96.1503 50.1808 93.5492L78.3244 77.074C82.7668 74.4734 85.5 69.6699 85.5 64.4752V31.5248C85.5 26.3301 82.7668 21.5266 78.3244 18.926Z'
124
+ );
125
+
126
+ --apkt-width-network-sm: 36px;
127
+ --apkt-width-network-md: 48px;
128
+ --apkt-width-network-lg: 86px;
129
+
130
+ --apkt-duration-dynamic: 0ms;
131
+ --apkt-height-network-sm: 40px;
132
+ --apkt-height-network-md: 54px;
133
+ --apkt-height-network-lg: 96px;
134
+ }
135
+ `,dark:iI`
136
+ :root {
137
+ }
138
+ `,light:iI`
139
+ :root {
140
+ }
141
+ `}}const SS=iI`
142
+ div,
143
+ span,
144
+ iframe,
145
+ a,
146
+ img,
147
+ form,
148
+ button,
149
+ label,
150
+ *::after,
151
+ *::before {
152
+ margin: 0;
153
+ padding: 0;
154
+ box-sizing: border-box;
155
+ font-style: normal;
156
+ text-rendering: optimizeSpeed;
157
+ -webkit-font-smoothing: antialiased;
158
+ -moz-osx-font-smoothing: grayscale;
159
+ -webkit-tap-highlight-color: transparent;
160
+ backface-visibility: hidden;
161
+ }
162
+
163
+ :host {
164
+ font-family: var(--apkt-fontFamily-regular);
165
+ }
166
+ `,_S=iI`
167
+ button,
168
+ a {
169
+ cursor: pointer;
170
+ display: flex;
171
+ justify-content: center;
172
+ align-items: center;
173
+ position: relative;
174
+
175
+ will-change: background-color, color, border, box-shadow, width, height, transform, opacity;
176
+ outline: none;
177
+ border: none;
178
+ text-decoration: none;
179
+ transition:
180
+ background-color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
181
+ color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
182
+ border var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
183
+ box-shadow var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
184
+ width var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
185
+ height var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
186
+ transform var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
187
+ opacity var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
188
+ scale var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
189
+ border-radius var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2);
190
+ will-change:
191
+ background-color, color, border, box-shadow, width, height, transform, opacity, scale,
192
+ border-radius;
193
+ }
194
+
195
+ a:active:not([disabled]),
196
+ button:active:not([disabled]) {
197
+ scale: 0.975;
198
+ transform-origin: center;
199
+ }
200
+
201
+ button:disabled {
202
+ cursor: default;
203
+ }
204
+
205
+ input {
206
+ border: none;
207
+ outline: none;
208
+ appearance: none;
209
+ }
210
+ `,OS={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:B.CHAIN.EVM,ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH",getSDKVersionWarningMessage:(e,t)=>`\n @@@@@@@ @@@@@@@@@@@@@@@@@@ \n @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ \n @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ \n @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ \n @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@ \n @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@ \n @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@\n @@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@ \n @@@@@@ @@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@ \n @@@@@@ @@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@ \n @@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@ \n @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ \n @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ \n @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ \n @@@@@ @@@@@@@@@@@@@@@@@@ \n \nAppKit SDK version ${e} is outdated. Latest version is ${t}. Please update to the latest version for bug fixes and new features.\n \nChangelog: https://github.com/reown-com/appkit/releases\nNPM Registry: https://www.npmjs.com/package/@reown/appkit`},TS={ConnectorExplorerIds:{[B.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[B.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[B.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[B.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[B.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[B.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[OS.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[OS.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[OS.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[OS.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[OS.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[OS.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[OS.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[OS.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[OS.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[OS.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[OS.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[OS.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[OS.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600","0x2b6653dc":"3502bb86-cc4e-420f-a387-59ea63a28b00","0x94a9059e":"3502bb86-cc4e-420f-a387-59ea63a28b00","0xcd8690dc":"3502bb86-cc4e-420f-a387-59ea63a28b00"},ConnectorImageIds:{[B.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[B.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[B.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[B.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[B.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[B.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[B.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[B.CONNECTOR_ID.INJECTED]:"Browser Wallet",[B.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[B.CONNECTOR_ID.COINBASE]:"Coinbase",[B.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[B.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[B.CONNECTOR_ID.LEDGER]:"Ledger",[B.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[B.CONNECTOR_ID.INJECTED]:"INJECTED",[B.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[B.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[B.CONNECTOR_ID.AUTH]:"AUTH",[OS.CONNECTOR_TYPE_AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},kS={getCaipTokens(e){if(!e)return;const t={};return Object.entries(e).forEach((([e,s])=>{t[`${OS.EIP155}:${e}`]=s})),t},isLowerCaseMatch:(e,t)=>e?.toLowerCase()===t?.toLowerCase(),getActiveNamespaceConnectedToAuth(){const e=Qs.state.activeChain;return B.AUTH_CONNECTOR_SUPPORTED_CHAINS.find((t=>bs.getConnectorId(t)===B.CONNECTOR_ID.AUTH&&t===e))},withRetry({conditionFn:e,intervalMs:t,maxRetries:s}){let n=0;return new Promise((r=>{!async function i(){return n+=1,await e()?r(!0):n>=s?r(!1):(setTimeout(i,t),null)}()}))},userChainIdToChainNamespace(e){if("number"==typeof e)return B.CHAIN.EVM;const[t]=e.split(":");return t},getOtherAuthNamespaces(e){if(!e)return[];const t=B.AUTH_CONNECTOR_SUPPORTED_CHAINS.filter((t=>t!==e));return t},getConnectorStorageInfo(e,t){const s=We.getConnections()[t]??[];return{hasDisconnected:We.isConnectorDisconnected(e,t),hasConnected:s.some((t=>kS.isLowerCaseMatch(t.connectorId,e)))}}},PS={EmbeddedWalletAbortController:new AbortController,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"ORIGIN_NOT_ALLOWED"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{code:"APKT001",displayMessage:"Network Not Found",debugMessage:"The specified network is not recognized. Please ensure it is included in the `networks` array of your `createAppKit` configuration."},ORIGIN_NOT_ALLOWED:{code:"APKT002",displayMessage:"Invalid App Configuration",debugMessage:()=>`The origin ${pe()?window.origin:"unknown"} is not in your allow list. Please update your allowed domains at https://dashboard.reown.com. [PID: ${kt.state.projectId}]`},IFRAME_LOAD_FAILED:{code:"APKT003",displayMessage:"Network Error: Wallet Load Failed",debugMessage:()=>"Failed to load the embedded wallet. This may be due to network issues or server downtime. Please check your network connection and try again shortly. Contact support if the issue persists."},IFRAME_REQUEST_TIMEOUT:{code:"APKT004",displayMessage:"Wallet Request Timeout",debugMessage:()=>"The request to the embedded wallet timed out. Please check your network connection and try again shortly. Contact support if the issue persists."},UNVERIFIED_DOMAIN:{code:"APKT005",displayMessage:"Unverified Domain",debugMessage:()=>"Embedded wallet load failed. Ensure your domain is verified in https://dashboard.reown.com."},JWT_TOKEN_NOT_VALID:{code:"APKT006",displayMessage:"Session Expired",debugMessage:"Your session is invalid or expired. Please check your system’s date and time settings, then reconnect."},INVALID_PROJECT_ID:{code:"APKT007",displayMessage:"Invalid Project ID",debugMessage:"The specified project ID is invalid. Please visit https://dashboard.reown.com to obtain a valid project ID."},PROJECT_ID_NOT_CONFIGURED:{code:"APKT008",displayMessage:"Project ID Missing",debugMessage:"No project ID is configured. You can create and configure a project ID at https://dashboard.reown.com."},SERVER_ERROR_APP_CONFIGURATION:{code:"APKT009",displayMessage:"Server Error",debugMessage:e=>`Unable to fetch App Configuration. ${e}. Please check your network connection and try again shortly. Contact support if the issue persists.`},RATE_LIMITED_APP_CONFIGURATION:{code:"APKT010",displayMessage:"Rate Limited",debugMessage:"You have been rate limited while retrieving App Configuration. Please wait a few minutes and try again. Contact support if the issue persists."}},ALERT_WARNINGS:{LOCAL_CONFIGURATION_IGNORED:{debugMessage:e=>`[Reown Config Notice] ${e}`},INACTIVE_NAMESPACE_NOT_CONNECTED:{code:"APKTW001",displayMessage:"Inactive Namespace Not Connected",debugMessage:(e,t)=>`An error occurred while connecting an inactive namespace ${e}: "${t}"`},INVALID_EMAIL:{code:"APKTW002",displayMessage:"Invalid Email Address",debugMessage:"Please enter a valid email address"}}},xS={TOKEN_ADDRESSES_BY_SYMBOL:{USDC:{8453:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",84532:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"}},getTokenSymbolByAddress(e){if(!e)return;const[t]=Object.entries(xS.TOKEN_ADDRESSES_BY_SYMBOL).find((([t,s])=>Object.values(s).includes(e)))??[];return t}};var RS={exports:{}};function US(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var LS=function(e,t,s){var n=s&&s.stringify||US;if("object"==typeof e&&null!==e){var r=t.length+1;if(1===r)return e;var i=new Array(r);i[0]=n(e);for(var o=1;o<r;o++)i[o]=n(t[o]);return i.join(" ")}if("string"!=typeof e)return e;var a=t.length;if(0===a)return e;for(var c="",l=0,d=-1,h=e&&e.length||0,u=0;u<h;){if(37===e.charCodeAt(u)&&u+1<h){switch(d=d>-1?d:0,e.charCodeAt(u+1)){case 100:case 102:if(l>=a||null==t[l])break;d<u&&(c+=e.slice(d,u)),c+=Number(t[l]),d=u+2,u++;break;case 105:if(l>=a||null==t[l])break;d<u&&(c+=e.slice(d,u)),c+=Math.floor(Number(t[l])),d=u+2,u++;break;case 79:case 111:case 106:if(l>=a||void 0===t[l])break;d<u&&(c+=e.slice(d,u));var p=typeof t[l];if("string"===p){c+="'"+t[l]+"'",d=u+2,u++;break}if("function"===p){c+=t[l].name||"<anonymous>",d=u+2,u++;break}c+=n(t[l]),d=u+2,u++;break;case 115:if(l>=a)break;d<u&&(c+=e.slice(d,u)),c+=String(t[l]),d=u+2,u++;break;case 37:d<u&&(c+=e.slice(d,u)),c+="%",d=u+2,u++,l--}++l}++u}return-1===d?e:(d<h&&(c+=e.slice(d)),c)};const DS=LS;RS.exports=HS;const MS=function(){function e(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return e(self)||e(window)||e(this)||{}}}().console||{},BS={mapHttpRequest:YS,mapHttpResponse:YS,wrapRequestSerializer:XS,wrapResponseSerializer:XS,wrapErrorSerializer:XS,req:YS,res:YS,err:GS,errWithCause:GS};function jS(e,t){return"silent"===e?1/0:t.levels.values[e]}const $S=Symbol("pino.logFuncs"),FS=Symbol("pino.hierarchy"),qS={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function WS(e,t){const s={logger:t,parent:e[FS]};t[FS]=s}function HS(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const s=e.browser.write||MS;e.browser.write&&(e.browser.asObject=!0);const n=e.serializers||{},r=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,n);let i=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(i=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);"function"==typeof s&&a.forEach((function(e){s[e]=s})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",l=Object.create(s);l.log||(l.log=ZS),function(e,t,s){const n={};t.forEach((e=>{n[e]=s[e]?s[e]:MS[e]||MS[qS[e]||"log"]||ZS})),e[$S]=n}(l,a,s),WS({},l),Object.defineProperty(l,"levelVal",{get:function(){return jS(this.level,this)}}),Object.defineProperty(l,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,zS(this,d,l,"error"),zS(this,d,l,"fatal"),zS(this,d,l,"warn"),zS(this,d,l,"info"),zS(this,d,l,"debug"),zS(this,d,l,"trace"),o.forEach((e=>{zS(this,d,l,e)}))}});const d={transmit:t,serialize:r,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:JS(e),messageKey:e.messageKey||"msg",onChild:e.onChild||ZS};function h(s,i,o){if(!i)throw new Error("missing bindings for child Pino");o=o||{},r&&i.serializers&&(o.serializers=i.serializers);const a=o.serializers;if(r&&a){var c=Object.assign({},n,a),l=!0===e.browser.serialize?Object.keys(c):r;delete i.serializers,VS([i],l,c,this._stdErrSerialize)}function d(e){this._childLevel=1+(0|e._childLevel),this.bindings=i,c&&(this.serializers=c,this._serialize=l),t&&(this._logEvent=KS([].concat(e._logEvent.bindings,i)))}d.prototype=this;const u=new d(this);return WS(this,u),u.child=function(...e){return h.call(this,s,...e)},u.level=o.level||this.level,s.onChild(u),u}return l.levels=function(e){const t=e.customLevels||{},s=Object.assign({},HS.levels.values,t),n=Object.assign({},HS.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(s){t[e[s]]=s})),t}(t));return{values:s,labels:n}}(e),l.level=c,l.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=ZS,l.serializers=n,l._serialize=r,l._stdErrSerialize=i,l.child=function(...e){return h.call(this,d,...e)},t&&(l._logEvent=KS()),l}function zS(e,t,s,n){if(Object.defineProperty(e,n,{value:jS(e.level,s)>jS(n,s)?ZS:s[$S][n],writable:!0,enumerable:!0,configurable:!0}),e[n]===ZS){if(!t.transmit)return;const r=jS(t.transmit.level||e.level,s);if(jS(n,s)<r)return}e[n]=function(e,t,s,n){return function(r){return function(){const i=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===MS?MS:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(t.serialize&&(VS(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),t.asObject||t.formatters?r.call(a,...function(e,t,s,n,r){const{level:i,log:o=(e=>e)}=r.formatters||{},a=s.slice();let c=a[0];const l={};let d=1+(0|e._childLevel);if(d<1&&(d=1),n&&(l.time=n),i){const s=i(t,e.levels.values[t]);Object.assign(l,s)}else l.level=e.levels.values[t];if(r.asObjectBindingsOnly){if(null!==c&&"object"==typeof c)for(;d--&&"object"==typeof a[0];)Object.assign(l,a.shift());return[o(l),...a]}if(null!==c&&"object"==typeof c){for(;d--&&"object"==typeof a[0];)Object.assign(l,a.shift());c=a.length?DS(a.shift(),a):void 0}else"string"==typeof c&&(c=DS(a.shift(),a));return void 0!==c&&(l[r.messageKey]=c),[o(l)]}(this,n,o,i,t)):r.apply(a,o),t.transmit){const r=t.transmit.level||e._level,a=jS(r,s),c=jS(n,s);if(c<a)return;!function(e,t,s,n=!1){const r=t.send,i=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,l=e._logEvent.bindings;n||VS(s,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=i,e._logEvent.messages=s.filter((function(e){return-1===l.indexOf(e)})),e._logEvent.level.label=o,e._logEvent.level.value=a,r(o,e._logEvent,c),e._logEvent=KS(l)}(this,{ts:i,methodLevel:n,methodValue:c,transmitLevel:r,transmitValue:s.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:jS(e._level,s)},o,l)}}}(e[$S][n])}(e,t,s,n);const r=function(e){const t=[];e.bindings&&t.push(e.bindings);let s=e[FS];for(;s.parent;)s=s.parent,s.logger.bindings&&t.push(s.logger.bindings);return t.reverse()}(e);0!==r.length&&(e[n]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(r,e[n]))}function VS(e,t,s,n){for(const r in e)if(n&&e[r]instanceof Error)e[r]=HS.stdSerializers.err(e[r]);else if("object"==typeof e[r]&&!Array.isArray(e[r])&&t)for(const n in e[r])t.indexOf(n)>-1&&n in s&&(e[r][n]=s[n](e[r][n]))}function KS(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function GS(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const s in e)void 0===t[s]&&(t[s]=e[s]);return t}function JS(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?QS:e_}function YS(){return{}}function XS(e){return e}function ZS(){}function QS(){return!1}function e_(){return Date.now()}HS.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},HS.stdSerializers=BS,HS.stdTimeFunctions=Object.assign({},{nullTime:QS,epochTime:e_,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),RS.exports.default=HS,RS.exports.pino=HS;const t_="info",s_=1024e3;var n_=Object.defineProperty,r_=(e,t,s)=>((e,t,s)=>t in e?n_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class i_{constructor(e){r_(this,"nodeValue"),r_(this,"sizeInBytes"),r_(this,"next"),this.nodeValue=e,this.sizeInBytes=(new TextEncoder).encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class o_{constructor(e){r_(this,"lengthInNodes"),r_(this,"sizeInBytes"),r_(this,"head"),r_(this,"tail"),r_(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new i_(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;null!==t;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}}function a_(e){return"string"==typeof e?e:(e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t)))(e)||""}var c_=Object.defineProperty,l_=(e,t,s)=>((e,t,s)=>t in e?c_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class d_{constructor(e,t=s_){l_(this,"logs"),l_(this,"level"),l_(this,"levelValue"),l_(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=RS.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new o_(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===RS.exports.levels.values.error?console.error(e):t===RS.exports.levels.values.warn?console.warn(e):t===RS.exports.levels.values.debug?console.debug(e):t===RS.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(a_({timestamp:(new Date).toISOString(),log:e}));const t="string"==typeof e?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new o_(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(a_({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var h_=Object.defineProperty,u_=(e,t,s)=>((e,t,s)=>t in e?h_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class p_{constructor(e,t=s_){u_(this,"baseChunkLogger"),this.baseChunkLogger=new d_(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),s=document.createElement("a");s.href=t,s.download=`walletconnect-logs-${(new Date).toISOString()}.txt`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)}}var f_=Object.defineProperty,g_=(e,t,s)=>((e,t,s)=>t in e?f_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class m_{constructor(e,t=s_){g_(this,"baseChunkLogger"),this.baseChunkLogger=new d_(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var y_=Object.defineProperty,w_=Object.defineProperties,b_=Object.getOwnPropertyDescriptors,v_=Object.getOwnPropertySymbols,E_=Object.prototype.hasOwnProperty,C_=Object.prototype.propertyIsEnumerable,N_=(e,t,s)=>t in e?y_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,A_=(e,t)=>{for(var s in t||(t={}))E_.call(t,s)&&N_(e,s,t[s]);if(v_)for(var s of v_(t))C_.call(t,s)&&N_(e,s,t[s]);return e},I_=(e,t)=>w_(e,b_(t));function S_(e){var t;if(typeof e.loggerOverride<"u"&&"string"!=typeof e.loggerOverride)return{logger:e.loggerOverride,chunkLoggerController:null};const s=I_(A_({},e.opts),{level:"string"==typeof e.loggerOverride?e.loggerOverride:null==(t=e.opts)?void 0:t.level});return typeof window<"u"?function(e){var t,s;const n=new p_(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:RS.exports(I_(A_({},e.opts),{level:"trace",browser:I_(A_({},null==(s=e.opts)?void 0:s.browser),{write:e=>n.write(e)})})),chunkLoggerController:n}}(I_(A_({},e),{opts:s})):function(e){var t,s;const n=new m_(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:RS.exports(I_(A_({},e.opts),{level:"trace",browser:I_(A_({},null==(s=e.opts)?void 0:s.browser),{write:e=>n.write(e)})}),n),chunkLoggerController:n}}(I_(A_({},e),{opts:s}))}const __={createLogger(e,t="error"){const s=function(e){return I_(A_({},e),{level:e?.level||t_})}({level:t}),{logger:n}=S_({opts:s});return n.error=(...t)=>{for(const s of t)if(s instanceof Error)return void e(s,...t);e(void 0,...t)},n}},O_="2.56.3";let T_=({docsBaseUrl:e,docsPath:t="",docsSlug:s})=>t?`${e??"https://viem.sh"}${t}${s?`#${s}`:""}`:void 0,k_=`viem@${O_}`;class P_ extends Error{constructor(e,t={}){const s=t.cause instanceof P_?t.cause.details:t.cause?.message?t.cause.message:t.details,n=t.cause instanceof P_&&t.cause.docsPath||t.docsPath,r=T_?.({...t,docsPath:n});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...r?[`Docs: ${r}`]:[],...s?[`Details: ${s}`]:[],...k_?[`Version: ${k_}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=n,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=O_}walk(e){return x_(this,e)}}function x_(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?x_(e.cause,t):t?null:e}class R_ extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&(super.delete(e),super.set(e,t)),t}set(e,t){if(super.has(e)&&super.delete(e),super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=super.keys().next().value;void 0!==e&&super.delete(e)}return this}}const U_=(e,t,s)=>JSON.stringify(e,((e,s)=>{const n="bigint"==typeof s?s.toString():s;return"function"==typeof t?t(e,n):n}),s);function L_(e){if(e?.reason)return e.reason;if("function"==typeof DOMException)return new DOMException("This operation was aborted","AbortError");const t=new Error("This operation was aborted");return t.name="AbortError",t}function D_(e){return"object"==typeof e&&null!==e&&"name"in e&&"AbortError"===e.name}const M_=e=>{try{const t=new URL(e);return t.username||t.password?(t.username="",t.password="",t.toString()):e}catch{return e}};class B_ extends P_{constructor({body:e,cause:t,details:s,headers:n,status:r,url:i}){super("HTTP request failed.",{cause:t,details:s,metaMessages:[r&&`Status: ${r}`,`URL: ${M_(i)}`,e&&`Request body: ${U_(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=n,this.status=r,this.url=i}}class j_ extends P_{constructor({maxSize:e,size:t}){super("HTTP response body exceeded the size limit.",{metaMessages:[`Max: ${e} bytes`,`Received: ${t} bytes`],name:"ResponseBodyTooLargeError"}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e,this.size=t}}class $_ extends P_{constructor({body:e,error:t,url:s}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${M_(s)}`,`Request body: ${U_(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=t.code,this.data=t.data,this.url=s}}class F_ extends P_{constructor({body:e,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${M_(t)}`,`Request body: ${U_(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}}class q_ extends P_{constructor(e,{code:t,docsPath:s,metaMessages:n,name:r,shortMessage:i}){super(i,{cause:e,docsPath:s,metaMessages:n||e?.metaMessages,name:r||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r||e.name,this.code=e instanceof $_?e.code:t??-1}}class W_ extends q_{constructor(e,t){super(e,t),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}}class H_ extends q_{constructor(e){super(e,{code:H_.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(H_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class z_ extends q_{constructor(e){super(e,{code:z_.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(z_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class V_ extends q_{constructor(e,{method:t}={}){super(e,{code:V_.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}}Object.defineProperty(V_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class K_ extends q_{constructor(e){super(e,{code:K_.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join("\n")})}}Object.defineProperty(K_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class G_ extends q_{constructor(e){super(e,{code:G_.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(G_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class J_ extends q_{constructor(e){super(e,{code:J_.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join("\n")})}}Object.defineProperty(J_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Y_ extends q_{constructor(e){super(e,{code:Y_.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Y_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class X_ extends q_{constructor(e){super(e,{code:X_.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(X_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Z_ extends q_{constructor(e){super(e,{code:Z_.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Z_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Q_ extends q_{constructor(e,{method:t}={}){super(e,{code:Q_.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(Q_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class eO extends q_{constructor(e){super(e,{code:eO.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(eO,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class tO extends q_{constructor(e){super(e,{code:tO.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(tO,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class sO extends W_{constructor(e){super(e,{code:sO.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(sO,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class nO extends W_{constructor(e){super(e,{code:nO.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(nO,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class rO extends W_{constructor(e,{method:t}={}){super(e,{code:rO.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(rO,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class iO extends W_{constructor(e){super(e,{code:iO.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(iO,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class oO extends W_{constructor(e){super(e,{code:oO.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(oO,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class aO extends W_{constructor(e){super(e,{code:aO.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(aO,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class cO extends W_{constructor(e){super(e,{code:cO.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(cO,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class lO extends W_{constructor(e){super(e,{code:lO.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(lO,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class dO extends W_{constructor(e){super(e,{code:dO.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(dO,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class hO extends W_{constructor(e){super(e,{code:hO.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(hO,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class uO extends W_{constructor(e){super(e,{code:uO.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(uO,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class pO extends W_{constructor(e){super(e,{code:pO.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(pO,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class fO extends W_{constructor(e){super(e,{code:fO.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(fO,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class gO extends W_{constructor(e){super(e,{code:gO.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}}Object.defineProperty(gO,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});class mO extends q_{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}class yO extends P_{constructor({cause:e,message:t}={}){const s=t?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${s?`with reason: ${s}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(yO,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(yO,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});const wO=new Map;function bO({fn:e,id:t,shouldSplitBatch:s,wait:n=0,sort:r}){const i=async()=>{const t=a();o();const s=t.map((({args:e})=>e));0!==s.length&&e(s).then((e=>{r&&Array.isArray(e)&&e.sort(r);for(let s=0;s<t.length;s++){const{resolve:n}=t[s];n?.([e[s],e])}})).catch((e=>{for(let s=0;s<t.length;s++){const{reject:n}=t[s];n?.(e)}}))},o=()=>wO.delete(t),a=()=>wO.get(t)||[],c=e=>wO.set(t,[...a(),e]);return{flush:o,async schedule(e){const{promise:t,resolve:r,reject:o}=function(){let e=()=>{},t=()=>{};return{promise:new Promise(((s,n)=>{e=s,t=n})),resolve:e,reject:t}}(),l=s?.([...a().map((({args:e})=>e)),e]);l&&i();return a().length>0?(c({args:e,resolve:r,reject:o}),t):(c({args:e,resolve:r,reject:o}),setTimeout(i,n),t)}}}async function vO(e,{signal:t}={}){return new Promise(((s,n)=>{if(t?.aborted)return void n(L_(t));const r=()=>t?.removeEventListener("abort",o),i=setTimeout((()=>{r(),s()}),e),o=()=>{clearTimeout(i),r(),n(L_(t))};t?.addEventListener("abort",o,{once:!0})}))}function EO(e,{delay:t=100,retryCount:s=2,shouldRetry:n=(()=>!0),signal:r}={}){return new Promise(((i,o)=>{const a=async({count:c=0}={})=>{if(r?.aborted)return void o(L_(r));try{const t=await e();i(t)}catch(e){if(r?.aborted)return void o(L_(r));if(D_(e))return void o(e);if(c<s&&await n({count:c,error:e}))return(async({error:e})=>{const s="function"==typeof t?t({count:c,error:e}):t;if(s)try{await vO(s,{signal:r})}catch(e){return void o(e)}return a({count:c+1})})({error:e});o(e)}};a().catch(o)}))}const CO=256;let NO,AO=CO;const IO=new R_(8192);function SO(e,t={}){return async(s,n={})=>{const{dedupe:r=!1,methods:i,retryDelay:o=150,retryCount:a=3,signal:c,uid:l}={...t,...n},{method:d}=s;if(i?.exclude?.includes(d))throw new Q_(new Error("method not supported"),{method:d});if(i?.include&&!i.include.includes(d))throw new Q_(new Error("method not supported"),{method:d});if(c?.aborted)throw L_(c);const h=r?function(e,t=0){let s=3735928559^t,n=1103547991^t;for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);s=Math.imul(s^r,2654435761),n=Math.imul(n^r,1597334677)}return s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(n^n>>>16,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(s^s>>>16,3266489909),(4294967296*(2097151&n)+(s>>>0)).toString(36)}(`${l}.${U_(s)}`):void 0;return function(e,{enabled:t=!0,id:s}){if(!t||!s)return e();if(IO.get(s))return IO.get(s);const n=e().finally((()=>IO.delete(s)));return IO.set(s,n),n}((()=>EO((async()=>{try{return await e(s,c?{signal:c}:void 0)}catch(e){if(c?.aborted)throw L_(c);if(D_(e))throw e;const t=e;switch(t.code){case H_.code:throw new H_(t);case z_.code:throw new z_(t);case V_.code:throw new V_(t,{method:s.method});case K_.code:throw new K_(t);case G_.code:throw new G_(t);case J_.code:throw new J_(t);case Y_.code:throw new Y_(t);case X_.code:throw new X_(t);case Z_.code:throw new Z_(t);case Q_.code:throw new Q_(t,{method:s.method});case eO.code:throw new eO(t);case tO.code:throw new tO(t);case sO.code:throw new sO(t);case nO.code:throw new nO(t);case rO.code:throw new rO(t);case iO.code:throw new iO(t);case oO.code:throw new oO(t);case aO.code:throw new aO(t);case cO.code:throw new cO(t);case lO.code:throw new lO(t);case dO.code:throw new dO(t);case hO.code:throw new hO(t);case uO.code:throw new uO(t);case pO.code:throw new pO(t);case fO.code:throw new fO(t);case 5e3:throw new sO(t);case gO.code:throw new gO(t);default:if(e instanceof P_)throw e;throw new mO(t)}}}),{delay:({count:e,error:t})=>{if(t&&t instanceof B_){const e=t?.headers?.get("Retry-After");if(e?.match(/\d/))return 1e3*Number.parseInt(e,10)}return~~(1<<e)*o},retryCount:a,signal:c,shouldRetry:({error:e})=>function(e){if(D_(e))return!1;if("code"in e&&"number"==typeof e.code)return-1===e.code||(e.code===eO.code||(e.code===G_.code||429===e.code));if(e instanceof B_&&e.status)return 403===e.status||(408===e.status||(413===e.status||(429===e.status||(500===e.status||(502===e.status||(503===e.status||504===e.status))))));return!0}(e)})),{enabled:r,id:h})}}function _O(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const OO=_O(),TO=10485760;function kO(e,t={}){const{url:s,headers:n}=function(e){try{const t=new URL(e),s=(()=>{if(t.username){const e=`${decodeURIComponent(t.username)}:${decodeURIComponent(t.password)}`;return t.username="",t.password="",{url:t.toString(),headers:{Authorization:`Basic ${btoa(e)}`}}}})();return{url:t.toString(),...s}}catch{return{url:e}}}(e);return{async request(e){const{body:r,fetchFn:i=t.fetchFn??fetch,maxResponseBodySize:o=t.maxResponseBodySize??TO,onRequest:a=t.onRequest,onResponse:c=t.onResponse,timeout:l=t.timeout??1e4}=e,d={...t.fetchOptions??{},...e.fetchOptions??{}},{headers:h,method:u,signal:p}=d;try{const e=await function(e,{errorInstance:t=new Error("timed out"),timeout:s,signal:n}){return new Promise(((r,i)=>{(async()=>{let o;const a=new AbortController;try{s>0&&(o=setTimeout((()=>{n?a.abort():i(t)}),s)),r(await e({signal:a?.signal||null}))}catch(e){if(a?.signal.aborted&&D_(e))return void i(t);i(e)}finally{clearTimeout(o)}})()}))}((async({signal:e})=>{const t={...d,body:Array.isArray(r)?U_(r.map((e=>({jsonrpc:"2.0",id:e.id??OO.take(),...e})))):U_({jsonrpc:"2.0",id:r.id??OO.take(),...r}),headers:{...n,"Content-Type":"application/json",...h},method:u||"POST",signal:p||(l>0?e:null)},o=new Request(s,t),c=await(a?.(o,t))??{...t,url:s};return await i(c.url??s,c)}),{errorInstance:new F_({body:r,url:s}),timeout:l,signal:!0});let t;c&&await c(e);const f=await async function(e,{maxResponseBodySize:t}){if(!1===t)return e.text();const s=e.headers.get("Content-Length");if(s){const e=Number(s);if(e>t)throw new j_({maxSize:t,size:e})}if(!e.body){const s=await e.text(),n=(new TextEncoder).encode(s).length;if(n>t)throw new j_({maxSize:t,size:n});return s}const n=e.body.getReader(),r=new TextDecoder;let i="",o=0;try{for(;;){const{done:e,value:s}=await n.read();if(e)break;if(o+=s.byteLength,o>t)throw await n.cancel(),new j_({maxSize:t,size:o});i+=r.decode(s,{stream:!0})}return i+=r.decode(),i}finally{n.releaseLock()}}(e,{maxResponseBodySize:o});if(e.headers.get("Content-Type")?.startsWith("application/json"))t=JSON.parse(f);else{t=f;try{t=JSON.parse(t||"{}")}catch(s){if(e.ok)throw s;t={error:t}}}if(!e.ok){if("number"==typeof t.error?.code&&"string"==typeof t.error?.message)return t;throw new B_({body:r,details:U_(t.error)||e.statusText,headers:e.headers,status:e.status,url:s})}return t}catch(e){if(p?.aborted)throw L_(p);if(D_(e))throw e;if(e instanceof B_)throw e;if(e instanceof j_)throw e;if(e instanceof F_)throw e;throw new B_({body:r,cause:e,url:s})}}}}function PO({key:e,methods:t,name:s,request:n,retryCount:r=3,retryDelay:i=150,timeout:o,type:a},c){const l=function(e=11){if(!NO||AO+e>2*CO){NO="",AO=0;for(let e=0;e<CO;e++)NO+=(256+256*Math.random()|0).toString(16).substring(1)}return NO.substring(AO,AO+++e)}();return{config:{key:e,methods:t,name:s,request:n,retryCount:r,retryDelay:i,timeout:o,type:a},request:SO(n,{methods:t,retryCount:r,retryDelay:i,uid:l}),value:c}}function xO(e,t={}){const{key:s="fallback",name:n="Fallback",rank:r=!1,shouldThrow:i=RO,retryCount:o,retryDelay:a}=t;return({chain:t,pollingInterval:c=4e3,timeout:l,...d})=>{let h=e,u=()=>{};const p=PO({key:s,name:n,async request({method:e,params:s}){let n;const r=async(o=0)=>{const a=h[o]({...d,chain:t,retryCount:0,timeout:l});try{const t=await a.request({method:e,params:s});return u({method:e,params:s,response:t,transport:a,status:"success"}),t}catch(c){if(u({error:c,method:e,params:s,transport:a,status:"error"}),i(c))throw c;if(o===h.length-1)throw c;if(n??=h.slice(o+1).some((s=>{const{include:n,exclude:r}=s({chain:t}).config.methods||{};return n?n.includes(e):!r||!r.includes(e)})),!n)throw c;return r(o+1)}};return r()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:e=>u=e,transports:h.map((e=>e({chain:t,retryCount:0})))});if(r){const e="object"==typeof r?r:{};!function({chain:e,interval:t=4e3,onTransports:s,ping:n,sampleCount:r=10,timeout:i=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,d=[],h=async()=>{const a=await Promise.all(o.map((async t=>{const s=t({chain:e,retryCount:0,timeout:i}),r=Date.now();let o,a;try{await(n?n({transport:s}):s.request({method:"net_listening"})),a=1}catch{a=0}finally{o=Date.now()}return{latency:o-r,success:a}})));d.push(a),d.length>r&&d.shift();const u=Math.max(...d.map((e=>Math.max(...e.map((({latency:e})=>e)))))),p=o.map(((e,t)=>{const s=d.map((e=>e[t].latency)),n=1-s.reduce(((e,t)=>e+t),0)/s.length/u,r=d.map((e=>e[t].success)),i=r.reduce(((e,t)=>e+t),0)/r.length;return 0===i?[0,t]:[l*n+c*i,t]})).sort(((e,t)=>t[0]-e[0]));s(p.map((([,e])=>o[e]))),await vO(t),h()};h()}({chain:t,interval:e.interval??c,onTransports:e=>h=e,ping:e.ping,sampleCount:e.sampleCount,timeout:e.timeout,transports:h,weights:e.weights})}return p}}function RO(e){return!(!("code"in e)||"number"!=typeof e.code||e.code!==Z_.code&&e.code!==sO.code&&e.code!==gO.code&&!yO.nodeMessage.test(e.message)&&5e3!==e.code)}class UO extends P_{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}let LO=0;const DO=new WeakMap;function MO(e){if(!e)return"default";const t=DO.get(e);if(void 0!==t)return t;const s=LO++;return DO.set(e,s),s}function BO(e,t={}){const{batch:s,fetchFn:n,fetchOptions:r,key:i="http",maxResponseBodySize:o,methods:a,name:c="HTTP JSON-RPC",onFetchRequest:l,onFetchResponse:d,retryDelay:h,raw:u}=t;return({chain:p,retryCount:f,timeout:g})=>{const{batchSize:m=1e3,wait:y=0}="object"==typeof s?s:{},w=t.retryCount??f,b=g??t.timeout??1e4,v=e||p?.rpcUrls.default.http[0];if(!v)throw new UO;const E=kO(v,{fetchFn:n,fetchOptions:r,maxResponseBodySize:o,onRequest:l,onResponse:d,timeout:b});return PO({key:i,methods:a,name:c,async request({method:e,params:t},n){const r={method:e,params:t},i=n?.signal?{signal:n.signal}:void 0,{schedule:o}=bO({id:`${v}.${MO(n?.signal)}`,wait:y,shouldSplitBatch:e=>e.length>m,fn:e=>E.request({body:e,fetchOptions:i}),sort:(e,t)=>e.id-t.id}),[{error:a,result:c}]=await(async e=>s?o(e):[await E.request({body:e,fetchOptions:i})])(r);if(u)return{error:a,result:c};if(a)throw new $_({body:r,error:a,url:v});return c},retryCount:w,retryDelay:h,timeout:b,type:"http"},{fetchOptions:r,url:v})}}function jO(e,t){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",e),s.searchParams.set("projectId",t),s.toString()}const $O=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","eip155:80094","eip155:80069","eip155:560048","eip155:31","eip155:2818","eip155:57054","eip155:911867","eip155:534351","eip155:1112","eip155:534352","eip155:1111","eip155:146","eip155:130","eip155:1284","eip155:30","eip155:2810","eip155:55931","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],FO={extendRpcUrlWithProjectId(e,t){let s=!1;try{s="rpc.walletconnect.org"===new URL(e).host}catch(e){s=!1}if(s){const s=new URL(e);return s.searchParams.has("projectId")||s.searchParams.set("projectId",t),s.toString()}return e},isCaipNetwork:e=>"chainNamespace"in e&&"caipNetworkId"in e,getChainNamespace(e){return this.isCaipNetwork(e)?e.chainNamespace:B.CHAIN.EVM},getCaipNetworkId(e){return this.isCaipNetwork(e)?e.caipNetworkId:`${B.CHAIN.EVM}:${e.id}`},getDefaultRpcUrl(e,t,s){const n=e.rpcUrls?.default?.http?.[0];return $O.includes(t)?jO(t,s):n||""},extendCaipNetwork(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:n}){const r=this.getChainNamespace(e),i=this.getCaipNetworkId(e),o=e.rpcUrls?.default?.http?.[0],a=this.getDefaultRpcUrl(e,i,s),c=e?.rpcUrls?.chainDefault?.http?.[0]||o,l=n?.[i]?.map((e=>e.url))||[],d=[...l,...a?[a]:[]],h=[...l];return c&&!h.includes(c)&&h.push(c),{...e,chainNamespace:r,caipNetworkId:i,assets:{imageId:TS.NetworkImageIds[e.id],imageUrl:t?.[e.id]},rpcUrls:{...e.rpcUrls,default:{http:d},chainDefault:{http:h}}}},extendCaipNetworks:(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:n})=>e.map((e=>FO.extendCaipNetwork(e,{customNetworkImageUrls:t,customRpcUrls:n,projectId:s}))),getViemTransport(e,t,s){const n=[];return s?.forEach((e=>{n.push(BO(e.url,e.config))})),$O.includes(e.caipNetworkId)&&n.push(BO(jO(e.caipNetworkId,t),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),e?.rpcUrls?.default?.http?.forEach((e=>{n.push(BO(e))})),xO(n)},extendWagmiTransports(e,t,s){if($O.includes(e.caipNetworkId)){return xO([s,BO(this.getDefaultRpcUrl(e,e.caipNetworkId,t))])}return s},getUnsupportedNetwork:e=>({id:e.split(":")[1],caipNetworkId:e,name:B.UNSUPPORTED_NETWORK_NAME,chainNamespace:e.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}),getCaipNetworkFromStorage(e){const t=We.getActiveCaipNetworkId(),s=Qs.getAllRequestedCaipNetworks(),n=Array.from(Qs.state.chains?.keys()||[]),r=t?.split(":")[0],i=!!r&&n.includes(r),o=s?.find((e=>e.caipNetworkId===t));return i&&!o&&t?this.getUnsupportedNetwork(t):o||(e||s?.[0])}};var qO=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");const t=new Uint8Array(256);for(let e=0;e<t.length;e++)t[e]=255;for(let s=0;s<e.length;s++){const n=e.charAt(s),r=n.charCodeAt(0);if(255!==t[r])throw new TypeError(n+" is ambiguous");t[r]=s}const s=e.length,n=e.charAt(0),r=Math.log(s)/Math.log(256),i=Math.log(256)/Math.log(s);function o(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let i=0,o=0,a=0;for(;e[i]===n;)o++,i++;const c=(e.length-i)*r+1>>>0,l=new Uint8Array(c);for(;i<e.length;){const n=e.charCodeAt(i);if(n>255)return;let r=t[n];if(255===r)return;let o=0;for(let e=c-1;(0!==r||o<a)&&-1!==e;e--,o++)r+=s*l[e]>>>0,l[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw new Error("Non-zero carry");a=o,i++}let d=c-a;for(;d!==c&&0===l[d];)d++;const h=new Uint8Array(o+(c-d));let u=o;for(;d!==c;)h[u++]=l[d++];return h}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";let r=0,o=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,r++;const l=(c-a)*i+1>>>0,d=new Uint8Array(l);for(;a!==c;){let e=t[a],n=0;for(let t=l-1;(0!==e||n<o)&&-1!==t;t--,n++)e+=256*d[t]>>>0,d[t]=e%s>>>0,e=e/s>>>0;if(0!==e)throw new Error("Non-zero carry");o=n,a++}let h=l-o;for(;h!==l&&0===d[h];)h++;let u=n.repeat(r);for(;h<l;++h)u+=e.charAt(d[h]);return u},decodeUnsafe:o,decode:function(e){const t=o(e);if(t)return t;throw new Error("Non-base"+s+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function WO(e){return function(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const HO="2.56.3";let zO=({docsBaseUrl:e,docsPath:t="",docsSlug:s})=>t?`${e??"https://viem.sh"}${t}${s?`#${s}`:""}`:void 0,VO=`viem@${HO}`;class KO extends Error{constructor(e,t={}){const s=t.cause instanceof KO?t.cause.details:t.cause?.message?t.cause.message:t.details,n=t.cause instanceof KO&&t.cause.docsPath||t.docsPath,r=zO?.({...t,docsPath:n});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...r?[`Docs: ${r}`]:[],...s?[`Details: ${s}`]:[],...VO?[`Version: ${VO}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=n,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=HO}walk(e){return GO(this,e)}}function GO(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?GO(e.cause,t):t?null:e}class JO extends KO{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function YO(e,{dir:t,size:s=32}={}){return"string"==typeof e?function(e,{dir:t,size:s=32}={}){if(null===s)return e;const n=e.replace("0x","");if(n.length>2*s)throw new JO({size:Math.ceil(n.length/2),targetSize:s,type:"hex"});return`0x${n["right"===t?"padEnd":"padStart"](2*s,"0")}`}(e,{dir:t,size:s}):function(e,{dir:t,size:s=32}={}){if(null===s)return e;if(e.length>s)throw new JO({size:e.length,targetSize:s,type:"bytes"});const n=new Uint8Array(s);for(let r=0;r<s;r++){const i="right"===t;n[i?r:s-r-1]=e[i?r:e.length-r-1]}return n}(e,{dir:t,size:s})}class XO extends KO{constructor({max:e,min:t,signed:s,size:n,value:r}){super(`Number "${r}" is not in safe ${n?`${8*n}-bit ${s?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class ZO extends KO{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function QO(e,{size:t}){if(WO(e)>t)throw new ZO({givenSize:WO(e),maxSize:t})}const eT=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function tT(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t={}){const{signed:s,size:n}=t,r=BigInt(e);let i;n?i=s?(1n<<8n*BigInt(n)-1n)-1n:2n**(8n*BigInt(n))-1n:"number"==typeof e&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof i&&s?-i-1n:0;if(i&&r>i||r<o){const t="bigint"==typeof e?"n":"";throw new XO({max:i?`${i}${t}`:void 0,min:`${o}${t}`,signed:s,size:n,value:`${e}${t}`})}const a=`0x${(s&&r<0?(1n<<BigInt(8*n))+BigInt(r):r).toString(16)}`;return n?YO(a,{size:n}):a}(e,t):"string"==typeof e?function(e,t={}){const s=nT.encode(e);return sT(s,t)}(e,t):"boolean"==typeof e?function(e,t={}){const s=`0x${Number(e)}`;if("number"==typeof t.size)return QO(s,{size:t.size}),YO(s,{size:t.size});return s}(e,t):sT(e,t)}function sT(e,t={}){let s="";for(let t=0;t<e.length;t++)s+=eT[e[t]];const n=`0x${s}`;return"number"==typeof t.size?(QO(n,{size:t.size}),YO(n,{dir:"right",size:t.size})):n}const nT=new TextEncoder;const rT=4902,iT=5e3,oT=32603;class aT extends VA{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new JA({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{const e=this.getWalletConnectConnector();await e.disconnect(),this.emit("disconnect")}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}return{connections:[]}}syncConnections(){return Promise.resolve()}async writeSolanaTransaction(){return Promise.resolve({hash:""})}async getAccounts({namespace:e}){const t=this.provider,s=(t?.session?.namespaces?.[e]?.accounts||[]).filter(((e,t,s)=>s.indexOf(e)===t));return Promise.resolve({accounts:s.map((t=>He.createAccount({caipAddress:t,type:"bip122"===e?"payment":"eoa"})))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&qe.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};const t=Qs.getAccountData();if(t?.balanceLoading&&e.chainId===Qs.state.activeCaipNetwork?.id)return{balance:t?.balance||"0.00",symbol:t?.balanceSymbol||""};const s=(await Qs.fetchTokenBalance()).find((t=>t.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&t.symbol===e.caipNetwork?.nativeCurrency.symbol));return{balance:s?.quantity.numeric||"0.00",symbol:s?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:t,message:s,address:n}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let r="";if(Qs.state.activeCaipNetwork?.chainNamespace===B.CHAIN.SOLANA){r=(await t.request({method:"solana_signMessage",params:{message:qO.encode((new TextEncoder).encode(s)),pubkey:n}},Qs.state.activeCaipNetwork?.caipNetworkId)).signature}else r=await t.request({method:"personal_sign",params:[s,n]},Qs.state.activeCaipNetwork?.caipNetworkId);return{signature:r}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:t}=e,s=this.getWalletConnectConnector();if(t.chainNamespace===B.CHAIN.EVM)try{await(s.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:tT(t.id)}]}))}catch(e){if(e.code===rT||e.code===oT||e.code===iT||e?.data?.originalError?.code===rT)try{await(s.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:tT(t.id),rpcUrls:[t?.rpcUrls.chainDefault?.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[t.blockExplorers?.default.url]}]}))}catch(e){throw new Error("Chain is not supported")}}s.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find((e=>"WALLET_CONNECT"===e.type)),t=e?.provider;return t}}const cT=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication","headless"],lT={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return Boolean(e.isEnabled)&&t.includes("email")},processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.email:Boolean(e)},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t.filter((e=>"email"!==e))},processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.socials:"boolean"==typeof e?!!e&&qe.DEFAULT_REMOTE_FEATURES.socials:e},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t},processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.swaps:"boolean"==typeof e?!!e&&qe.DEFAULT_REMOTE_FEATURES.swaps:e},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!e?.config)return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t},processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.onramp:"boolean"==typeof e?!!e&&qe.DEFAULT_REMOTE_FEATURES.onramp:e},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.activity:Boolean(e)},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.reownBranding:Boolean(e)},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>e.isEnabled&&(e.config??[]),processFallback:e=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:()=>qe.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:()=>qe.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:()=>qe.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.reownAuthentication:Boolean(e)},headless:{apiFeatureName:"headless",localFeatureName:"headless",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:()=>qe.DEFAULT_REMOTE_FEATURES.headless}},dT={localSettingsOverridden:new Set,getApiConfig:(e,t)=>t?.find((t=>t.id===e)),addWarning(e,t){if(void 0!==e){const e=lT[t],s=e.isLegacy?`"features.${e.localFeatureName}" (now "${t}")`:`"features.${t}"`;this.localSettingsOverridden.add(s)}},processFeature(e,t,s,n,r){const i=lT[e],o=t[i.localFeatureName];if(r&&!i.isAvailableOnBasic)return!1;if(n){const t=this.getApiConfig(i.apiFeatureName,s);return null===t?.config?this.processFallbackFeature(e,o):!!t?.config&&(void 0!==o&&this.addWarning(o,e),this.processApiFeature(e,t))}return this.processFallbackFeature(e,o)},processApiFeature:(e,t)=>lT[e].processApi(t),processFallbackFeature:(e,t)=>lT[e].processFallback(t),async fetchRemoteFeatures(e){const t=e.basic??!1,s=e.features||{};this.localSettingsOverridden.clear();let n=null,r=!1;try{n=await os.fetchProjectConfig(),r=null!=n}catch(e){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",e)}const i=r&&!t?qe.DEFAULT_REMOTE_FEATURES:qe.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const e of cT){const o=this.processFeature(e,s,n,r,t);Object.assign(i,{[e]:o})}}catch(e){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",e),qe.DEFAULT_REMOTE_FEATURES}if(r&&this.localSettingsOverridden.size>0){const e=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;ZA.open({debugMessage:PS.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(e)},"warning")}return i}};class hT{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(e,t)=>{if(e){const s=Qs.getCaipNetworks(e)?.find((e=>e.id===t));if(s)return s;const n=Qs.getNetworkData(e)?.caipNetwork;if(n)return n;const r=Qs.getRequestedCaipNetworks(e);return r.filter((t=>t.chainNamespace===e))?.[0]}return Qs.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const e=this.getCaipNetwork();if(e)return e.id},this.getCaipNetworks=e=>Qs.getCaipNetworks(e),this.getActiveChainNamespace=()=>Qs.state.activeChain,this.setRequestedCaipNetworks=(e,t)=>{Qs.setRequestedCaipNetworks(e,t)},this.getApprovedCaipNetworkIds=()=>Qs.getAllApprovedCaipNetworkIds(),this.getCaipAddress=e=>Qs.state.activeChain!==e&&e?Qs.state.chains.get(e)?.accountState?.caipAddress:Qs.state.activeCaipAddress,this.setClientId=e=>{Mt.setClientId(e)},this.getProvider=e=>Hs.getProvider(e),this.getProviderType=e=>Hs.getProviderId(e),this.getPreferredAccountType=e=>Ns(e),this.setCaipAddress=(e,t,s=!1)=>{Qs.setAccountProp("caipAddress",e,t,s),Qs.setAccountProp("address",He.getPlainAddress(e),t,s)},this.setBalance=(e,t,s)=>{Qs.setAccountProp("balance",e,s),Qs.setAccountProp("balanceSymbol",t,s)},this.setProfileName=(e,t)=>{Qs.setAccountProp("profileName",e,t)},this.setProfileImage=(e,t)=>{Qs.setAccountProp("profileImage",e,t)},this.setUser=(e,t)=>{Qs.setAccountProp("user",e,t)},this.resetAccount=e=>{Qs.resetAccount(e)},this.setCaipNetwork=e=>{Qs.setActiveCaipNetwork(e)},this.setCaipNetworkOfNamespace=(e,t)=>{Qs.setChainNetworkData(t,{caipNetwork:e})},this.setStatus=(e,t)=>{Qs.setAccountProp("status",e,t),bs.isConnected()?We.setConnectionStatus("connected"):We.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=e=>Qs.getAccountData(e)?.address,this.setConnectors=e=>{const t=[...bs.state.allConnectors,...e];bs.setConnectors(t)},this.setConnections=(e,t)=>{We.setConnections(e,t),Us.setConnections(e,t)},this.fetchIdentity=e=>Mt.fetchIdentity(e),this.getReownName=e=>jA.getNamesForAddress(e),this.getConnectors=()=>bs.getConnectors(),this.getConnectorImage=e=>Jt.getConnectorImage(e),this.getConnections=e=>this.remoteFeatures.multiWallet?Is.getConnectionsData(e).connections:(ZA.open(B.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=e=>this.remoteFeatures.multiWallet?Is.getConnectionsData(e).recentConnections:(ZA.open(B.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async e=>{this.remoteFeatures.multiWallet?await Us.switchConnection(e):ZA.open(B.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info")},this.deleteConnection=e=>{this.remoteFeatures.multiWallet?(We.deleteAddressFromConnection(e),Us.syncStorageConnections()):ZA.open(B.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info")},this.setConnectedWalletInfo=(e,t)=>{const s=Hs.getProviderId(t),n=e?{...e,type:s}:void 0;Qs.setAccountProp("connectedWalletInfo",n,t)},this.getIsConnectedState=()=>Boolean(Qs.state.activeCaipAddress),this.addAddressLabel=(e,t,s)=>{const n=Qs.getAccountData(s)?.addressLabels||{};Qs.setAccountProp("addressLabels",{...n,[e]:t},s)},this.removeAddressLabel=(e,t)=>{const s=Qs.getAccountData(t)?.addressLabels||{};Qs.setAccountProp("addressLabels",{...s,[e]:void 0},t)},this.getAddress=e=>{const t=e||Qs.state.activeChain;return Qs.getAccountData(t)?.address},this.resetNetwork=e=>{Qs.resetNetwork(e)},this.addConnector=e=>{bs.addConnector(e)},this.resetWcConnection=()=>{Us.resetWcConnection()},this.setAddressExplorerUrl=(e,t)=>{Qs.setAccountProp("addressExplorerUrl",e,t)},this.setSmartAccountDeployed=(e,t)=>{Qs.setAccountProp("smartAccountDeployed",e,t)},this.setPreferredAccountType=(e,t)=>{Qs.setAccountProp("preferredAccountType",e,t)},this.setEIP6963Enabled=e=>{kt.setEIP6963Enabled(e)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,t){const s=e?.map((e=>e.namespace)).filter((e=>Boolean(e)));if(s?.length)return[...new Set(s)];const n=t?.map((e=>e.chainNamespace));return[...new Set(n)]}async initialize(e){if(this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),e.features?.headless&&!cs.hasInjectedConnectors()&&os.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1,fetchRecommendedWallets:!0}),kt.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),e.basic||e.manualWCControl||(this.remoteFeatures=await dT.fetchRemoteFeatures(e)),await os.fetchUsage(),kt.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&an.setOnrampProviders(this.remoteFeatures.onramp),(kt.state.remoteFeatures?.email||Array.isArray(kt.state.remoteFeatures?.socials)&&kt.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins(),kt.state.features?.reownAuthentication||kt.state.remoteFeatures?.reownAuthentication){const{ReownAuthentication:e}=await import("./features-d8d1c9ce.js"),t=kt.state.siwx;t instanceof e||(t&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),kt.setSIWX(new e))}}async openSend(e){const t=e.namespace||Qs.state.activeChain,s=this.getCaipAddress(t),n=this.getCaipNetwork(t)?.id;if(!s)throw new Error("openSend: caipAddress not found");if(n?.toString()!==e.chainId.toString()){const s=Qs.getCaipNetworkById(e.chainId,t);if(!s)throw new Error(`openSend: caipNetwork with chainId ${e.chainId} not found`);await this.switchNetwork(s,{throwOnFailure:!0})}try{const t=xS.getTokenSymbolByAddress(e.assetAddress);t&&await os.fetchTokenImages([t])}catch{}return await sn.open({view:"WalletSend",data:{send:e}}),new Promise(((e,t)=>{const s=Gs.subscribeKey("hash",(t=>{t&&(r(),e({hash:t}))})),n=sn.subscribe((e=>{e.open||(r(),t(new Error("Modal closed")))})),r=this.createCleanupHandler([s,n])}))}toModalOptions(){return{isSwap:function(e){return"Swap"===e?.view},isSend:function(e){return"WalletSend"===e?.view}}}async checkAllowedOrigins(){try{const e=await os.fetchAllowedOrigins();if(!He.isClient())return;const t=window.location.origin;HA.isOriginAllowed(t,e,B.DEFAULT_ALLOWED_ANCESTORS)||ZA.open(PS.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":ZA.open(PS.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const t=e.cause instanceof Error?e.cause:e;ZA.open({displayMessage:PS.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:PS.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(t.message)},"error");break}}}}createCleanupHandler(e){return()=>{e.forEach((e=>{try{e()}catch{}}))}}sendInitializeEvent(e){const{...t}=e;delete t.adapters,delete t.universalProvider,ss.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map((e=>e.id)),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initAdapterController(){Fs.initialize(this.chainAdapters)}initializeThemeController(e){e.themeMode&&fs.setThemeMode(e.themeMode),e.themeVariables&&fs.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");Qs.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const t=this.getDefaultNetwork();t&&Qs.setActiveCaipNetwork(t)}initializeConnectionController(e){Us.initialize(e.adapters??[]),Us.setWcBasic(e.basic??!1)}initializeConnectorController(){bs.initialize(this.chainNamespaces)}initializeProjectSettings(e){kt.setProjectId(e.projectId),kt.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){kt.setDebug(!1!==e.debug),kt.setEnableWalletGuide(!1!==e.enableWalletGuide),kt.setEnableWallets(!1!==e.enableWallets),kt.setEIP6963Enabled(!1!==e.enableEIP6963),kt.setEnableCoinbase(!1!==e.enableCoinbase),kt.setEnableNetworkSwitch(!1!==e.enableNetworkSwitch),kt.setEnableReconnect(!1!==e.enableReconnect),kt.setEnableMobileFullScreen(!0===e.enableMobileFullScreen),kt.setCoinbasePreference(e.coinbasePreference),kt.setEnableAuthLogger(!1!==e.enableAuthLogger),kt.setCustomRpcUrls(e.customRpcUrls),kt.setEnableEmbedded(e.enableEmbedded),kt.setAllWallets(e.allWallets),kt.setIncludeWalletIds(e.includeWalletIds),kt.setExcludeWalletIds(e.excludeWalletIds),kt.setFeaturedWalletIds(e.featuredWalletIds),kt.setTokens(e.tokens),kt.setTermsConditionsUrl(e.termsConditionsUrl),kt.setPrivacyPolicyUrl(e.privacyPolicyUrl),kt.setCustomWallets(e.customWallets),kt.setFeatures(e.features),kt.setAllowUnsupportedChain(e.allowUnsupportedChain),kt.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),kt.setPreferUniversalLinks(e.experimental_preferUniversalLinks),kt.setDefaultAccountTypes(e.defaultAccountTypes);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),kt.setMetadata(e.metadata),kt.setDisableAppend(e.disableAppend),kt.setEnableEmbedded(e.enableEmbedded),kt.setSIWX(e.siwx),this.features=kt.state.features??{},!e.projectId)return void ZA.open(PS.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");const s=e.adapters?.find((e=>e.namespace===B.CHAIN.EVM));if(s&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");kt.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return He.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const s=FO.getUnsupportedNetwork(`${t}:${e}`);Qs.setActiveCaipNetwork(s)}}getDefaultNetwork(){return FO.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return FO.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return FO.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find((t=>t.id===e.defaultNetwork?.id));return t?FO.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectConnector(e,t){try{this.setLoading(!0,e);let s={connections:[]};const n=this.getAdapter(e),r=Qs.state.chains.get(e)?.accountState?.caipAddress;return!r&&kt.state.enableReconnect||!n?.disconnect||(s=await n.disconnect({id:t})),this.setLoading(!1,e),s}catch(t){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${t.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=Qs.state.activeChain,t=this.getAdapter(e),s=this.getCaipNetwork(e)?.id,n=Us.getConnections(e),r=this.remoteFeatures.multiWallet,i=n.length>0;if(!t)throw new Error("Adapter not found");const o=await t.connectWalletConnect(s);(!i||!r)&&this.close(),this.setClientId(o?.clientId||null),We.setConnectedNamespaces([...Qs.state.chains.keys()]),await this.syncWalletConnectAccount(),await GA.initializeIfEnabled()},connectExternal:async e=>{const t=await this.onConnectExternal(e);return await this.connectInactiveNamespaces(e,t),t?{address:t.address}:void 0},reconnectExternal:async({id:e,info:t,type:s,provider:n})=>{const r=Qs.state.activeChain,i=this.getAdapter(r);if(!r)throw new Error("reconnectExternal: namespace not found");if(!i)throw new Error("reconnectExternal: adapter not found");i?.reconnect&&(await(i?.reconnect({id:e,info:t,type:s,provider:n,chainId:this.getCaipNetwork()?.id})),We.addConnectedNamespace(r),this.syncConnectedWalletInfo(r))},disconnectConnector:async e=>{await this.disconnectConnector(e.namespace,e.id)},disconnect:async e=>{const{id:t,chainNamespace:s,initialDisconnect:n}=e||{},r=s||Qs.state.activeChain,i=bs.getConnectorId(r),o=t===B.CONNECTOR_ID.AUTH||i===B.CONNECTOR_ID.AUTH,a=t===B.CONNECTOR_ID.WALLET_CONNECT||i===B.CONNECTOR_ID.WALLET_CONNECT;try{const e=Array.from(Qs.state.chains.keys());let r=s?[s]:e;(a||o)&&(r=e);const i=r.map((async e=>{const s=bs.getConnectorId(e),r=t||s,i=await this.disconnectConnector(e,r);i&&(o&&We.deleteConnectedSocialProvider(),i.connections.forEach((t=>{We.addDisconnectedConnectorId(t.connectorId,e)}))),n&&this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})})),c=await Promise.allSettled(i);Gs.resetSend(),Us.resetWcConnection(),GA.getSIWX()?.signOutOnDisconnect&&await GA.clearSessions(),bs.setFilterByNamespace(void 0),Us.syncStorageConnections();const l=c.filter((e=>"rejected"===e.status));if(l.length>0)throw new Error(l.map((e=>e.reason.message)).join(", "));ss.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:s||"all"}})}catch(e){throw new Error(`Failed to disconnect chains: ${e.message}`)}},checkInstalled:e=>e?e.some((e=>Boolean(window.ethereum?.[String(e)]))):Boolean(window.ethereum),signMessage:async e=>{const t=Qs.state.activeChain,s=this.getAdapter(Qs.state.activeChain);if(!t)throw new Error("signMessage: namespace not found");if(!s)throw new Error("signMessage: adapter not found");const n=this.getAddress(t);if(!n)throw new Error("signMessage: address not found");const r=await(s?.signMessage({message:e,address:n,provider:Hs.getProvider(t)}));return r?.signature||""},sendTransaction:async e=>{const t=e.chainNamespace;if(!t)throw new Error("sendTransaction: namespace not found");if(qe.SEND_SUPPORTED_NAMESPACES.includes(t)){const s=this.getAdapter(t);if(!s)throw new Error("sendTransaction: adapter not found");const n=Hs.getProvider(t),r=await(s?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:n}));return r?.hash||""}return""},estimateGas:async e=>{const t=e.chainNamespace;if(t===B.CHAIN.EVM){const s=this.getAdapter(t);if(!s)throw new Error("estimateGas: adapter is required but got undefined");const n=Hs.getProvider(t),r=this.getCaipNetwork();if(!r)throw new Error("estimateGas: caipNetwork is required but got undefined");const i=await(s?.estimateGas({...e,provider:n,caipNetwork:r}));return i?.gas||0n}return 0n},getEnsAvatar:async()=>{const e=Qs.state.activeChain;if(!e)throw new Error("getEnsAvatar: namespace is required but got undefined");const t=this.getAddress(e);if(!t)throw new Error("getEnsAvatar: address not found");await this.syncIdentity({address:t,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:e});const s=Qs.getAccountData();return s?.profileImage||!1},getEnsAddress:async e=>await HA.resolveReownName(e),writeContract:async e=>{const t=Qs.state.activeChain,s=this.getAdapter(t);if(!t)throw new Error("writeContract: namespace is required but got undefined");if(!s)throw new Error("writeContract: adapter is required but got undefined");const n=this.getCaipNetwork(),r=this.getCaipAddress(),i=Hs.getProvider(t);if(!n||!r)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");const o=await(s?.writeContract({...e,caipNetwork:n,provider:i,caipAddress:r}));return o?.hash},writeSolanaTransaction:async e=>{const t=Qs.state.activeChain,s=this.getAdapter(t);if(!t)throw new Error("writeContract: namespace is required but got undefined");if(!s)throw new Error("writeContract: adapter is required but got undefined");const n=this.getCaipNetwork(),r=this.getCaipAddress(),i=Hs.getProvider(t);if(!n||!r)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");const o=await(s?.writeSolanaTransaction({...e,caipNetwork:n,provider:i,caipAddress:r}));return o?.hash},parseUnits:(e,t)=>{const s=this.getAdapter(Qs.state.activeChain);if(!s)throw new Error("parseUnits: adapter is required but got undefined");return s?.parseUnits({value:e,decimals:t})??0n},formatUnits:(e,t)=>{const s=this.getAdapter(Qs.state.activeChain);if(!s)throw new Error("formatUnits: adapter is required but got undefined");return s?.formatUnits({value:e,decimals:t})??"0"},getCapabilities:async e=>{const t=this.getAdapter(Qs.state.activeChain);if(!t)throw new Error("getCapabilities: adapter is required but got undefined");return await(t?.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(Qs.state.activeChain);if(!t)throw new Error("grantPermissions: adapter is required but got undefined");return await(t?.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(Qs.state.activeChain);if(!t)throw new Error("revokePermissions: adapter is required but got undefined");return t?.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(Qs.state.activeChain);if(!t)throw new Error("walletGetAssets: adapter is required but got undefined");return await(t?.walletGetAssets(e))??{}},updateBalance:e=>{const t=this.getAddress(e),s=this.getCaipNetwork(e);s&&t&&this.updateNativeBalance(t,s?.id,e)}},Us.setClient(this.connectionControllerClient)}async onConnectExternal(e){const t=Qs.state.activeChain,s=e.chain||t,n=this.getAdapter(s);let r=!0;if(e.type===OS.CONNECTOR_TYPE_AUTH){const s=B.AUTH_CONNECTOR_SUPPORTED_CHAINS.some((e=>bs.getConnectorId(e)===B.CONNECTOR_ID.AUTH));s&&e.chain!==t&&(r=!1)}if(e.chain&&e.chain!==t&&!e.caipNetwork){const t=this.getCaipNetworks().find((t=>t.chainNamespace===e.chain));t&&r&&this.setCaipNetwork(t)}if(!s)throw new Error("connectExternal: namespace not found");if(!n)throw new Error("connectExternal: adapter not found");const i=this.getCaipNetwork(s),o=e.caipNetwork||i,a=await n.connect({id:e.id,address:e.address,info:e.info,type:e.type,provider:e.provider,socialUri:e.socialUri,chainId:e.caipNetwork?.id||i?.id,rpcUrl:e.caipNetwork?.rpcUrls?.default?.http?.[0]||i?.rpcUrls?.default?.http?.[0]});if(a)return We.addConnectedNamespace(s),this.syncProvider({...a,chainNamespace:s}),this.setStatus("connected",s),this.syncConnectedWalletInfo(s),We.removeDisconnectedConnectorId(e.id,s),{address:a.address,connectedCaipNetwork:o}}async connectInactiveNamespaces(e,t){const s=e.type===OS.CONNECTOR_TYPE_AUTH,n=kS.getOtherAuthNamespaces(t?.connectedCaipNetwork?.chainNamespace),r=Qs.state.activeCaipNetwork,i=this.getAdapter(r?.chainNamespace);s&&(await Promise.all(n.map((async t=>{try{const s=Hs.getProvider(t),n=this.getCaipNetwork(t),r=this.getAdapter(t);await(r?.connect({...e,provider:s,socialUri:void 0,chainId:n?.id,rpcUrl:n?.rpcUrls?.default?.http?.[0]}))&&(We.addConnectedNamespace(t),We.removeDisconnectedConnectorId(e.id,t),this.setStatus("connected",t),this.syncConnectedWalletInfo(t))}catch(e){ZA.warn(PS.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,PS.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(t,e instanceof Error?e.message:void 0),PS.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}}))),r&&await(i?.switchNetwork({caipNetwork:r})))}getApprovedCaipNetworksData(){if(Hs.getProviderId(Qs.state.activeChain)===OS.CONNECTOR_TYPE_WALLET_CONNECT){const e=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:"MetaMask Wallet"===this.universalProvider?.session?.peer?.metadata.name,approvedCaipNetworkIds:this.getChainsFromNamespaces(e)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const s=Hs.getProviderId(t);if(e.chainNamespace===Qs.state.activeChain){const s=this.getAdapter(t);await(s?.switchNetwork({caipNetwork:e}))}else if(this.setCaipNetwork(e),s===OS.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const s=this.getAddressByChainNamespace(t);s&&this.syncAccount({address:s,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap((e=>{const t=e.chains||[],s=e.accounts.map((e=>{const{chainId:t,chainNamespace:s}=oe.parseCaipAddress(e);return`${s}:${t}`}));return Array.from(new Set([...t,...s]))}))}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce(((t,s)=>{const n=e?.find((e=>e.namespace===s));return n?(n.construct({namespace:s,projectId:this.options?.projectId,networks:this.caipNetworks?.filter((({chainNamespace:e})=>e===s))}),t[s]=n):t[s]=new aT({namespace:s,networks:this.getCaipNetworks()}),t}),{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e);const t=this.getAdapter(e);if(!t)throw new Error("adapter not found");await t.syncConnectors(),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map((async e=>{await this.initChainAdapter(e)}))),this.initAdapterController()}onConnectors(e){const t=this.getAdapter(e);t?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const s=We.getConnectionStatus();!1===kt.state.enableReconnect?this.setStatus("disconnected",e):"connected"===s?this.setStatus("connecting",e):"disconnected"===s?(We.clearAddressCache(),this.setStatus(s,e)):this.setStatus(s,e),t.on("switchNetwork",(({address:t,chainId:s})=>{const n=this.getCaipNetworks().find((e=>e.id.toString()===s.toString()||e.caipNetworkId.toString()===s.toString())),r=Qs.state.activeChain===e,i=Qs.state.chains.get(e)?.accountState?.address;if(n){const s=r&&t?t:i;s&&this.syncAccount({address:s,chainId:n.id,chainNamespace:e})}else this.setUnsupportedNetwork(s)})),t.on("disconnect",(()=>{const t=this.remoteFeatures.multiWallet,s=Array.from(Us.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:e,closeModal:!t||0===s.length})})),t.on("connections",(t=>{this.setConnections(t,e)})),t.on("pendingTransactions",(()=>{const t=this.getAddress(e),s=Qs.state.activeCaipNetwork;t&&s?.id&&this.updateNativeBalance(t,s.id,s.chainNamespace)})),t.on("accountChanged",(({address:t,chainId:s,connector:n})=>{this.handlePreviousConnectorConnection(n);const r=Qs.state.activeChain===e;n?.provider&&(this.syncProvider({id:n.id,type:n.type,provider:n?.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const i=Qs.getNetworkData(e)?.caipNetwork?.id,o=s||i;r&&o?this.syncAccount({address:t,chainId:o,chainNamespace:e}):!r&&o?(this.syncAccountInfo(t,o,e),this.syncBalance({address:t,chainId:o,chainNamespace:e})):this.syncAccountInfo(t,s,e),We.addConnectedNamespace(e)}))}async handlePreviousConnectorConnection(e){const t=e?.chain,s=e?.id,n=bs.getConnectorId(t),r=kt.state.remoteFeatures?.multiWallet,i=t&&s&&n&&n!==s&&!r;try{i&&await Us.disconnect({id:n,namespace:t})}catch(e){console.warn("Error disconnecting previous connector",e)}}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&await(this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map((e=>this.syncNamespaceConnection(e))))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map((e=>Us.disconnect({namespace:e,initialDisconnect:!0}))))}catch(e){console.error("Error disconnecting existing connections:",e)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();const e=this.getAddress();this.getCaipAddress()||We.deleteRecentWallet();const t=We.getRecentWallet();ss.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:He.isMobile()?"mobile":"qrcode",name:t?.name||"Unknown",reconnect:!0,view:hs.state.view,walletRank:t?.order}})}async syncNamespaceConnection(e){try{e===B.CHAIN.EVM&&He.isSafeApp()&&bs.setConnectorId(B.CONNECTOR_ID.SAFE,e);const t=bs.getConnectorId(e);switch(this.setStatus("connecting",e),t){case B.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case B.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}onDisconnectNamespace(e){const{chainNamespace:t,closeModal:s}=e||{};Qs.resetAccount(t),Qs.resetNetwork(t),We.removeConnectedNamespace(t);const n=Array.from(Qs.state.chains.keys());(t?[t]:n).forEach((e=>We.addDisconnectedConnectorId(bs.getConnectorId(e)||"",e))),bs.removeConnectorId(t),Hs.resetChain(t),this.setUser(null,t),this.setStatus("disconnected",t),this.setConnectedWalletInfo(null,t),!1!==s&&sn.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map((e=>{const t=this.getAdapter(e),s=this.getCaipAddress(e),n=this.getCaipNetwork(e);return t?.syncConnections({connectToFirstConnector:!s,caipNetwork:n})})))}async syncAdapterConnection(e){const t=this.getAdapter(e),s=this.getCaipNetwork(e),n=bs.getConnectorId(e),r=bs.getConnectors(e).find((e=>e.id===n));try{if(!t||!r)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!s?.id)throw new Error("CaipNetwork not found");const n=await(t?.syncConnection({namespace:e,id:r.id,chainId:s.id,rpcUrl:s?.rpcUrls?.default?.http?.[0]}));n?(this.syncProvider({...n,chainNamespace:e}),await this.syncAccount({...n,chainNamespace:e}),this.setStatus("connected",e),ss.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:n.address,properties:{method:"browser",name:r.info?.name||r.name||"Unknown",reconnect:!0,view:hs.state.view,walletRank:r?.explorerWallet?.order}})):this.setStatus("disconnected",e)}catch(t){this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){const e=Object.keys(this.universalProvider?.session?.namespaces||{}),t=this.chainNamespaces.map((async t=>{const s=this.getAdapter(t);if(!s)return;const n=this.universalProvider?.session?.namespaces?.[t]?.accounts||[],r=Qs.state.activeCaipNetwork?.id,i=n.find((e=>{const{chainId:t}=oe.parseCaipAddress(e);return t===r?.toString()}))||n[0];if(i){const e=oe.validateCaipAddress(i),{chainId:n,address:r}=oe.parseCaipAddress(e);if(Hs.setProviderId(t,OS.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&Qs.state.activeCaipNetwork&&s.namespace!==B.CHAIN.EVM){const e=s.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:Qs.state.activeCaipNetwork});Hs.setProvider(t,e)}else Hs.setProvider(t,this.universalProvider);bs.setConnectorId(B.CONNECTOR_ID.WALLET_CONNECT,t),We.addConnectedNamespace(t),await this.syncAccount({address:r,chainId:n,chainNamespace:t})}else e.includes(t)&&this.setStatus("disconnected",t);const o=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(t),Qs.setApprovedCaipNetworksData(t,{approvedCaipNetworkIds:o.approvedCaipNetworkIds,supportsAllNetworks:o.supportsAllNetworks})}));await Promise.all(t)}syncProvider({type:e,provider:t,id:s,chainNamespace:n}){Hs.setProviderId(n,e),Hs.setProvider(n,t),bs.setConnectorId(s,n)}async syncAccount(e){const t=e.chainNamespace===Qs.state.activeChain,s=Qs.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:n,chainId:r,chainNamespace:i}=e,{chainId:o}=We.getActiveNetworkProps(),a=s?.id||o,c=Qs.state.activeCaipNetwork?.name===B.UNSUPPORTED_NETWORK_NAME,l=Qs.getNetworkProp("supportsAllNetworks",i);if(this.setStatus("connected",i),(!c||l)&&a){let e=this.getCaipNetworks().find((e=>e.id.toString()===a.toString())),o=this.getCaipNetworks().find((e=>e.chainNamespace===i));if(!l&&!e&&!o){const t=this.getApprovedCaipNetworkIds()||[],s=t.find((e=>oe.parseCaipNetworkId(e)?.chainId===a.toString())),n=t.find((e=>oe.parseCaipNetworkId(e)?.chainNamespace===i));e=this.getCaipNetworks().find((e=>e.caipNetworkId===s)),o=this.getCaipNetworks().find((e=>e.caipNetworkId===n||"deprecatedCaipNetworkId"in e&&e.deprecatedCaipNetworkId===n))}const c=e||o;c?.chainNamespace===Qs.state.activeChain?kt.state.enableNetworkSwitch&&!kt.state.allowUnsupportedChain&&Qs.state.activeCaipNetwork?.name===B.UNSUPPORTED_NETWORK_NAME?Qs.showUnsupportedChainUI():this.setCaipNetwork(c):t||s&&this.setCaipNetworkOfNamespace(s,i),this.syncConnectedWalletInfo(i);const d=this.getAddress(i);kS.isLowerCaseMatch(n,d)||this.syncAccountInfo(n,c?.id,i),t?await this.syncBalance({address:n,chainId:c?.id,chainNamespace:i}):await this.syncBalance({address:n,chainId:s?.id,chainNamespace:i}),this.syncIdentity({address:n,chainId:r,chainNamespace:i})}}async syncAccountInfo(e,t,s){const n=this.getCaipAddress(s),r=t||n?.split(":")[1];if(!r)return;const i=`${s}:${r}:${e}`;this.setCaipAddress(i,s,!0),await this.syncIdentity({address:e,chainId:r,chainNamespace:s})}async syncReownName(e,t){try{const s=await this.getReownName(e);if(s[0]){const e=s[0];this.setProfileName(e.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){const t=bs.getConnectorId(e),s=Hs.getProviderId(e);if(s===OS.CONNECTOR_TYPE_ANNOUNCED||s===OS.CONNECTOR_TYPE_INJECTED){if(t){const s=this.getConnectors().find((e=>{const s=e.id===t,n=e.info?.rdns===t,r=e.connectors?.some((e=>e.id===t||e.info?.rdns===t));return s||n||Boolean(r)}));if(s){const{info:t,name:n,imageUrl:r}=s,i=r||this.getConnectorImage(s);this.setConnectedWalletInfo({name:n,icon:i,...t},e)}}}else if(s===OS.CONNECTOR_TYPE_WALLET_CONNECT){const t=Hs.getProvider(e);t?.session&&this.setConnectedWalletInfo({...t.session.peer.metadata,name:t.session.peer.metadata.name,icon:t.session.peer.metadata.icons?.[0]},e)}else if(t&&(t===B.CONNECTOR_ID.COINBASE_SDK||t===B.CONNECTOR_ID.COINBASE)){const s=this.getConnectors().find((e=>e.id===t)),n=s?.name||"Coinbase Wallet",r=s?.imageUrl||this.getConnectorImage(s),i=s?.info;this.setConnectedWalletInfo({...i,name:n,icon:r},e)}}async syncBalance(e){const t=j.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find((t=>t.id.toString()===e.chainId?.toString()));t&&e.chainId&&await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,t,s){const n=this.getAdapter(s),r=Qs.getCaipNetworkByNamespace(s,t);if(n){const i=await n.getBalance({address:e,chainId:t,caipNetwork:r,tokens:this.options.tokens});return this.setBalance(i.balance,i.symbol,s),i}}async initializeUniversalAdapter(){const e=__.createLogger(((e,...t)=>{e&&this.handleAlertError(e),console.error(...t)})),t={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};kt.setManualWCControl(Boolean(this.options?.manualWCControl)),this.universalProvider=this.options.universalProvider??await UA.init(t);const s=this.universalProvider.disconnect.bind(this.universalProvider);this.universalProvider.disconnect=async()=>{try{return await s()}catch(e){if(e instanceof Error){if(e.message.includes("Missing or invalid. Record was recently deleted"))return}throw e}},!1===kt.state.enableReconnect&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach((e=>{HA.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:e=>{Us.setUri(e)},onConnect:e=>{const{address:t}=He.getAccount(e[0]);for(const e of this.chainNamespaces)We.removeDisconnectedConnectorId(B.CONNECTOR_ID.WALLET_CONNECT,e);Us.finalizeWcConnection(t)},onDisconnect:()=>{Qs.state.noAdapters&&this.resetAccount(e),Us.resetWcConnection()},onChainChanged:t=>{const s=Qs.state.activeChain,n=s&&bs.state.activeConnectorIds[s]===B.CONNECTOR_ID.WALLET_CONNECT;if(s===e&&(Qs.state.noAdapters||n)){const e=this.getCaipNetworks().find((e=>e.id.toString()===t.toString()||e.caipNetworkId.toString()===t.toString())),s=this.getCaipNetwork();if(!e)return void this.setUnsupportedNetwork(t);s?.id.toString()!==e?.id.toString()&&s?.chainNamespace===e?.chainNamespace&&this.setCaipNetwork(e)}},onAccountsChanged:t=>{const s=Qs.state.activeChain,n=s&&bs.state.activeConnectorIds[s]===B.CONNECTOR_ID.WALLET_CONNECT;if(s===e&&(Qs.state.noAdapters||n)){const e=t?.[0];e&&this.syncAccount({address:e.address,chainId:e.chainId,chainNamespace:e.chainNamespace})}}})}))}createUniversalProvider(){return!this.universalProviderInitPromise&&He.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){ss.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}getDisabledCaipNetworks(){const e=Qs.getAllApprovedCaipNetworkIds(),t=Qs.getAllRequestedCaipNetworks();return He.sortRequestedNetworks(e,t).filter((e=>Qs.isCaipNetworkDisabled(e)))}handleAlertError(e){const t=Object.entries(PS.UniversalProviderErrors).find((([,{message:t}])=>e.message.includes(t))),[s,n]=t??[],{message:r,alertErrorKey:i}=n??{};if(s&&r&&!this.reportedAlertErrors[s]){const e=PS.ALERT_ERRORS[i];e&&(ZA.open(e,"error"),this.reportedAlertErrors[s]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const s=e;s.namespace=t,s.construct({namespace:t,projectId:this.options?.projectId,networks:this.caipNetworks?.filter((({chainNamespace:e})=>e===t))}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=s)}async open(e){await this.injectModalUi(),e?.uri&&Us.setUri(e.uri);const{isSwap:t,isSend:s}=this.toModalOptions();return t(e)?sn.open({...e,data:{swap:e.arguments}}):s(e)&&e.arguments?this.openSend(e.arguments):sn.open(e)}async close(){await this.injectModalUi(),sn.close()}setLoading(e,t){sn.setLoading(e,t)}async disconnect(e){await Us.disconnect({namespace:e})}getSIWX(){return kt.state.siwx}getError(){return""}getChainId(){return Qs.state.activeCaipNetwork?.id}async switchNetwork(e,{throwOnFailure:t=!1}={}){const s=this.getCaipNetworks().find((t=>t.id===e.id));s?await Qs.switchActiveNetwork(s,{throwOnFailure:t}):ZA.open(PS.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error")}getWalletProvider(){return Qs.state.activeChain?Hs.state.providers[Qs.state.activeChain]:null}getWalletProviderType(){return Hs.getProviderId(Qs.state.activeChain)}subscribeProviders(e){return Hs.subscribeProviders(e)}getThemeMode(){return fs.state.themeMode}getThemeVariables(){return fs.state.themeVariables}setThemeMode(e){fs.setThemeMode(e),AS(fs.state.themeMode)}setTermsConditionsUrl(e){kt.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){kt.setPrivacyPolicyUrl(e)}setThemeVariables(e){fs.setThemeVariables(e),function(e){if(vS=e,yS&&wS&&bS){yS.textContent=IS(e).core.cssText,wS.textContent=IS(e).dark.cssText,bS.textContent=IS(e).light.cssText;const t=e?.["--apkt-font-family"]||e?.["--w3m-font-family"];t&&(yS.textContent=yS.textContent?.replace("font-family: KHTeka",`font-family: ${t}`),wS.textContent=wS.textContent?.replace("font-family: KHTeka",`font-family: ${t}`),bS.textContent=bS.textContent?.replace("font-family: KHTeka",`font-family: ${t}`))}mS&&CS(e,"enabled"===bS?.media?"light":"dark")}(fs.state.themeVariables)}subscribeTheme(e){return fs.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?Us.subscribe(e):(ZA.open(B.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){if(e)return Qs.state.chains.get(e)?.accountState?.connectedWalletInfo;const t=Qs.getAccountData();return t?.connectedWalletInfo}getAccount(e){const t=e||Qs.state.activeChain,s=bs.getAuthConnector(t),n=Qs.getAccountData(t),r=We.getConnectedConnectorId(Qs.state.activeChain),i=Us.getConnections(t);if(!t)throw new Error("AppKit:getAccount - namespace is required");const o=i.flatMap((e=>{const{caipNetwork:t}=e;return t?e.accounts.map((({address:e,type:s,publicKey:n})=>He.createAccount({caipAddress:`${t.caipNetworkId}:${e}`,type:s||"eoa",publicKey:n}))):[]}));if(n)return{allAccounts:o,caipAddress:n.caipAddress,address:He.getPlainAddress(n.caipAddress),isConnected:Boolean(n.caipAddress),status:n.status,embeddedWalletInfo:s&&r===B.CONNECTOR_ID.AUTH?{user:n.user?{...n.user,username:We.getConnectedSocialUsername()}:void 0,authProvider:n.socialProvider||"email",accountType:Ns(t),isSmartAccountDeployed:Boolean(n.smartAccountDeployed)}:void 0}}subscribeAccount(e,t){const s=[],n=()=>{const s=this.getAccount(t);s&&e(s)};if(t){const e=Qs.subscribeChainProp("accountState",n,t);s.push(e)}else{const e=Qs.subscribe(n);s.push(e)}const r=bs.subscribe(n);return s.push(r),()=>{s.forEach((e=>e()))}}subscribeNetwork(e){return Qs.subscribe((({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t?.id,caipNetworkId:t?.caipNetworkId})}))}subscribeWalletInfo(e,t){return t?Qs.subscribeChainProp("accountState",(t=>e(t?.connectedWalletInfo)),t):Qs.subscribeChainProp("accountState",(t=>e(t?.connectedWalletInfo)))}subscribeShouldUpdateToAddress(e){return Qs.subscribeChainProp("accountState",(t=>e(t?.shouldUpdateToAddress)))}subscribeCaipNetworkChange(e){return Qs.subscribeKey("activeCaipNetwork",e)}getState(){return _s.state}getRemoteFeatures(){return kt.state.remoteFeatures}subscribeState(e){return _s.subscribe(e)}subscribeRemoteFeatures(e){return kt.subscribeKey("remoteFeatures",e)}showErrorMessage(e){Rt.showError(e)}showSuccessMessage(e){Rt.showSuccess(e)}getEvent(){return{...ss.state}}subscribeEvents(e){return ss.subscribe(e)}replace(e){hs.replace(e)}redirect(e){hs.push(e)}popTransactionStack(e){hs.popTransactionStack(e)}isOpen(){return sn.state.open}isTransactionStackEmpty(){return 0===hs.state.transactionStack.length}static getInstance(){return this.instance}updateFeatures(e){kt.setFeatures(e)}updateRemoteFeatures(e){kt.setRemoteFeatures(e)}updateOptions(e){const t={...kt.state||{},...e};kt.setOptions(t)}setConnectMethodsOrder(e){kt.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){kt.setWalletFeaturesOrder(e)}setCollapseWallets(e){kt.setCollapseWallets(e)}setSocialsOrder(e){kt.setSocialsOrder(e)}getConnectMethodsOrder(){return as.getConnectOrderMethod(kt.state.features,bs.getConnectors())}addNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const s=this.extendCaipNetwork(t,this.options);this.getCaipNetworks().find((e=>e.id===s.id))||Qs.addNetwork(s)}removeNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const s=this.getCaipNetworks().find((e=>e.id===t));s&&Qs.removeNetwork(e,t)}}let uT=!1;class pT extends hT{async open(e){bs.isConnected()||await super.open(e)}async close(){if(await super.close(),this.options.manualWCControl){const e=Qs.getAccountData(this.activeChainNamespace)?.address;Us.finalizeWcConnection(e)}}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!uT&&He.isClient()){await import("./basic-77fe1b96.js"),await import("./w3m-modal-49add722.js");if(!document.querySelector("w3m-modal")){const e=document.createElement("w3m-modal");kt.state.disableAppend||kt.state.enableEmbedded||document.body.insertAdjacentElement("beforeend",e)}uT=!0}}}var fT=Object.freeze({__proto__:null,createAppKit:function(e){return new pT({...e,basic:!0,sdkVersion:"html-core-1.8.19"})},AppKit:pT});export{Cs as $,os as A,xe as B,bs as C,Ht as D,ss as E,Re as F,De as G,kS as H,Es as I,zs as J,Mt as K,js as L,sn as M,ee as N,kt as O,ZA as P,Ns as Q,hs as R,Rt as S,fs as T,Ye as U,GA as V,as as W,oe as X,re as Y,Hs as Z,_t as _,He as a,NS as a0,Fs as a1,j as a2,de as a3,As as a4,ue as a5,rt as a6,it as a7,ht as a8,ut as a9,yt as aa,ft as ab,mt as ac,gt as ad,at as ae,ct as af,ot as ag,wt as ah,bt as ai,It as aj,vt as ak,Et as al,Nt as am,Ct as an,At as ao,fT as ap,Us as b,B as c,qI as d,gS as e,Vt as f,cs as g,Jt as h,aS as i,Qs as j,_S as k,qt as l,ae as m,Is as n,qe as o,FO as p,Xt as q,SS as r,We as s,zI as t,iI as u,wI as v,WI as w,bI as x,fS as y,HI as z};