@dodoex/wallet-web3 0.6.3 → 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 (217) 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-2b1b6d17.js → __tslib-6d6a586c.js} +1 -1
  54. package/dist/{alchemy-provider-5870b6fa-b23243a1.js → alchemy-provider-5870b6fa-a9fe5aa5.js} +1 -1
  55. package/dist/{alchemy-websocket-provider-213da986-559da73b.js → alchemy-websocket-provider-213da986-16164c2e.js} +1 -1
  56. package/dist/basic-77fe1b96.js +1320 -0
  57. package/dist/{blocto-8e69bccf.js → blocto-ab8ba330.js} +1 -1
  58. package/dist/{ccip-99b4ad16.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-91c50e46.cjs → __tslib-a9f27ba6.cjs} +1 -1
  112. package/dist/cjs/{alchemy-provider-5870b6fa-a824dbf0.cjs → alchemy-provider-5870b6fa-bb1c607e.cjs} +1 -1
  113. package/dist/cjs/{alchemy-websocket-provider-213da986-f96378c8.cjs → alchemy-websocket-provider-213da986-521569b5.cjs} +1 -1
  114. package/dist/cjs/basic-b777d2b1.cjs +1320 -0
  115. package/dist/cjs/{blocto-255deb25.cjs → blocto-09e0d574.cjs} +1 -1
  116. package/dist/cjs/{ccip-58f4c3ce.cjs → ccip-6ebee1cf.cjs} +1 -1
  117. package/dist/cjs/core-78a709db.cjs +210 -0
  118. package/dist/cjs/{draggabilly-b00ba129.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-4cb4044e.cjs → index-07e81389.cjs} +1 -1
  122. package/dist/cjs/{index-28fe8dc2.cjs → index-093cef5a.cjs} +2 -2
  123. package/dist/cjs/{index-0f3e4a4a.cjs → index-208df3f3.cjs} +1 -1
  124. package/dist/cjs/{index-9cbeb66d.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-b0eb86b6.cjs → index-54d7fc75.cjs} +1 -1
  128. package/dist/cjs/{index-5d1879f6.cjs → index-5d28acf4.cjs} +3 -3
  129. package/dist/cjs/{index-02043814.cjs → index-5dac528b.cjs} +4 -4
  130. package/dist/cjs/index-702e8f89.cjs +15 -0
  131. package/dist/cjs/{index-7d213984.cjs → index-823e17e6.cjs} +1 -1
  132. package/dist/cjs/{index-2c339ec0.cjs → index-916994aa.cjs} +1 -1
  133. package/dist/cjs/{index-96c22872.cjs → index-a2b665f4.cjs} +1 -1
  134. package/dist/cjs/{index-110f55af.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-a67cd05c.cjs → interface-4947cfa6.cjs} +1 -1
  139. package/dist/cjs/lib-typedarrays-a9baf142.cjs +1 -0
  140. package/dist/cjs/native-55bb141d.cjs +1 -0
  141. package/dist/cjs/{portis-ec737dc5.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-65a82f1e.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-095edc5f.cjs → walletLink-08b8da20.cjs} +2 -2
  154. package/dist/core-4d7ad6f2.js +210 -0
  155. package/dist/{draggabilly-919fe798.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-de7476e4.js → index-09298bd0.js} +7 -7
  159. package/dist/{index-085a063c.js → index-244a8189.js} +1 -1
  160. package/dist/{index-23ae718c.js → index-2ad0fb2a.js} +1 -1
  161. package/dist/index-35d87b79.js +17 -0
  162. package/dist/{index-bbaf7a43.js → index-587ff998.js} +1 -1
  163. package/dist/{index-601a6250.js → index-750a7dfe.js} +1 -1
  164. package/dist/{index-cc764016.js → index-8bd12de1.js} +1 -1
  165. package/dist/{index-6382b40b.js → index-938686fb.js} +1 -1
  166. package/dist/{index-3cf73206.js → index-9d7fee1e.js} +2 -2
  167. package/dist/{index-fd3058aa.js → index-aa744ca0.js} +1 -1
  168. package/dist/{index-7fabb817.js → index-b7d25e8a.js} +3 -3
  169. package/dist/index-bb1a0019.js +15 -0
  170. package/dist/index-c5ca8a4e.js +4 -0
  171. package/dist/{index-f5d95949.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-82bdcddb.js → interface-0c535796.js} +1 -1
  176. package/dist/lib-typedarrays-979d2723.js +1 -0
  177. package/dist/native-029c50f7.js +1 -0
  178. package/dist/{portis-0a2bd95e.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-83d7ae9a.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-1b3cb067.js → walletLink-67264328.js} +2 -2
  191. package/package.json +5 -5
  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-0c26cee0.cjs +0 -1
  195. package/dist/cjs/index-21f86827.cjs +0 -17
  196. package/dist/cjs/index-35edc6a0.cjs +0 -60
  197. package/dist/cjs/index-568647cf.cjs +0 -15
  198. package/dist/cjs/index-9f2a69d5.cjs +0 -1
  199. package/dist/cjs/index.es-2a36620f.cjs +0 -9
  200. package/dist/cjs/lib-typedarrays-f921c603.cjs +0 -1
  201. package/dist/cjs/rainbow-322fb6a9.cjs +0 -1
  202. package/dist/cjs/sha224-f0657d8a.cjs +0 -1
  203. package/dist/cjs/sha256-a0c6063a.cjs +0 -1
  204. package/dist/cjs/uAuth-d389b45d.cjs +0 -1
  205. package/dist/cjs/walletConnect-3c32ceb8.cjs +0 -1
  206. package/dist/id-bc1ef47c.js +0 -1
  207. package/dist/index-24d19ee3.js +0 -15
  208. package/dist/index-65d96278.js +0 -60
  209. package/dist/index-e4c02dc7.js +0 -17
  210. package/dist/index-f08d6a6b.js +0 -1
  211. package/dist/index.es-474ba2f2.js +0 -9
  212. package/dist/lib-typedarrays-becaa8ad.js +0 -1
  213. package/dist/rainbow-aa24fa3b.js +0 -1
  214. package/dist/sha224-e9d5a920.js +0 -1
  215. package/dist/sha256-65d6895c.js +0 -1
  216. package/dist/uAuth-8aef513a.js +0 -1
  217. package/dist/walletConnect-f12ca9e1.js +0 -1
@@ -0,0 +1,210 @@
1
+ "use strict";var e=require("events"),t=require("./index-2e8e7a50.cjs"),s=require("./__tslib-a9f27ba6.cjs"),n=require("./index-5dac528b.cjs");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=r(e);const o={isLowerCaseMatch:(e,t)=>e?.toLowerCase()===t?.toLowerCase()},a={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"},c={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 a.CHAIN_NAME_MAP?.[n]||void 0}},l=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var d=1e6,h=1e6,u="[big.js] ",p=u+"Invalid ",f=p+"decimal places",g=p+"rounding mode",m=u+"Division by zero",y={},w=void 0,b=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function v(e,t,s,n){var r=e.c;if(s===w&&(s=e.constructor.RM),0!==s&&1!==s&&2!==s&&3!==s)throw Error(g);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]!==w))),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]!==w||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 E(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}y.abs=function(){var e=new this.constructor(this);return e.s=1,e},y.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},y.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>d)throw Error(f);if(!r[0])throw Error(m);if(!n[0])return e.s=i,e.c=[e.e=0],e;var a,c,l,h,u,p=r.slice(),g=a=r.length,y=n.length,b=n.slice(0,a),E=b.length,C=e,N=C.c=[],A=0,I=o+(C.e=t.e-e.e)+1;for(C.s=i,i=I<0?0:I,p.unshift(0);E++<a;)b.push(0);do{for(l=0;l<10;l++){if(a!=(E=b.length))h=a>E?1:-1;else for(u=-1,h=0;++u<a;)if(r[u]!=b[u]){h=r[u]>b[u]?1:-1;break}if(!(h<0))break;for(c=E==a?r:p;E;){if(b[--E]<c[E]){for(u=E;u&&!b[--u];)b[u]=9;--b[u],b[E]+=10}b[E]-=c[E]}for(;!b[0];)b.shift()}N[A++]=h?l:++l,b[0]&&h?b[E]=n[g]||0:b=[n[g]]}while((g++<y||b[0]!==w)&&i--);return N[0]||1==A||(N.shift(),C.e--,I--),A>I&&v(C,I,s.RM,b[0]!==w),C},y.eq=function(e){return 0===this.cmp(e)},y.gt=function(e){return this.cmp(e)>0},y.gte=function(e){return this.cmp(e)>-1},y.lt=function(e){return this.cmp(e)<0},y.lte=function(e){return this.cmp(e)<1},y.minus=y.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},y.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(m);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)))},y.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},y.plus=y.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},y.pow=function(e){var t=this,s=new t.constructor("1"),n=s,r=e<0;if(e!==~~e||e<-1e6||e>h)throw Error(p+"exponent");for(r&&(e=-e);1&e&&(n=n.times(t)),e>>=1;)t=t.times(t);return r?s.div(n):n},y.prec=function(e,t){if(e!==~~e||e<1||e>d)throw Error(p+"precision");return v(new this.constructor(this),e,t)},y.round=function(e,t){if(e===w)e=0;else if(e!==~~e||e<-d||e>d)throw Error(f);return v(new this.constructor(this),e+this.e+1,t)},y.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(u+"No square root");0===(i=Math.sqrt(+E(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 v(e,(r.DP-=4)+e.e+1,r.RM)},y.times=y.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},y.toExponential=function(e,t){var s=this,n=s.c[0];if(e!==w){if(e!==~~e||e<0||e>d)throw Error(f);for(s=v(new s.constructor(s),++e,t);s.c.length<e;)s.c.push(0)}return E(s,!0,!!n)},y.toFixed=function(e,t){var s=this,n=s.c[0];if(e!==w){if(e!==~~e||e<0||e>d)throw Error(f);for(e=e+(s=v(new s.constructor(s),e+s.e+1,t)).e+1;s.c.length<e;)s.c.push(0)}return E(s,!1,!!n)},y[Symbol.for("nodejs.util.inspect.custom")]=y.toJSON=y.toString=function(){var e=this,t=e.constructor;return E(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},y.toNumber=function(){var e=+E(this,!0,!0);if(!0===this.constructor.strict&&!this.eq(e.toString()))throw Error(u+"Imprecise conversion");return e},y.toPrecision=function(e,t){var s=this,n=s.constructor,r=s.c[0];if(e!==w){if(e!==~~e||e<1||e>d)throw Error(p+"precision");for(s=v(new n(s),e,t);s.c.length<e;)s.c.push(0)}return E(s,e<=s.e||s.e<=n.NE||s.e>=n.PE,!!r)},y.valueOf=function(){var e=this,t=e.constructor;if(!0===t.strict)throw Error(u+"valueOf disallowed");return E(e,e.e<=t.NE||e.e>=t.PE,!0)};var C=function e(){function t(s){var n=this;if(!(n instanceof t))return s===w?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(p+"value");s=0===s&&1/s<0?"-0":String(s)}!function(e,t){var s,n,r;if(!b.test(t))throw Error(p+"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=y,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 N={bigNumber(e,t={safe:!1}){try{return new C(e?e:0)}catch(e){if(t.safe)return new C(0);throw e}},formatNumber(e,t){const{decimals:s,round:n=8,safe:r=!0}=t;return N.bigNumber(e,{safe:r}).div(new C(10).pow(s)).round(n)},multiply(e,t){if(void 0===e||void 0===t)return new C(0);const s=new C(e),n=new C(t);return s.times(n)},toFixed:(e,t=2)=>void 0===e||""===e?new C(0).toFixed(t):new C(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 C(t).toNumber()}},A=[{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"}]}],I=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],S=[{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"}]}],_={getERC20Abi:e=>a.USDT_CONTRACT_ADDRESSES.includes(e)?S:A,getSwapAbi:()=>I},O={ConnectorExplorerIds:{[a.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[a.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[a.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[a.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[a.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[a.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[a.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[a.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[a.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[a.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[a.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[a.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[a.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[a.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[a.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[a.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[a.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[a.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[a.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:{[a.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[a.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[a.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[a.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[a.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[a.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[a.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[a.CONNECTOR_ID.INJECTED]:"Browser Wallet",[a.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[a.CONNECTOR_ID.COINBASE]:"Coinbase",[a.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[a.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[a.CONNECTOR_ID.LEDGER]:"Ledger",[a.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[a.CONNECTOR_ID.INJECTED]:"INJECTED",[a.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[a.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[a.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]},T={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}}},k={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(k.isRpcProviderError(e)){const t=e.code===k.RPC_ERROR_CODE.USER_REJECTED_REQUEST,s=e.code===k.RPC_ERROR_CODE.USER_REJECTED_METHODS;return t||s||k.isUserRejectedMessage(e.message)}return e instanceof Error&&k.isUserRejectedMessage(e.message)}};class x extends Error{constructor(e,t){super(t.message,{cause:e}),this.name=k.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=t.code}}class P extends x{constructor(e){super(e,{code:k.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=k.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const R={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 U(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const L={setItem(e,t){D()&&void 0!==t&&localStorage.setItem(e,t)},getItem(e){if(D())return localStorage.getItem(e)||void 0},removeItem(e){D()&&localStorage.removeItem(e)},clear(){D()&&localStorage.clear()}};function D(){return"undefined"!=typeof window&&"undefined"!=typeof localStorage}function M(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 B=Symbol(),j=Object.getPrototypeOf,$=new WeakMap,F=e=>(e=>e&&($.has(e)?$.get(e):j(e)===Object.prototype||j(e)===Array.prototype))(e)&&e[B]||null,q=(e,t=!0)=>{$.set(e,t)},W=e=>"object"==typeof e&&null!==e,H=(e,t)=>{const s=K.get(e);if((null==s?void 0:s[0])===t)return s[1];const n=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return q(n,!0),K.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(V.has(s))q(s,!1);else if(z.has(s)){const[e,t]=z.get(s);i.value=H(e,t())}Object.defineProperty(n,t,i)})),Object.preventExtensions(n)},z=new WeakMap,V=new WeakSet,K=new WeakMap,G=[1],J=new WeakMap;let Y=Object.is,X=(e,t)=>new Proxy(e,t),Z=e=>W(e)&&!V.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),Q=H,ee=(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&&(Y(l,o)||J.has(o)&&Y(l,J.get(o))))return!0;s(i),W(o)&&(o=F(o)||o);const d=!z.has(o)&&Z(o)?te(o):o;return t(i,d),Reflect.set(r,i,d,a),n(["set",[i],o,l]),!0}});function te(e={}){if(!W(e))throw new Error("object required");const t=J.get(e);if(t)return t;let s=G[0];const n=new Set,r=(e,t=++G[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=ee((()=>c),((e,t)=>{const s=!V.has(t)&&z.get(t);if(s){if(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=X(e,l);J.set(e,d);const h=[e,(e=G[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(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 z.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 se(e,t,s){const n=z.get(e);let r;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 ne(e){const t=z.get(e);t||console.warn("Please use proxy object");const[s,n]=t;return Q(s,n())}function re(e){return V.add(e),e}function ie(e,t,s,n){let r=e[t];return se(e,(()=>{const n=e[t];Object.is(r,n)||s(r=n)}),n)}const{proxyStateMap:oe,snapCache:ae}={proxyStateMap:z,refSet:V,snapCache:K,versionHolder:G,proxyCache:J},ce=e=>oe.has(e);const le=("undefined"!=typeof process&&void 0!==process.env?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",de=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],he={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:le,SECURE_SITE_DASHBOARD:`${le}/dashboard`,SECURE_SITE_FAVICON:`${le}/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:[a.CHAIN.EVM,a.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[a.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:[a.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[a.CHAIN.EVM,a.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[a.CHAIN.EVM,a.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[a.CHAIN.EVM,a.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:[a.CHAIN.EVM,a.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:[O.ConnectorExplorerIds[a.CONNECTOR_ID.COINBASE],O.ConnectorExplorerIds[a.CONNECTOR_ID.COINBASE_SDK],O.ConnectorExplorerIds[a.CONNECTOR_ID.BASE_ACCOUNT],O.ConnectorExplorerIds[a.SOLFLARE_CONNECTOR_NAME],O.ConnectorExplorerIds[a.PHANTOM_CONNECTOR_NAME],O.ConnectorExplorerIds[a.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]},ue={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=ue.getActiveNamespace(),t=ue.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{L.setItem(R.DEEPLINK_CHOICE,JSON.stringify({href:t,name:e}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const e=L.getItem(R.DEEPLINK_CHOICE);if(e)return JSON.parse(e)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{L.removeItem(R.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(e){try{L.setItem(R.ACTIVE_NAMESPACE,e)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(e){try{L.setItem(R.ACTIVE_CAIP_NETWORK_ID,e),ue.setActiveNamespace(e.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return L.getItem(R.ACTIVE_CAIP_NETWORK_ID)}catch{return void console.info("Unable to get active caip network id")}},deleteActiveCaipNetworkId(){try{L.removeItem(R.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(e){try{const t=U(e);L.removeItem(t)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(e){try{const t=ue.getRecentWallets(),s=t.find((t=>t.id===e.id));s||(t.unshift(e),t.length>2&&t.pop(),L.setItem(R.RECENT_WALLETS,JSON.stringify(t)),L.setItem(R.RECENT_WALLET,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const e=L.getItem(R.RECENT_WALLETS);return e?JSON.parse(e):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const e=L.getItem(R.RECENT_WALLET);return e?JSON.parse(e):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{L.removeItem(R.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(e,t){try{const s=U(e);L.setItem(s,t)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return L.getItem(R.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(e){if(e)try{const t=U(e);return L.getItem(t)}catch(t){console.info("Unable to get connected connector id in namespace",e)}},setConnectedSocialProvider(e){try{L.setItem(R.CONNECTED_SOCIAL,e)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return L.getItem(R.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{L.removeItem(R.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return L.getItem(R.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){const e=L.getItem(R.ACTIVE_CAIP_NETWORK_ID),t=e?.split(":")?.[1];return t},setConnectionStatus(e){try{L.setItem(R.CONNECTION_STATUS,e)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return L.getItem(R.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const e=L.getItem(R.CONNECTED_NAMESPACES);return e?.length?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));L.setItem(R.CONNECTED_NAMESPACES,t.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(e){try{const t=ue.getConnectedNamespaces();t.includes(e)||(t.push(e),ue.setConnectedNamespaces(t))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(e){try{const t=ue.getConnectedNamespaces(),s=t.indexOf(e);s>-1&&(t.splice(s,1),ue.setConnectedNamespaces(t))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return L.getItem(R.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(e){try{L.setItem(R.TELEGRAM_SOCIAL_PROVIDER,e)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{L.removeItem(R.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let e={};try{const t=L.getItem(R.PORTFOLIO_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromBalanceCache(e){try{const t=ue.getBalanceCache();L.setItem(R.PORTFOLIO_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove address from balance cache",e)}},getBalanceCacheForCaipAddress(e){try{const t=ue.getBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;ue.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateBalanceCache(e){try{const t=ue.getBalanceCache();t[e.caipAddress]=e,L.setItem(R.PORTFOLIO_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getNativeBalanceCache(){let e={};try{const t=L.getItem(R.NATIVE_BALANCE_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get balance cache")}return e},removeAddressFromNativeBalanceCache(e){try{const t=ue.getBalanceCache();L.setItem(R.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=ue.getNativeBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",e),ue.removeAddressFromBalanceCache(e)}catch{console.info("Unable to get balance cache for address",e)}},updateNativeBalanceCache(e){try{const t=ue.getNativeBalanceCache();t[e.caipAddress]=e,L.setItem(R.NATIVE_BALANCE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update balance cache",e)}},getEnsCache(){let e={};try{const t=L.getItem(R.ENS_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get ens name cache")}return e},getEnsFromCacheForAddress(e){try{const t=ue.getEnsCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;ue.removeEnsFromCache(e)}catch{console.info("Unable to get ens name from cache",e)}},updateEnsCache(e){try{const t=ue.getEnsCache();t[e.address]=e,L.setItem(R.ENS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ens name cache",e)}},removeEnsFromCache(e){try{const t=ue.getEnsCache();L.setItem(R.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=L.getItem(R.IDENTITY_CACHE);e=t?JSON.parse(t):{}}catch{console.info("Unable to get identity cache")}return e},getIdentityFromCacheForAddress(e){try{const t=ue.getIdentityCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;ue.removeIdentityFromCache(e)}catch{console.info("Unable to get identity from cache",e)}},updateIdentityCache(e){try{const t=ue.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},L.setItem(R.IDENTITY_CACHE,JSON.stringify(t))}catch{console.info("Unable to update identity cache",e)}},removeIdentityFromCache(e){try{const t=ue.getIdentityCache();L.setItem(R.IDENTITY_CACHE,JSON.stringify({...t,[e]:void 0}))}catch{console.info("Unable to remove identity from cache",e)}},getTonWalletsCache(){try{const e=L.getItem(R.TON_WALLETS_CACHE),t=e?JSON.parse(e):void 0;if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tonWallets))return t;ue.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(e){try{const t=ue.getTonWalletsCache()||{timestamp:0,wallets:[]};t.timestamp=(new Date).getTime(),t.wallets=e,L.setItem(R.TON_WALLETS_CACHE,JSON.stringify(t))}catch{console.info("Unable to update ton wallets cache",e)}},removeTonWalletsCache(){try{L.removeItem(R.TON_WALLETS_CACHE)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{L.removeItem(R.PORTFOLIO_CACHE),L.removeItem(R.NATIVE_BALANCE_CACHE),L.removeItem(R.ENS_CACHE),L.removeItem(R.IDENTITY_CACHE),L.removeItem(R.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(e){try{L.setItem(R.PREFERRED_ACCOUNT_TYPES,JSON.stringify(e))}catch{console.info("Unable to set preferred account types",e)}},getPreferredAccountTypes(){try{const e=L.getItem(R.PREFERRED_ACCOUNT_TYPES);return e?JSON.parse(e):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(e,t){try{const s=ue.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===a.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())};L.setItem(R.CONNECTIONS,JSON.stringify(i))}catch(e){console.error("Unable to sync connections to storage",e)}},getConnections(){try{const e=L.getItem(R.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=ue.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()))})}L.setItem(R.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=L.getItem(R.DISCONNECTED_CONNECTOR_IDS);return e?JSON.parse(e):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(e,t){try{const s=ue.getDisconnectedConnectorIds(),n=s[t]??[];n.push(e),L.setItem(R.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=ue.getDisconnectedConnectorIds();let n=s[t]??[];n=n.filter((t=>t.toLowerCase()!==e.toLowerCase())),L.setItem(R.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=ue.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=L.getItem(R.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=ue.getTransactionsCache(),n=s[e]?.[t];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.transactionsHistory))return n.transactions;ue.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=ue.getTransactionsCache();r[e]={...r[e],[t]:{timestamp:s,transactions:n}},L.setItem(R.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=ue.getTransactionsCache(),n=s?.[e]||{},{[t]:r,...i}=n;L.setItem(R.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...s,[e]:i}))}catch{console.info("Unable to remove transactions cache",{address:e,chainId:t})}},getTokenPriceCache(){try{const e=L.getItem(R.TOKEN_PRICE_CACHE);return e?JSON.parse(e):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(e){try{const t=ue.getTokenPriceCache()[e.join(",")];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.tokenPrice))return t.tokenPrice;ue.removeTokenPriceCache(e)}catch{console.info("Unable to get token price cache for addresses",e)}},updateTokenPriceCache(e){try{const t=ue.getTokenPriceCache();t[e.addresses.join(",")]={timestamp:e.timestamp,tokenPrice:e.tokenPrice},L.setItem(R.TOKEN_PRICE_CACHE,JSON.stringify(t))}catch{console.info("Unable to update token price cache",e)}},removeTokenPriceCache(e){try{const t=ue.getTokenPriceCache();L.setItem(R.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=L.getItem(R.LATEST_APPKIT_VERSION);return e?JSON.parse(e):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(e){try{const t=ue.getLatestAppKitVersionCache();t.timestamp=e.timestamp,t.version=e.version,L.setItem(R.LATEST_APPKIT_VERSION,JSON.stringify(t))}catch{console.info("Unable to update latest AppKit version on local storage",e)}}},pe={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 pe.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()<=he.TEN_SEC_MS,isAllowedRetry:(e,t=he.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(pe.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()+he.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(pe.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(!pe.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()?ue.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,pe.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:()=>a.W3M_API_URL,getBlockchainApiUrl:()=>a.BLOCKCHAIN_API_RPC_URL,getAnalyticsUrl:()=>a.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?he.ADAPTER_TYPES.UNIVERSAL:e.map((e=>e.adapterType)).join(",")}-${s}`,createAccount(e){const{chainNamespace:t,chainId:s,address:n}=T.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 a.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 fe="@appkit-wallet/",ge="LAST_EMAIL_LOGIN_TIME",me="SMART_ACCOUNT_ENABLED_NETWORKS",ye="RPC_RESPONSE_TRANSACTION_HASH",we="RPC_RESPONSE_OBJECT",be={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"}},ve=/^0x(?:[A-Fa-f0-9]{64})$/u,Ee=/^0x(?:[a-fA-F0-9]{62,})$/u,Ce={set(e,t){Ae.isClient&&localStorage.setItem(`${fe}${e}`,t)},get:e=>Ae.isClient?localStorage.getItem(`${fe}${e}`):null,delete(e,t){Ae.isClient&&(t?localStorage.removeItem(e):localStorage.removeItem(`${fe}${e}`))}},Ne=3e4,Ae={checkIfAllowedToTriggerEmail(){const e=Ce.get(ge);if(e){const t=Date.now()-Number(e);if(t<Ne){const e=Math.ceil((Ne-t)/1e3);throw new Error(`Please try again after ${e} seconds`)}}},getTimeToNextEmailLogin(){const e=Ce.get(ge);if(e){const t=Date.now()-Number(e);if(t<Ne)return Math.ceil((Ne-t)/1e3)}return 0},checkIfRequestExists:e=>be.NOT_SAFE_RPC_METHODS.includes(e.method)||be.SAFE_RPC_METHODS.includes(e.method),getResponseType:e=>"string"==typeof e&&(e?.match(ve)||e?.match(Ee))?ye:we,checkIfRequestIsSafe:e=>be.SAFE_RPC_METHODS.includes(e.method),isClient:"undefined"!=typeof window},Ie={wei:0,gwei:9,szabo:12,finney:15,ether:18};function Se(e,t=0){if(!Number.isInteger(t)||t<0)throw new Te({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 _e(e,t=0){if(!Number.isInteger(t)||t<0)throw new Te({decimals:t});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(e))throw new Oe({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}`)}class Oe 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 Te 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 ke=[{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"}],xe=[...ke,{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"}]}],Pe=[...ke,{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"}]}],Re=[{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"}]}];function Ue(e,t){return Se(e,t)}async function Le(...e){const t=await fetch(...e);if(!t.ok){throw new Error(`HTTP status code: ${t.status}`,{cause:t})}return t}class De{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 Le(r,{method:"GET",headers:e,signal:t,cache:s})).json()}async getBlob({headers:e,signal:t,...s}){const n=this.createUrl(s);return(await Le(n,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:s,...n}){const r=this.createUrl(n);return(await Le(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 Le(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 Le(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 Me={getFeatureValue(e,t){const s=t?.[e];return void 0===s?he.DEFAULT_FEATURES[e]:s},filterSocialsByPlatform(e){if(!e||!e.length)return e;let t=e;return pe.isTelegram()&&(pe.isIos()&&(t=t.filter((e=>"google"!==e))),pe.isMac()&&(t=t.filter((e=>"x"!==e))),pe.isAndroid()&&(t=t.filter((e=>!["facebook","x"].includes(e))))),pe.isMobile()&&(t=t.filter((e=>"facebook"!==e))),t},isSocialsEnabled:()=>Array.isArray(je.state.features?.socials)&&je.state.features?.socials.length>0||Array.isArray(je.state.remoteFeatures?.socials)&&je.state.remoteFeatures?.socials.length>0,isEmailEnabled:()=>Boolean(je.state.features?.email||je.state.remoteFeatures?.email)},Be=te({features:he.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:he.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),je={state:Be,subscribeKey:(e,t)=>ie(Be,e,t),setOptions(e){Object.assign(Be,e)},setRemoteFeatures(e){if(!e)return;const t={...Be.remoteFeatures,...e};Be.remoteFeatures=t,Be.remoteFeatures?.socials&&(Be.remoteFeatures.socials=Me.filterSocialsByPlatform(Be.remoteFeatures.socials)),Be.features?.pay&&(Be.remoteFeatures.email=!1,Be.remoteFeatures.socials=!1)},setFeatures(e){if(!e)return;Be.features||(Be.features=he.DEFAULT_FEATURES);const t={...Be.features,...e};Be.features=t,Be.features?.pay&&Be.remoteFeatures&&(Be.remoteFeatures.email=!1,Be.remoteFeatures.socials=!1)},setProjectId(e){Be.projectId=e},setCustomRpcUrls(e){Be.customRpcUrls=e},setAllWallets(e){Be.allWallets=e},setIncludeWalletIds(e){Be.includeWalletIds=e},setExcludeWalletIds(e){Be.excludeWalletIds=e},setFeaturedWalletIds(e){Be.featuredWalletIds=e},setTokens(e){Be.tokens=e},setTermsConditionsUrl(e){Be.termsConditionsUrl=e},setPrivacyPolicyUrl(e){Be.privacyPolicyUrl=e},setCustomWallets(e){Be.customWallets=e},setIsSiweEnabled(e){Be.isSiweEnabled=e},setIsUniversalProvider(e){Be.isUniversalProvider=e},setSdkVersion(e){Be.sdkVersion=e},setMetadata(e){Be.metadata=e},setDisableAppend(e){Be.disableAppend=e},setEIP6963Enabled(e){Be.enableEIP6963=e},setEnableCoinbase(e){Be.enableCoinbase=e},setDebug(e){Be.debug=e},setEnableWalletGuide(e){Be.enableWalletGuide=e},setEnableAuthLogger(e){Be.enableAuthLogger=e},setEnableWallets(e){Be.enableWallets=e},setPreferUniversalLinks(e){Be.experimental_preferUniversalLinks=e},setSIWX(e){if(e)for(const[t,s]of Object.entries(he.SIWX_DEFAULTS))e[t]??=s;Be.siwx=e},setConnectMethodsOrder(e){Be.features={...Be.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){Be.features={...Be.features,walletFeaturesOrder:e}},setSocialsOrder(e){Be.remoteFeatures={...Be.remoteFeatures,socials:e}},setCollapseWallets(e){Be.features={...Be.features,collapseWallets:e}},setEnableEmbedded(e){Be.enableEmbedded=e},setAllowUnsupportedChain(e){Be.allowUnsupportedChain=e},setManualWCControl(e){Be.manualWCControl=e},setEnableNetworkSwitch(e){Be.enableNetworkSwitch=e},setEnableMobileFullScreen(e){Be.enableMobileFullScreen=pe.isMobile()&&e},setEnableReconnect(e){Be.enableReconnect=e},setCoinbasePreference(e){Be.coinbasePreference=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach((([e,t])=>{t&&(Be.defaultAccountTypes[e]=t)}))},setUniversalProviderConfigOverride(e){Be.universalProviderConfigOverride=e},getUniversalProviderConfigOverride:()=>Be.universalProviderConfigOverride,getSnapshot:()=>ne(Be)},$e=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),Fe=te({...$e}),qe={state:Fe,subscribeKey:(e,t)=>ie(Fe,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=pe.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){Fe.message=$e.message,Fe.variant=$e.variant,Fe.svg=$e.svg,Fe.open=$e.open,Fe.autoClose=$e.autoClose},_showMessage({message:e,svg:t,variant:s="success",autoClose:n=$e.autoClose}){Fe.open?(Fe.open=!1,setTimeout((()=>{Fe.message=e,Fe.variant=s,Fe.svg=t,Fe.open=!0,Fe.autoClose=n}),150)):(Fe.message=e,Fe.variant=s,Fe.svg=t,Fe.open=!0,Fe.autoClose=n)}},We={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"}]}]},He=pe.getBlockchainApiUrl(),ze=te({clientId:null,api:new De({baseUrl:He,clientId:null}),supportedChains:{http:[],ws:[]}}),Ve={state:ze,async get(e){const{st:t,sv:s}=Ve.getSdkProperties(),n=je.state.projectId,r={...e.params||{},st:t,sv:s,projectId:n};return ze.api.get({...e,params:r})},getSdkProperties(){const{sdkType:e,sdkVersion:t}=je.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{ze.supportedChains.http.length||await Ve.getSupportedNetworks()}catch(e){return!1}return ze.supportedChains.http.includes(e)},async getSupportedNetworks(){try{const e=await Ve.get({path:"v1/supported-chains"});return ze.supportedChains=e,e}catch{return ze.supportedChains}},async fetchIdentity({address:e}){const t=ue.getIdentityFromCacheForAddress(e);if(t)return t;const s=await Ve.get({path:`/v1/identity/${e}`,params:{sender:as.state.activeCaipAddress?pe.getPlainAddress(as.state.activeCaipAddress):void 0}});return ue.updateIdentityCache({address:e,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:e,cursor:t,signal:s,cache:n,chainId:r}){if(!await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};const i=ue.getTransactionsCacheForAddress({address:e,chainId:r});if(i)return i;const o=await Ve.get({path:`/v1/account/${e}/history`,params:{cursor:t,chainId:r},signal:s,cache:n});return ue.updateTransactionsCache({address:e,chainId:r,timestamp:Date.now(),transactions:o}),o},fetchSwapQuote:async({amount:e,userAddress:t,from:s,to:n,gasPrice:r})=>await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId)?Ve.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 Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId)?Ve.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]},getAddressBalance:async({caipNetworkId:e,address:t,method:s="getAddressBalance",params:n})=>ze.api.post({path:`/v1?chainId=${e}&projectId=${je.state.projectId}`,body:{id:"1",jsonrpc:"2.0",method:s,params:n??{address:t}}}).then((e=>e.result)),async fetchTokenPrice({addresses:e,caipNetworkId:t=as.state.activeCaipNetwork?.caipNetworkId}){if(!await Ve.isNetworkSupported(t))return{fungibles:[]};const s=ue.getTokenPriceCacheForAddresses(e);if(s)return s;const n=await ze.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:je.state.projectId},headers:{"Content-Type":"application/json"}});return ue.updateTokenPriceCache({addresses:e,timestamp:Date.now(),tokenPrice:n}),n},fetchSwapAllowance:async({tokenAddress:e,userAddress:t})=>await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId)?Ve.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}=Ve.getSdkProperties();if(!await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return Ve.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 Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ze.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:he.CONVERT_SLIPPAGE_TOLERANCE},projectId:je.state.projectId,from:t,to:s,userAddress:n,disableEstimate:r}})},async generateApproveCalldata({from:e,to:t,userAddress:s}){const{st:n,sv:r}=Ve.getSdkProperties();if(!await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return Ve.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}=Ve.getSdkProperties();if(!await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))return qe.showError("Token Balance Unavailable"),{balances:[]};const i=`${t}:${e}`,o=ue.getBalanceCacheForCaipAddress(i);if(o)return o;const a=await Ve.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:s,st:n,sv:r}});return ue.updateBalanceCache({caipAddress:i,balance:a,timestamp:Date.now()}),a},lookupEnsName:async e=>await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId)?Ve.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]},async reverseLookupEnsName({address:e}){if(!await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))return[];const t=as.getAccountData()?.address;return Ve.get({path:`/v1/profile/reverse/${e}`,params:{sender:t,apiVersion:"2"}})},getEnsNameSuggestions:async e=>await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId)?Ve.get({path:`/v1/profile/suggestions/${e}`,params:{zone:"reown.id"}}):{suggestions:[]},registerEnsName:async({coinType:e,address:t,message:s,signature:n})=>await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId)?ze.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 Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))return"";return(await ze.api.post({path:"/v1/generators/onrampurl",params:{projectId:je.state.projectId},body:{destinationWallets:e,defaultNetwork:s,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:r}})).url},async getOnrampOptions(){if(!await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await Ve.get({path:"/v1/onramp/options"})}catch(e){return We}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:s,network:n}){try{if(!await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId))return null;return await ze.api.post({path:"/v1/onramp/quote",params:{projectId:je.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 Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId)?Ve.get({path:`/v1/sessions/${e}`}):[],revokeSmartSession:async(e,t,s)=>await Ve.isNetworkSupported(as.state.activeCaipNetwork?.caipNetworkId)?ze.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:je.state.projectId},body:{pci:t,signature:s}}):{success:!1},setClientId(e){ze.clientId=e,ze.api=new De({baseUrl:He,clientId:e})}},Ke=Object.freeze({enabled:!0,events:[]}),Ge=new De({baseUrl:pe.getAnalyticsUrl(),clientId:null}),Je=te({...Ke}),Ye={state:Je,subscribeKey:(e,t)=>ie(Je,e,t),async sendError(e,t){if(!Je.enabled)return;const s=Date.now();if(Je.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()}};Je.events.push(n);try{if("undefined"==typeof window)return;const{projectId:s,sdkType:n,sdkVersion:r}=je.state;await Ge.post({path:"/e",params:{projectId:s,st:n,sv:r||"html-wagmi-4.2.2"},body:{eventId:pe.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(){Je.enabled=!0},disable(){Je.enabled=!1},clearEvents(){Je.events=[]}};class Xe 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,Xe.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,Xe):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Ze(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 Xe?e:new Xe(s,t,e);throw Ye.sendError(n,n.category),n}function Qe(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 Ze(e,t)}}:(...e)=>{try{return r(...e)}catch(e){return Ze(e,t)}},s[n]=e}else s[n]=r})),s}const et=te({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),tt=Qe({state:et,subscribeNetworkImages:e=>se(et.networkImages,(()=>e(et.networkImages))),subscribeKey:(e,t)=>ie(et,e,t),subscribe:e=>se(et,(()=>e(et))),setWalletImage(e,t){et.walletImages[e]=t},setNetworkImage(e,t){et.networkImages[e]=t},setChainImage(e,t){et.chainImages[e]=t},setConnectorImage(e,t){et.connectorImages={...et.connectorImages,[e]:t}},setTokenImage(e,t){et.tokenImages[e]=t},setCurrencyImage(e,t){et.currencyImages[e]=t}}),st={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"},nt=te({networkImagePromises:{},tokenImagePromises:{}}),rt={async fetchWalletImage(e){if(e)return await gt._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;const t=this.getNetworkImageById(e);return t||(nt.networkImagePromises[e]||(nt.networkImagePromises[e]=gt._fetchNetworkImage(e)),await nt.networkImagePromises[e],this.getNetworkImageById(e))},async fetchTokenImage(e){if(e)return nt.tokenImagePromises[e]||(nt.tokenImagePromises[e]=gt._fetchTokenImage(e)),await nt.tokenImagePromises[e],this.getTokenImage(e)},getWalletImageById(e){if(e)return tt.state.walletImages[e]},getWalletImage:e=>e?.image_url?e?.image_url:e?.image_id?tt.state.walletImages[e.image_id]:void 0,getNetworkImage:e=>e?.assets?.imageUrl?e?.assets?.imageUrl:e?.assets?.imageId?tt.state.networkImages[e.assets.imageId]:void 0,getNetworkImageById(e){if(e)return tt.state.networkImages[e]},getConnectorImage:e=>e?.imageUrl?e.imageUrl:e?.info?.icon?e.info.icon:e?.imageId?tt.state.connectorImages[e.imageId]:void 0,getChainImage:e=>tt.state.networkImages[st[e]],getTokenImage(e){if(e)return tt.state.tokenImages[e]},getWalletImageUrl(e){if(!e)return"";const{projectId:t,sdkType:s,sdkVersion:n}=je.state,r=new URL(`${a.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}=je.state,r=new URL(`${a.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(st[e])},async getImageByToken(e,t){if("native"===e){const e=a.NATIVE_IMAGE_IDS_BY_NAMESPACE[t]??null;if(!e)return;return rt.fetchNetworkImage(e)}const[,s]=Object.entries(a.TOKEN_SYMBOLS_BY_ADDRESS).find((([t])=>t.toLowerCase()===e.toLowerCase()))??[];if(s)return rt.fetchTokenImage(s)}},it={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"}},ot={isCustomDeeplinkWallet:(e,t)=>e===it.PHANTOM.id?t===a.CHAIN.SOLANA||t===a.CHAIN.EVM||t===a.CHAIN.BITCOIN:e===it.SOLFLARE.id?t===a.CHAIN.SOLANA:e===it.COINBASE.id?t===a.CHAIN.SOLANA||t===a.CHAIN.EVM:e===it.BINANCE.id&&t===a.CHAIN.BITCOIN,handleMobileDeeplinkRedirect(e,t,s){const n=window.location.href,r=encodeURIComponent(n),i=s?.isCoinbaseDisabled??!1;if(e===it.PHANTOM.id&&!("phantom"in window)){const e=n.startsWith("https")?"https":"http",t=n.split("/")[2],s=encodeURIComponent(`${e}://${t}`),i=`${it.PHANTOM.url}/ul/browse/${r}?ref=${s}`;if(pe.isAndroid()){const e=`intent://browse/${r}?ref=${s}#Intent;scheme=phantom;package=${it.PHANTOM.androidPackage};end`;window.location.href=e}else window.location.href=i}if(e!==it.SOLFLARE.id||t!==a.CHAIN.SOLANA||"solflare"in window||(window.location.href=`${it.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),t===a.CHAIN.SOLANA&&(e!==it.COINBASE.id||!i&&"coinbaseSolana"in window||(window.location.href=`${it.COINBASE.url}/dapp?cb_url=${r}`)),t===a.CHAIN.EVM&&(e!==it.COINBASE.id||!i&&"coinbaseWalletExtension"in window||(window.location.href=`${it.COINBASE.evmDeeplink}?url=${r}`)),t===a.CHAIN.BITCOIN&&e===it.BINANCE.id&&!("binancew3w"in window)){const e=as.state.activeCaipNetwork,t=window.btoa("/pages/browser/index"),s=window.btoa(`url=${r}&defaultChainId=${e?.id??1}`),n=new URL(it.BINANCE.deeplink);n.searchParams.set("appId",it.BINANCE.appId),n.searchParams.set("startPagePath",t),n.searchParams.set("startPageQuery",s);const i=new URL(it.BINANCE.url);i.searchParams.set("_dp",window.btoa(n.toString())),window.location.href=i.toString()}}},at=pe.getAnalyticsUrl(),ct=new De({baseUrl:at,clientId:null}),lt=["MODAL_CREATED"],dt=te({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),ht={state:dt,subscribe:e=>se(dt,(()=>e(dt))),getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=je.state;return{projectId:e,st:t,sv:s||"html-wagmi-4.2.2"}},shouldFlushEvents(){const e=JSON.stringify(dt.pendingEvents).length/1024>45,t=dt.lastFlush+1e4<Date.now();return e||t},_setPendingEvent(e){try{let t=as.getAccountData()?.address;if("address"in e.data&&e.data.address&&(t=e.data.address),lt.includes(e.data.event)||"undefined"==typeof window)return;const s=as.getActiveCaipNetwork()?.caipNetworkId;this.state.pendingEvents.push({eventId:pe.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}}}),dt.reportedErrors.FORBIDDEN=!1;ht.shouldFlushEvents()&&ht._submitPendingEvents()}catch(e){console.warn("_setPendingEvent",e)}},sendEvent(e){dt.timestamp=Date.now(),dt.data=e;(je.state.features?.analytics||["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"].includes(e.event))&&ht._setPendingEvent(dt),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(e){dt.walletImpressions.push(e)},_transformPendingEventsForBatch(e){try{return e.filter((e=>"WALLET_IMPRESSION_V2"!==e.props.event))}catch{return e}},_submitPendingEvents(){if(dt.lastFlush=Date.now(),0!==dt.pendingEvents.length||0!==dt.walletImpressions.length)try{const e=ht._transformPendingEventsForBatch(dt.pendingEvents);dt.walletImpressions.length&&e.push({eventId:pe.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...dt.walletImpressions]}}),ct.sendBeacon({path:"/batch",params:ht.getSdkProperties(),body:e}),dt.reportedErrors.FORBIDDEN=!1,dt.pendingEvents=[],dt.walletImpressions=[]}catch(e){dt.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){dt.subscribedToVisibilityChange||"undefined"!=typeof document&&(dt.subscribedToVisibilityChange=!0,document?.addEventListener?.("visibilitychange",(()=>{"hidden"===document.visibilityState&&ht._submitPendingEvents()})),document?.addEventListener?.("freeze",(()=>{ht._submitPendingEvents()})),window?.addEventListener?.("pagehide",(()=>{ht._submitPendingEvents()})),setInterval((()=>{ht._submitPendingEvents()}),1e4))}},ut=pe.getApiUrl(),pt=new De({baseUrl:ut,clientId:null}),ft=te({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}}}),gt={state:ft,subscribeKey:(e,t)=>ie(ft,e,t),_getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=je.state;return{projectId:e,st:t||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions:e=>je.state.isUniversalProvider?e.filter((e=>Boolean(e.mobile_link||e.desktop_link||e.webapp_link))):e,async _fetchWalletImage(e){const t=`${pt.baseUrl}/getWalletImage/${e}`,s=await pt.getBlob({path:t,params:gt._getSdkProperties()});tt.setWalletImage(e,URL.createObjectURL(s))},async _fetchNetworkImage(e){const t=`${pt.baseUrl}/public/getAssetImage/${e}`,s=await pt.getBlob({path:t,params:gt._getSdkProperties()});tt.setNetworkImage(e,URL.createObjectURL(s))},async _fetchConnectorImage(e){const t=`${pt.baseUrl}/public/getAssetImage/${e}`,s=await pt.getBlob({path:t,params:gt._getSdkProperties()});tt.setConnectorImage(e,URL.createObjectURL(s))},async _fetchCurrencyImage(e){const t=`${pt.baseUrl}/public/getCurrencyImage/${e}`,s=await pt.getBlob({path:t,params:gt._getSdkProperties()});tt.setCurrencyImage(e,URL.createObjectURL(s))},async _fetchTokenImage(e){const t=`${pt.baseUrl}/public/getTokenImage/${e}`,s=await pt.getBlob({path:t,params:gt._getSdkProperties()});tt.setTokenImage(e,URL.createObjectURL(s))},_filterWalletsByPlatform(e){const t=e.length,s=pe.isMobile()?e?.filter((e=>{if(e.mobile_link||e.webapp_link)return!0;return Object.values(it).map((e=>e.id)).includes(e.id)})):e;return{filteredWallets:s,mobileFilteredOutWalletsLength:t-s.length}},fetchProjectConfig:async()=>(await pt.get({path:"/appkit/v1/config",params:gt._getSdkProperties()})).features,async fetchUsage(){try{const e=await pt.get({path:"/appkit/v1/project-limits",params:gt._getSdkProperties()}),{tier:t,isAboveMauLimit:s,isAboveRpcLimit:n}=e.planLimits,r="starter"===t,i=s||n;gt.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 pt.get({path:"/projects/v1/origins",params:gt._getSdkProperties()});return e}catch(e){if(e instanceof Error&&e.cause instanceof Response){const t=e.cause.status;if(t===a.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:e});if(t>=a.HTTP_STATUS_CODES.SERVER_ERROR&&t<600)throw new Error("SERVER_ERROR",{cause:e});return[]}return[]}},async fetchNetworkImages(){const e=as.getAllRequestedCaipNetworks(),t=e?.map((({assets:e})=>e?.imageId)).filter(Boolean).filter((e=>!rt.getNetworkImageById(e)));t&&await Promise.allSettled(t.map((e=>gt._fetchNetworkImage(e))))},async fetchConnectorImages(){const{connectors:e}=Ot.state,t=e.map((({imageId:e})=>e)).filter(Boolean);await Promise.allSettled(t.map((e=>gt._fetchConnectorImage(e))))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map((e=>gt._fetchCurrencyImage(e))))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map((e=>gt._fetchTokenImage(e))))},async fetchWallets(e){const t=e.exclude??[];gt._getSdkProperties().sv.startsWith("html-core-")&&t.push(...Object.values(it).map((e=>e.id)));const s=await pt.get({path:"/getWallets",params:{...gt._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:e.include?.join(","),exclude:t.join(",")}}),{filteredWallets:n,mobileFilteredOutWalletsLength:r}=gt._filterWalletsByPlatform(s?.data);return{data:n||[],count:s?.count,mobileFilteredOutWalletsLength:r}},async prefetchWalletRanks(){const e=Ot.state.connectors;if(!e?.length)return;const t={page:1,entries:20,badge:"certified"};if(t.names=e.map((e=>e.name)).join(","),as.state.activeChain===a.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 gt.fetchWallets(t);ft.explorerWallets=s,Ot.extendConnectorsWithExplorerWallets(s);const n=as.getRequestedCaipNetworkIds().join(",");ft.explorerFilteredWallets=s.filter((e=>e.chains?.some((e=>n.includes(e)))))},async fetchFeaturedWallets(){const{featuredWalletIds:e}=je.state;if(e?.length){const t={...gt._getSdkProperties(),page:1,entries:e?.length??4,include:e},{data:s}=await gt.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=>gt._fetchWalletImage(e)))),ft.featured=n,ft.allFeatured=n}},async fetchRecommendedWallets(){try{ft.isFetchingRecommendedWallets=!0;const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:s}=je.state,n=[...t??[],...s??[]].filter(Boolean),r={page:1,entries:4,include:e,exclude:n,chains:as.getRequestedCaipNetworkIds().join(",")},{data:i,count:o}=await gt.fetchWallets(r),a=ue.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=>gt._fetchWalletImage(e)))),ft.recommended=i,ft.allRecommended=i,ft.count=o??0}catch{}finally{ft.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e,entries:t,badge:s,include:n,exclude:r}){const{includeWalletIds:i,excludeWalletIds:o,featuredWalletIds:a}=je.state,c=as.getRequestedCaipNetworkIds().join(","),l=[...ft.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 gt.fetchWallets(d);ft.mobileFilteredOutWalletsLength=p+(ft.mobileFilteredOutWalletsLength??0);const f=h.slice(0,20).map((e=>e.image_id)).filter(Boolean);await Promise.allSettled(f.map((e=>gt._fetchWalletImage(e)))),ft.wallets=pe.uniqueBy([...ft.wallets,...gt._filterOutExtensions(h)],"id").filter((e=>e.chains?.some((e=>c.includes(e))))),ft.count=u>ft.count?u:ft.count,ft.page=e},async initializeExcludedWallets({ids:e}){const t={page:1,entries:e.length,include:e},{data:s}=await gt.fetchWallets(t);s&&s.forEach((e=>{ft.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}=je.state,c=as.getRequestedCaipNetworkIds().join(",");ft.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 gt.fetchWallets(l);ht.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=>gt._fetchWalletImage(e))),pe.wait(300)]),ft.search=gt._filterOutExtensions(d)},initPromise(e,t){const s=ft.promises[e];return s||(ft.promises[e]=t())},prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:n=!0,fetchWalletRanks:r=!0}={}){const i=[e&&gt.initPromise("connectorImages",gt.fetchConnectorImages),t&&gt.initPromise("featuredWallets",gt.fetchFeaturedWallets),s&&gt.initPromise("recommendedWallets",gt.fetchRecommendedWallets),n&&gt.initPromise("networkImages",gt.fetchNetworkImages),r&&gt.initPromise("walletRanks",gt.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){je.state.features?.analytics&&gt.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:e}=await pt.get({path:"/getAnalyticsConfig",params:gt._getSdkProperties()});je.setFeatures({analytics:e})}catch(e){je.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!e?.length)return ft.featured=ft.allFeatured,void(ft.recommended=ft.allRecommended);const t=as.getRequestedCaipNetworkIds().join(",");ft.featured=ft.allFeatured.filter((e=>e.chains?.some((e=>t.includes(e))))),ft.recommended=ft.allRecommended.filter((e=>e.chains?.some((e=>t.includes(e))))),ft.filteredWallets=ft.wallets.filter((e=>e.chains?.some((e=>t.includes(e)))))},clearFilterByNamespaces(){ft.filteredWallets=[]},setFilterByNamespace(e){if(!e)return ft.featured=ft.allFeatured,void(ft.recommended=ft.allRecommended);const t=as.getRequestedCaipNetworkIds().join(",");ft.featured=ft.allFeatured.filter((e=>e.chains?.some((e=>t.includes(e))))),ft.recommended=ft.allRecommended.filter((e=>e.chains?.some((e=>t.includes(e))))),ft.filteredWallets=ft.wallets.filter((e=>e.chains?.some((e=>t.includes(e)))))}},mt={filterOutDuplicatesByRDNS(e){const t=je.state.enableEIP6963?Ot.state.connectors:[],s=ue.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")&&pe.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=Ot.state.connectors.filter((e=>"ANNOUNCED"===e.type||"INJECTED"===e.type||"MULTI_CHAIN"===e.type)),s=ue.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}=Ot.state,{featuredWalletIds:s}=je.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||je.state.features?.connectMethodsOrder,n=t||Ot.state.connectors;if(s)return s;const{injected:r,announced:i}=yt.getConnectorsByType(n,gt.state.recommended,gt.state.featured),o=r.filter(yt.showConnector),a=i.filter(yt.showConnector);return o.length||a.length?["wallet","email","social"]:he.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){const t=Boolean(e.rdns)&&gt.state.excludedWallets.some((t=>t.rdns===e.rdns)),s=Boolean(e.name)&&gt.state.excludedWallets.some((t=>o.isLowerCaseMatch(t.name,e.name)));return t||s},markWalletsWithDisplayIndex:e=>e.map(((e,t)=>({...e,display_index:t}))),filterWalletsByWcSupport:e=>qt.state.wcBasic?e.filter((e=>e.supports_wc)):pe.isMobile()?e.filter((e=>e.supports_wc||he.MANDATORY_WALLET_IDS_ON_MOBILE.includes(e.id))):e,getWalletConnectWallets(e){const t=[...gt.state.featured,...gt.state.recommended];gt.state.filteredWallets?.length>0?t.push(...gt.state.filteredWallets):t.push(...e);const s=pe.uniqueBy(t,"id"),n=mt.markWalletsAsInstalled(s),r=mt.filterWalletsByWcSupport(n);return mt.markWalletsWithDisplayIndex(r)}},yt={getConnectorsByType(e,t,s){const{customWallets:n}=je.state,r=ue.getRecentWallets(),i=mt.filterOutDuplicateWallets(t),o=mt.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)&&gt.state.excludedWallets.some((e=>Boolean(e.rdns)&&e.rdns===t)),n=Boolean(e.name)&&gt.state.excludedWallets.some((t=>o.isLowerCaseMatch(t.name,e.name)));if("INJECTED"===e.type){if("Browser Wallet"===e.name){if(!pe.isMobile())return!1;if(pe.isMobile()&&!t&&!qt.checkInstalled())return!1}if(s||n)return!1}return"ANNOUNCED"!==e.type&&"EXTERNAL"!==e.type||!s&&!n},getIsConnectedWithWC(){const e=Array.from(as.state.chains.values()).some((e=>Ot.getConnectorId(e.namespace)===a.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=je.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===a.CONNECTOR_ID.BASE_ACCOUNT?0:e.id===a.CONNECTOR_ID.COINBASE||e.id===a.CONNECTOR_ID.COINBASE_SDK?1:2,sortConnectorsByPriority:e=>[...e].sort(((e,t)=>yt.getPriority(e)-yt.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&&!pe.isMobile())return{accounts:[],chainId:void 0};if(e.id===a.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=ue.getRecentWallets(),s=Ot.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")&&pe.isMobile()){const e=r.indexOf("io.metamask.mobile");r[e]="io.metamask"}return e.filter((e=>!r.includes(String(e?.rdns))))},hasWalletConnector:e=>Ot.state.connectors.some((t=>t.id===e.id||t.name===e.name)),isWalletCompatibleWithCurrentChain(e){const t=as.state.activeChain;return!t||!e.chains||e.chains.some((e=>{const s=e.split(":")[0];return t===s}))},getFilteredRecentWallets(){return ue.getRecentWallets().filter((e=>!mt.isExcluded(e))).filter((e=>!this.hasWalletConnector(e))).filter((e=>this.isWalletCompatibleWithCurrentChain(e)))},getCappedRecommendedWallets(e){const{connectors:t}=Ot.state,{customWallets:s,featuredWalletIds:n}=je.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=Me.isEmailEnabled(),a=Me.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 mt.filterOutDuplicateWallets(e).slice(0,d)},processConnectorsByType(e,t=!0){const s=yt.sortConnectorsByExplorerWallet([...e]);return t?s.filter(yt.showConnector):s},connectorList(){const e=yt.getConnectorsByType(Ot.state.connectors,gt.state.recommended,gt.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!==a.CONNECTOR_ID.COINBASE_SDK&&e.id!==a.CONNECTOR_ID.BASE_ACCOUNT))),c=e.recommended,l=e.featured,d=yt.getConnectorTypeOrder({custom:r,recent:i,announced:t,injected:s,multiChain:n,recommended:c,featured:l,external:o}),h=Ot.state.connectors.find((e=>"walletConnect"===e.id)),u=pe.isMobile(),p=[];for(const e of d)switch(e){case"walletConnect":!u&&h&&p.push({kind:"connector",subtype:"walletConnect",connector:h});break;case"recent":yt.getFilteredRecentWallets().forEach((e=>p.push({kind:"wallet",subtype:"recent",wallet:e})));break;case"injected":n.forEach((e=>p.push({kind:"connector",subtype:"multiChain",connector:e}))),t.forEach((e=>p.push({kind:"connector",subtype:"announced",connector:e}))),s.forEach((e=>p.push({kind:"connector",subtype:"injected",connector:e})));break;case"featured":l.forEach((e=>p.push({kind:"wallet",subtype:"featured",wallet:e})));break;case"custom":yt.getFilteredCustomWallets(r??[]).forEach((e=>p.push({kind:"wallet",subtype:"custom",wallet:e})));break;case"external":o.forEach((e=>p.push({kind:"connector",subtype:"external",connector:e})));break;case"recommended":yt.getCappedRecommendedWallets(c).forEach((e=>p.push({kind:"wallet",subtype:"recommended",wallet:e})));break;default:console.warn(`Unknown connector type: ${e}`)}return p},hasInjectedConnectors:()=>Ot.state.connectors.filter((e=>("INJECTED"===e.type||"ANNOUNCED"===e.type||"MULTI_CHAIN"===e.type)&&"Browser Wallet"!==e.name&&"WalletConnect"!==e.name)).length},wt=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],bt=te({view:"Connect",history:["Connect"],transactionStack:[]}),vt=Qe({state:bt,subscribeKey:(e,t)=>ie(bt,e,t),pushTransactionStack(e){bt.transactionStack.push(e)},popTransactionStack(e){const t=bt.transactionStack.pop();if(!t)return;const{onSuccess:s,onError:n,onCancel:r}=t;switch(e){case"success":s?.();break;case"error":n?.(),vt.goBack();break;case"cancel":r?.(),vt.goBack()}},push(e,t){let s=e,n=t;gt.state.plan.hasExceededUsageLimit&&wt.includes(e)&&(s="UsageExceeded",n=void 0),s!==bt.view&&(bt.view=s,bt.history.push(s),bt.data=n)},reset(e,t){bt.view=e,bt.history=[e],bt.data=t},replace(e,t){bt.history.at(-1)===e||(bt.view=e,bt.history[bt.history.length-1]=e,bt.data=t)},goBack(){const e=as.state.activeCaipAddress,t="ConnectingFarcaster"===vt.state.view,s=!e&&t;if(bt.history.length>1){bt.history.pop();const[t]=bt.history.slice(-1);if(t){const s="Connect"===t;bt.view=e&&s?"Account":t}}else ds.close();bt.data?.wallet&&(bt.data.wallet=void 0),bt.data?.redirectView&&(bt.data.redirectView=void 0),setTimeout((()=>{if(s){as.setAccountProp("farcasterUrl",void 0,as.state.activeChain);const e=Ot.getAuthConnector();e?.provider?.reload();const t=ne(je.state);e?.provider?.syncDappData?.({metadata:t.metadata,sdkVersion:t.sdkVersion,projectId:t.projectId,sdkType:t.sdkType})}}),100)},goBackToIndex(e){if(bt.history.length>1){bt.history=bt.history.slice(0,e+1);const[t]=bt.history.slice(-1);t&&(bt.view=t)}},goBackOrCloseModal(){vt.state.history.length>1?vt.goBack():ds.close()}}),Et=te({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Ct={state:Et,subscribe:e=>se(Et,(()=>e(Et))),setThemeMode(e){Et.themeMode=e;try{const t=Ot.getAuthConnector();if(t){const s=Ct.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:s,w3mThemeVariables:M(s,e)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(e){Et.themeVariables={...Et.themeVariables,...e};try{const e=Ot.getAuthConnector();if(e){const t=Ct.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:M(Et.themeVariables,Et.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot:()=>ne(Et)},Nt=Qe(Ct),At=Object.fromEntries(l.map((e=>[e,void 0]))),It=Object.fromEntries(l.map((e=>[e,!0]))),St=te({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:At,filterByNamespaceMap:It}),_t={state:St,subscribe:e=>se(St,(()=>{e(St)})),subscribeKey:(e,t)=>ie(St,e,t),initialize(e){e.forEach((e=>{const t=ue.getConnectedConnectorId(e);t&&Ot.setConnectorId(t,e)}))},setActiveConnector(e){e&&(St.activeConnector=re(e))},setConnectors(e){e.filter((e=>!St.allConnectors.some((t=>t.id===e.id&&Ot.getConnectorName(t.name)===Ot.getConnectorName(e.name)&&t.chain===e.chain)))).forEach((e=>{"MULTI_CHAIN"!==e.type&&St.allConnectors.push(re(e))}));const t=Ot.getEnabledNamespaces(),s=Ot.getEnabledConnectors(t);St.connectors=Ot.mergeMultiChainConnectors(s)},filterByNamespaces(e){Object.keys(St.filterByNamespaceMap).forEach((e=>{St.filterByNamespaceMap[e]=!1})),e.forEach((e=>{St.filterByNamespaceMap[e]=!0})),Ot.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){St.filterByNamespaceMap[e]=t,Ot.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const e=Ot.getEnabledNamespaces(),t=Ot.getEnabledConnectors(e),s=Ot.areAllNamespacesEnabled();St.connectors=Ot.mergeMultiChainConnectors(t),s?gt.clearFilterByNamespaces():gt.filterByNamespaces(e)},getEnabledNamespaces:()=>Object.entries(St.filterByNamespaceMap).filter((([e,t])=>t)).map((([e])=>e)),getEnabledConnectors:e=>St.allConnectors.filter((t=>e.includes(t.chain))),areAllNamespacesEnabled:()=>Object.values(St.filterByNamespaceMap).every((e=>e)),mergeMultiChainConnectors(e){const t=Ot.generateConnectorMapByName(e),s=[];return t.forEach((e=>{const t=e[0],n=t?.id===a.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=Ot.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===a.CONNECTOR_ID.AUTH){const t=e,s=ne(je.state),n=Nt.getSnapshot().themeMode,r=Nt.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:M(r,n)}),Ot.setConnectors([e])}else Ot.setConnectors([e])},getAuthConnector(e){const t=e||as.state.activeChain,s=St.connectors.find((e=>e.id===a.CONNECTOR_ID.AUTH));if(s){if(s?.connectors?.length){const e=s.connectors.find((e=>e.chain===t));return e}return s}},getAnnouncedConnectorRdns:()=>St.connectors.filter((e=>"ANNOUNCED"===e.type)).map((e=>e.info?.rdns)),getConnectorById:e=>yt.sortConnectorsByPriority(St.allConnectors).find((t=>t.id===e)),getConnector({id:e,namespace:t}){const s=t||as.state.activeChain,n=St.allConnectors.filter((e=>e.chain===s)),r=yt.sortConnectorsByPriority(n).find((t=>t.id===e||t.explorerId===e));return r},syncIfAuthConnector(e){if("AUTH"!==e.id)return;const t=e,s=ne(je.state),n=Nt.getSnapshot().themeMode,r=Nt.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:M(r,n)})},getConnectorsByNamespace(e){const t=St.allConnectors.filter((t=>t.chain===e));return Ot.mergeMultiChainConnectors(t)},canSwitchToSmartAccount:e=>as.checkIfSmartAccountEnabled()&&xt(e)===be.ACCOUNT_TYPES.EOA,selectWalletConnector(e){const t=vt.state.data?.redirectView,s=as.state.activeChain,n=s?Ot.getConnector({id:e.id,namespace:s}):void 0;ot.handleMobileDeeplinkRedirect(n?.explorerId||e.id,as.state.activeChain,{isCoinbaseDisabled:!1===je.state.enableCoinbase}),n?vt.push("ConnectingExternal",{connector:n,wallet:e,redirectView:t}):vt.push("ConnectingWalletConnect",{wallet:e,redirectView:t})},getConnectors:e=>e?Ot.getConnectorsByNamespace(e):Ot.mergeMultiChainConnectors(St.allConnectors),setFilterByNamespace(e){St.filterByNamespace=e,St.connectors=Ot.getConnectors(e),gt.setFilterByNamespace(e)},setConnectorId(e,t){e&&(St.activeConnectorIds={...St.activeConnectorIds,[t]:e},ue.setConnectedConnectorId(t,e))},removeConnectorId(e){St.activeConnectorIds={...St.activeConnectorIds,[e]:void 0},ue.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return St.activeConnectorIds[e]},isConnected:e=>e?Boolean(St.activeConnectorIds[e]):Object.values(St.activeConnectorIds).some((e=>Boolean(e))),resetConnectorIds(){St.activeConnectorIds={...At}},extendConnectorsWithExplorerWallets(e){St.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=Ot.getEnabledNamespaces(),s=Ot.getEnabledConnectors(t);St.connectors=Ot.mergeMultiChainConnectors(s)},async connect(e={}){const{namespace:t}=e;return Ot.setFilterByNamespace(t),vt.push("Connect",{addWalletForNamespace:t}),new Promise(((e,s)=>{if(t){const n=as.subscribeChainProp("accountState",(t=>{t?.caipAddress&&(e({caipAddress:t?.caipAddress}),n())}),t),r=ds.subscribeKey("open",(e=>{e||(s(new Error("Modal closed")),r())}))}else{const t=as.subscribeKey("activeCaipAddress",(s=>{s&&(e({caipAddress:s}),t())})),n=ds.subscribeKey("open",(e=>{e||(s(new Error("Modal closed")),n())}))}}))}},Ot=Qe(_t),Tt={checkNamespaceConnectorId:(e,t)=>Ot.getConnectorId(e)===t,isSocialProvider:e=>he.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&&Ot.setActiveConnector(t),r?.(pe.isMobile()&&e),n){const e=ds.subscribeKey("open",(t=>{t||(vt.state.view!==n&&vt.replace(n),e(),a(new Error("Modal closed")))}))}const c=as.subscribeKey("activeCaipAddress",(e=>{e&&(i?.(),s&&ds.close(),c(),o(T.parseCaipAddress(e)))}))})),connectExternal:e=>new Promise(((t,s)=>{const n=as.subscribeKey("activeCaipAddress",(e=>{e&&(ds.close(),n(),t(T.parseCaipAddress(e)))}));qt.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,c=null;const l=t||as.state.activeChain,d=as.subscribeKey("activeCaipAddress",(e=>{e&&(s&&ds.close(),d())}));return new Promise(((t,s)=>{async function d(n){if(n.data?.resultUri)if(n.origin===a.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",d,!1);try{const r=Ot.getAuthConnector(l);if(r&&!o){i&&i.close(),o=!0;const a=n.data.resultUri;ht.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:e}}),ue.setConnectedSocialProvider(e),await qt.connectExternal({id:r.id,type:r.type,socialUri:a},r.chain);const c=as.state.activeCaipAddress;if(!c)return void s(new Error("Failed to connect"));t(T.parseCaipAddress(c)),ht.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:e}})}}catch(t){ht.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:pe.parseError(t)}}),s(new Error("Failed to connect"))}}else ht.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:e,message:"Untrusted Origin"}})}!async function(){if(ht.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:e}}),"farcaster"===e){n?.();const t=ds.subscribeKey("open",(n=>{n||"farcaster"!==e||(s(new Error("Popup closed")),r?.(),t())})),i=Ot.getAuthConnector();if(i){const e=as.getAccountData(l);if(!e?.farcasterUrl)try{const{url:e}=await i.provider.getFarcasterUri();as.setAccountProp("farcasterUrl",e,l)}catch{s(new Error("Failed to connect to farcaster"))}}}else{const t=Ot.getAuthConnector();c=pe.returnOpenHref(`${a.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(c&&n){c.location.href=n,i=c;const e=setInterval((()=>{i?.closed&&!o&&(s(new Error("Popup closed")),clearInterval(e))}),1e3);window.addEventListener("message",d,!1)}else c?.close(),s(new Error("Failed to initiate social connection"))}}catch{s(new Error("Failed to initiate social connection")),c?.close()}}}()}))},connectEmail:({closeModalOnConnect:e=!0,redirectViewOnModalClose:t="Connect",onOpen:s,onConnect:n})=>new Promise(((r,i)=>{if(s?.(),t){const e=ds.subscribeKey("open",(s=>{s||(vt.state.view!==t&&vt.replace(t),e(),i(new Error("Modal closed")))}))}const o=as.subscribeKey("activeCaipAddress",(t=>{t&&(n?.(),e&&ds.close(),o(),r(T.parseCaipAddress(t)))}))})),async updateEmail(){const e=ue.getConnectedConnectorId(as.state.activeChain),t=Ot.getAuthConnector();if(!t)throw new Error("No auth connector found");if(e!==a.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const s=t.provider.getEmail()??"";return await ds.open({view:"UpdateEmailWallet",data:{email:s,redirectView:void 0}}),new Promise(((e,n)=>{const r=setInterval((()=>{const n=t.provider.getEmail()??"";n!==s&&(ds.close(),clearInterval(r),i(),e({email:n}))}),1e3),i=ds.subscribeKey("open",(e=>{e||("Connect"!==vt.state.view&&vt.push("Connect"),clearInterval(r),i(),n(new Error("Modal closed")))}))}))},canSwitchToSmartAccount:e=>as.checkIfSmartAccountEnabled()&&xt(e)===be.ACCOUNT_TYPES.EOA};function kt(){const e=as.state.activeCaipNetwork?.chainNamespace||"eip155";return`${e}:${as.state.activeCaipNetwork?.id||1}:${he.NATIVE_TOKEN_ADDRESS[e]}`}function xt(e){const t=as.getAccountData(e)?.preferredAccountType;return t}function Pt(e){return e?as.state.chains.get(e)?.networkState?.caipNetwork:as.state.activeCaipNetwork}const Rt={getConnectionStatus(e,t){const s=Ot.state.activeConnectorIds[t],n=qt.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(je.state.remoteFeatures?.multiWallet),s=Ot.state.activeConnectorIds[e],n=qt.getConnections(e),r=(qt.state.recentConnections.get(e)??[]).filter((e=>Ot.getConnectorById(e.connectorId))),i=Rt.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=qt.state.wcUri;if(e?.mobile_link&&s)try{qt.setWcError(!1);const{mobile_link:n,link_mode:r,name:i}=e,o=pe.appendPayToUri(s,t),{redirect:a,redirectUniversalLink:c,href:l}=pe.formatNativeUrl(n,o,r),d=a,h=c,u=pe.isIframe()?"_top":"_self";qt.setWcLinking({name:i,href:l}),qt.setRecentWallet(e),je.state.experimental_preferUniversalLinks&&h?pe.openHref(h,u):pe.openHref(d,u)}catch(t){ht.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}}),qt.setWcError(!0)}}},Ut=te({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1,connectingWallet:void 0}),Lt={state:Ut,subscribe:e=>se(Ut,(()=>e(Ut))),subscribeOpen:e=>ie(Ut,"open",e),set(e){Object.assign(Ut,{...Ut,...e})}},Dt=te({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Mt={state:Dt,subscribe:e=>se(Dt,(()=>e(Dt))),setLastNetworkInView(e){Dt.lastNetworkInView=e},async fetchTransactions(e){if(!e)throw new Error("Transactions can't be fetched without an accountAddress");Dt.loading=!0;try{const t=await Ve.fetchTransactions({account:e,cursor:Dt.next,chainId:as.state.activeCaipNetwork?.caipNetworkId}),s=Bt.filterSpamTransactions(t.data),n=Bt.filterByConnectedChain(s),r=[...Dt.transactions,...n];Dt.loading=!1,Dt.transactions=r,Dt.transactionsByYear=Bt.groupTransactionsByYearAndMonth(Dt.transactionsByYear,n),Dt.empty=0===r.length,Dt.next=t.next?t.next:void 0}catch(t){const s=as.state.activeChain;ht.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:je.state.projectId,cursor:Dt.next,isSmartAccount:xt(s)===be.ACCOUNT_TYPES.SMART_ACCOUNT}}),qe.showError("Failed to fetch transactions"),Dt.loading=!1,Dt.empty=!0,Dt.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=as.state.activeCaipNetwork?.caipNetworkId;return e.filter((e=>e.metadata.chain===t))},clearCursor(){Dt.next=void 0},resetTransactions(){Dt.transactions=[],Dt.transactionsByYear={},Dt.lastNetworkInView=void 0,Dt.loading=!1,Dt.empty=!1,Dt.next=void 0}},Bt=Qe(Mt,"API_ERROR"),jt=te({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,wcFetchingUri:!1,buffering:!1,status:"disconnected"});let $t;const Ft={state:jt,subscribe:e=>se(jt,(()=>e(jt))),subscribeKey:(e,t)=>ie(jt,e,t),_getClient:()=>jt._client,setClient(e){jt._client=re(e)},initialize(e){const t=e.filter((e=>Boolean(e.namespace))).map((e=>e.namespace));qt.syncStorageConnections(t)},syncStorageConnections(e){const t=ue.getConnections(),s=e??Array.from(as.state.chains.keys());for(const e of s){const s=t[e]??[],n=new Map(jt.recentConnections);n.set(e,s),jt.recentConnections=n}},getConnections:e=>e?jt.connections.get(e)??[]:[],hasAnyConnection(e){const t=qt.state.connections;return Array.from(t.values()).flatMap((e=>e)).some((({connectorId:t})=>t===e))},async connectWalletConnect({cache:e="auto"}={}){jt.wcFetchingUri=!0;const t=pe.isTelegram()||pe.isSafari()&&pe.isIos();try{if("always"===e||"auto"===e&&t){if($t)return await $t,void($t=void 0);if(!pe.isPairingExpired(jt?.wcPairingExpiry)){const e=jt.wcUri;return void(jt.wcUri=e)}$t=qt._getClient()?.connectWalletConnect?.(),qt.state.status="connecting",await $t,$t=void 0,jt.wcPairingExpiry=void 0,qt.state.status="connected"}else await(qt._getClient()?.connectWalletConnect?.())}catch(e){throw jt.wcError=!0,jt.wcFetchingUri=!1,jt.status="disconnected",$t=void 0,e}},async connectExternal(e,t,s=!0){const n=await(qt._getClient()?.connectExternal?.(e));s&&as.setActiveNamespace(t);const r=Ot.state.allConnectors.find((t=>t.id===e?.id)),i="AUTH"===e.type?"email":"browser";return ht.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:i,name:r?.name||"Unknown",view:vt.state.view,walletRank:r?.explorerWallet?.order}}),n},async reconnectExternal(e){await(qt._getClient()?.reconnectExternal?.(e));const t=e.chain||as.state.activeChain;t&&Ot.setConnectorId(e.id,t)},async setPreferredAccountType(e,t){if(!t)return;ds.setLoading(!0,as.state.activeChain);const s=Ot.getAuthConnector();s&&(as.setAccountProp("preferredAccountType",e,t),await s.provider.setPreferredAccount(e),ue.setPreferredAccountTypes(Object.entries(as.state.chains).reduce(((e,[t,s])=>{const n=t,r=xt(n);return void 0!==r&&(e[n]=r),e}),{})),await qt.reconnectExternal(s),ds.setLoading(!1,as.state.activeChain),ht.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:as.state.activeCaipNetwork?.caipNetworkId||""}}))},signMessage:async e=>qt._getClient()?.signMessage(e),parseUnits:(e,t)=>qt._getClient()?.parseUnits(e,t),formatUnits:(e,t)=>qt._getClient()?.formatUnits(e,t),updateBalance:e=>qt._getClient()?.updateBalance(e),sendTransaction:async e=>qt._getClient()?.sendTransaction(e),getCapabilities:async e=>qt._getClient()?.getCapabilities(e),grantPermissions:async e=>qt._getClient()?.grantPermissions(e),walletGetAssets:async e=>qt._getClient()?.walletGetAssets(e)??{},estimateGas:async e=>qt._getClient()?.estimateGas(e),writeContract:async e=>qt._getClient()?.writeContract(e),writeSolanaTransaction:async e=>qt._getClient()?.writeSolanaTransaction(e),getEnsAddress:async e=>qt._getClient()?.getEnsAddress(e),getEnsAvatar:async e=>qt._getClient()?.getEnsAvatar(e),checkInstalled:e=>qt._getClient()?.checkInstalled?.(e)||!1,resetWcConnection(){jt.wcUri=void 0,jt.wcPairingExpiry=void 0,jt.wcLinking=void 0,jt.recentWallet=void 0,jt.wcFetchingUri=!1,jt.status="disconnected",Bt.resetTransactions(),ue.deleteWalletConnectDeepLink(),ue.deleteRecentWallet(),Lt.set({connectingWallet:void 0})},resetUri(){jt.wcUri=void 0,jt.wcPairingExpiry=void 0,$t=void 0,jt.wcFetchingUri=!1,Lt.set({connectingWallet:void 0})},finalizeWcConnection(e){const{wcLinking:t,recentWallet:s}=qt.state;t&&ue.setWalletConnectDeepLink(t),s&&ue.setAppKitRecent(s),e&&ht.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:t?"mobile":"qrcode",name:vt.state.data?.wallet?.name||"Unknown",view:vt.state.view,walletRank:s?.order}})},setWcBasic(e){jt.wcBasic=e},setUri(e){jt.wcUri=e,jt.wcFetchingUri=!1,jt.wcPairingExpiry=pe.getPairingExpiry()},setWcLinking(e){jt.wcLinking=e},setWcError(e){jt.wcError=e,jt.wcFetchingUri=!1,jt.buffering=!1},setRecentWallet(e){jt.recentWallet=e},setBuffering(e){jt.buffering=e},setStatus(e){jt.status=e},setIsSwitchingConnection(e){jt.isSwitchingConnection=e},async disconnect({id:e,namespace:t,initialDisconnect:s}={}){try{await(qt._getClient()?.disconnect({id:e,chainNamespace:t,initialDisconnect:s}))}catch(e){throw new Xe("Failed to disconnect","INTERNAL_SDK_ERROR",e)}},async disconnectConnector({id:e,namespace:t}){try{await(qt._getClient()?.disconnectConnector({id:e,namespace:t}))}catch(e){throw new Xe("Failed to disconnect connector","INTERNAL_SDK_ERROR",e)}},setConnections(e,t){const s=new Map(jt.connections);s.set(t,e),jt.connections=s},async handleAuthAccountSwitch({address:e,namespace:t}){const s=as.getAccountData(t),n=s?.user?.accounts?.find((e=>"smartAccount"===e.type)),r=n&&n.address.toLowerCase()===e.toLowerCase()&&Tt.canSwitchToSmartAccount(t)?"smartAccount":"eoa";await qt.setPreferredAccountType(r,t)},async handleActiveConnection({connection:e,namespace:t,address:s}){const n=Ot.getConnectorById(e.connectorId),r=e.connectorId===a.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${e.connectorId}`);if(!r){const e=await qt.connectExternal({id:n.id,type:n.type,provider:n.provider,address:s,chain:t},t);return e?.address}return s&&await qt.handleAuthAccountSwitch({address:s,namespace:t}),s},async handleDisconnectedConnection({connection:e,namespace:t,address:s,closeModalOnConnect:n}){const r=Ot.getConnectorById(e.connectorId),i=e.auth?.name?.toLowerCase(),o=e.connectorId===a.CONNECTOR_ID.AUTH,c=e.connectorId===a.CONNECTOR_ID.WALLET_CONNECT;if(!r)throw new Error(`No connector found for connection: ${e.connectorId}`);let l;if(o)if(i&&Tt.isSocialProvider(i)){const{address:e}=await Tt.connectSocial({social:i,closeModalOnConnect:n,onOpenFarcaster(){ds.open({view:"ConnectingFarcaster"})},onConnect(){vt.replace("ProfileWallets")}});l=e}else{const{address:e}=await Tt.connectEmail({closeModalOnConnect:n,onOpen(){ds.open({view:"EmailLogin"})},onConnect(){vt.replace("ProfileWallets")}});l=e}else if(c){const{address:e}=await Tt.connectWalletConnect({walletConnect:!0,connector:r,closeModalOnConnect:n,onOpen(e){const t=e?"AllWallets":"ConnectingWalletConnect";ds.state.open?vt.push(t):ds.open({view:t})},onConnect(){vt.replace("ProfileWallets")}});l=e}else{const e=await qt.connectExternal({id:r.id,type:r.type,provider:r.provider,chain:t},t);e&&(l=e.address)}return o&&s&&await qt.handleAuthAccountSwitch({address:s,namespace:t}),l},async switchConnection({connection:e,address:t,namespace:s,closeModalOnConnect:n,onChange:r}){let i;const o=as.getAccountData(s)?.caipAddress;if(o){const{address:e}=T.parseCaipAddress(o);i=e}const a=Rt.getConnectionStatus(e,s);switch(a){case"connected":case"active":{const n=await qt.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 qt.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}`)}}},qt=Qe(Ft),Wt={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})=>Ue(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 Ht;async function zt(){if(!Ht){const{createPublicClient:e,http:t,defineChain:s}=await Promise.resolve().then((function(){return require("./index-395b933d.cjs")}));Ht={createPublicClient:e,http:t,defineChain:s}}return Ht}const Vt={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 zt(),{chainId:s}=T.parseCaipNetworkId(e.caipNetworkId);return t({...e,id:Number(s)})},async createViemPublicClient(e){const{createPublicClient:t,http:s}=await zt(),n=je.state.projectId,r=await Vt.getViemChain(e);if(!r)throw new Error(`Chain ${e.caipNetworkId} not found in viem/chains`);return t({chain:r,transport:s(Vt.getBlockchainApiRpcUrl(e.caipNetworkId,n))})}},Kt={async getMyTokensWithBalance(e={forceUpdate:void 0,caipNetwork:as.state.activeCaipNetwork,address:as.getAccountData()?.address}){const{forceUpdate:t,caipNetwork:s,address:n}=e,r=Ot.getConnectorId("eip155")===a.CONNECTOR_ID.AUTH;if(!n)return[];const i=s?`${s.caipNetworkId}:${n}`:n,o=ue.getBalanceCacheForCaipAddress(i);if(o)return o.balances;if(s&&s.chainNamespace===a.CHAIN.EVM&&r){const e=await this.getEIP155Balances(n,s);if(e)return this.filterLowQualityTokens(e)}const c=await Ve.getBalance(n,s?.caipNetworkId,t);return this.filterLowQualityTokens(c.balances)},async getEIP155Balances(e,t){try{const s=Wt.getChainIdHexFromCAIP2ChainId(t.caipNetworkId),n=await qt.getCapabilities(e);if(!n?.[s]?.assetDiscovery?.supported)return null;const r=await qt.walletGetAssets({account:e,chainFilter:[s]});if(!Wt.isWalletGetAssetsResponse(r))return null;const i=(r[s]||[]).map((e=>Wt.createBalance(e,t.caipNetworkId)));return ue.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 Vt.createViemPublicClient(s),{address:r}=T.parseCaipAddress(e),[{result:i},{result:o},{result:a},{result:c}]=await n.multicall({contracts:[{address:t,functionName:"name",args:[],abi:Re},{address:t,functionName:"symbol",args:[],abi:Re},{address:t,functionName:"balanceOf",args:[r],abi:Re},{address:t,functionName:"decimals",args:[],abi:Re}]});return{name:i,symbol:o,decimals:c,balance:a&&c?Ue(a,c):"0"}}},Gt={adapters:{}},Jt={state:Gt,initialize(e){Gt.adapters={...e}},get:e=>Gt.adapters[e]},Yt={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},Xt=te({providers:{...Yt},providerIds:{...Yt}}),Zt={state:Xt,subscribeKey:(e,t)=>ie(Xt,e,t),subscribe:e=>se(Xt,(()=>{e(Xt)})),subscribeProviders:e=>se(Xt.providers,(()=>e(Xt.providers))),setProvider(e,t){e&&t&&(Xt.providers[e]=re(t))},getProvider(e){if(e)return Xt.providers[e]},setProviderId(e,t){t&&(Xt.providerIds[e]=t)},getProviderId(e){if(e)return Xt.providerIds[e]},reset(){Xt.providers={...Yt},Xt.providerIds={...Yt}},resetChain(e){Xt.providers[e]=void 0,Xt.providerIds[e]=void 0}},Qt={async getTokenList(e){const t=await Ve.fetchSwapTokens({chainId:e});return t?.tokens?.map((e=>({...e,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0})))||[]},async fetchGasPrice(){const e=as.state.activeCaipNetwork;if(!e)return null;try{if("solana"===e.chainNamespace){const e=(await(qt?.estimateGas({chainNamespace:"solana"})))?.toString();return{standard:e,fast:e,instant:e}}return await Ve.fetchGasPrice({chainId:e.caipNetworkId})}catch{return null}},async fetchSwapAllowance({tokenAddress:e,userAddress:t,sourceTokenAmount:s,sourceTokenDecimals:n}){const r=await Ve.fetchSwapAllowance({tokenAddress:e,userAddress:t});if(r?.allowance&&s&&n){const e=qt.parseUnits(s,n)||0;return BigInt(r.allowance)>=e}return!1},async getMyTokensWithBalance(e){const t=await Kt.getMyTokensWithBalance({forceUpdate:e,caipNetwork:as.state.activeCaipNetwork,address:as.getAccountData()?.address});return as.setAccountProp("tokenBalance",t,as.state.activeChain),this.mapBalancesToSwapTokens(t)},mapBalancesToSwapTokens:e=>e?.map((e=>({...e,address:e?.address?e.address:kt(),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}}},es=te({tokenBalances:[],loading:!1}),ts={state:es,subscribe:e=>se(es,(()=>e(es))),subscribeKey:(e,t)=>ie(es,e,t),setToken(e){e&&(es.token=re(e))},setTokenAmount(e){es.sendTokenAmount=e},setReceiverAddress(e){es.receiverAddress=e},setReceiverProfileImageUrl(e){es.receiverProfileImageUrl=e},setReceiverProfileName(e){es.receiverProfileName=e},setNetworkBalanceInUsd(e){es.networkBalanceInUSD=e},setLoading(e){es.loading=e},getSdkEventProperties:e=>({message:pe.parseError(e),isSmartAccount:xt(as.state.activeChain)===be.ACCOUNT_TYPES.SMART_ACCOUNT,token:es.token?.symbol||"",amount:es.sendTokenAmount??0,network:as.state.activeCaipNetwork?.caipNetworkId||""}),async sendToken(){try{switch(ss.setLoading(!0),as.state.activeCaipNetwork?.chainNamespace){case"eip155":return void await ss.sendEvmToken();case"solana":return void await ss.sendSolanaToken();default:throw new Error("Unsupported chain")}}catch(e){if(k.isUserRejectedRequestError(e))throw new P(e);throw e}finally{ss.setLoading(!1)}},async sendEvmToken(){const e=as.state.activeChain;if(!e)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const t=xt(e);if(!ss.state.sendTokenAmount||!ss.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!ss.state.token)throw new Error("A token is required");if(ss.state.token?.address){ht.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===be.ACCOUNT_TYPES.SMART_ACCOUNT,token:ss.state.token.address,amount:ss.state.sendTokenAmount,network:as.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:e}=await ss.sendERC20Token({receiverAddress:ss.state.receiverAddress,tokenAddress:ss.state.token.address,sendTokenAmount:ss.state.sendTokenAmount,decimals:ss.state.token.quantity.decimals});e&&(es.hash=e)}else{ht.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:t===be.ACCOUNT_TYPES.SMART_ACCOUNT,token:ss.state.token.symbol||"",amount:ss.state.sendTokenAmount,network:as.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:e}=await ss.sendNativeToken({receiverAddress:ss.state.receiverAddress,sendTokenAmount:ss.state.sendTokenAmount,decimals:ss.state.token.quantity.decimals});e&&(es.hash=e)}},async fetchTokenBalance(e){es.loading=!0;const t=as.state.activeChain,s=as.state.activeCaipNetwork?.caipNetworkId,n=as.state.activeCaipNetwork?.chainNamespace,r=as.getAccountData(t)?.caipAddress??as.state.activeCaipAddress,i=r?pe.getPlainAddress(r):void 0;if(es.lastRetry&&!pe.isAllowedRetry(es.lastRetry,30*he.ONE_SEC_MS))return es.loading=!1,[];try{if(i&&s&&n){const e=await Kt.getMyTokensWithBalance();return es.tokenBalances=e,es.lastRetry=void 0,e}}catch(t){es.lastRetry=Date.now(),e?.(t),qe.showError("Token Balance Unavailable")}finally{es.loading=!1}return[]},fetchNetworkBalance(){if(0===es.tokenBalances.length)return;const e=Qt.mapBalancesToSwapTokens(es.tokenBalances);if(!e)return;const t=e.find((e=>e.address===kt()));t&&(es.networkBalanceInUSD=t?N.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){vt.pushTransactionStack({});const t=e.receiverAddress,s=as.getAccountData()?.address,n=qt.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),r=await qt.sendTransaction({chainNamespace:a.CHAIN.EVM,to:t,address:s,data:"0x",value:n??BigInt(0)});return ht.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:xt("eip155")===be.ACCOUNT_TYPES.SMART_ACCOUNT,token:ss.state.token?.symbol||"",amount:e.sendTokenAmount,network:as.state.activeCaipNetwork?.caipNetworkId||"",hash:r||""}}),qt._getClient()?.updateBalance("eip155"),ss.resetSend(),{hash:r}},async sendERC20Token(e){vt.pushTransactionStack({onSuccess(){vt.replace("Account")}});const t=qt.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals)),s=as.getAccountData()?.address;if(s&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){const n=pe.getPlainAddress(e.tokenAddress);if(!n)throw new Error("SendController:sendERC20Token - tokenAddress is required");const r=await qt.writeContract({fromAddress:s,tokenAddress:n,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:_.getERC20Abi(n),chainNamespace:a.CHAIN.EVM});return ht.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:xt("eip155")===be.ACCOUNT_TYPES.SMART_ACCOUNT,token:ss.state.token?.symbol||"",amount:e.sendTokenAmount,network:as.state.activeCaipNetwork?.caipNetworkId||"",hash:r||""}}),ss.resetSend(),{hash:r}}return{hash:void 0}},async sendSolanaToken(){if(!ss.state.sendTokenAmount||!ss.state.receiverAddress)throw new Error("An amount and receiver address are required");let e;vt.pushTransactionStack({onSuccess(){vt.replace("Account")}}),ss.state.token&&ss.state.token.address!==he.SOLANA_NATIVE_TOKEN_ADDRESS&&(e=pe.isCaipAddress(ss.state.token.address)?pe.getPlainAddress(ss.state.token.address):ss.state.token.address);const t=await qt.sendTransaction({chainNamespace:"solana",tokenMint:e,to:ss.state.receiverAddress,value:ss.state.sendTokenAmount});t&&(es.hash=t),qt._getClient()?.updateBalance("solana"),ht.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:ss.state.token?.symbol||"",amount:ss.state.sendTokenAmount,network:as.state.activeCaipNetwork?.caipNetworkId||"",hash:t||""}}),ss.resetSend()},resetSend(){es.token=void 0,es.sendTokenAmount=void 0,es.receiverAddress=void 0,es.receiverProfileImageUrl=void 0,es.receiverProfileName=void 0,es.loading=!1,es.tokenBalances=[]}},ss=Qe(ts),ns={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},rs={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},is=te({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(){ce(this)||(()=>{const e=ae.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(!ce(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(!ce(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(!ce(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=te(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}),os={state:is,subscribe:e=>se(is,(()=>{e(is)})),subscribeKey:(e,t)=>ie(is,e,t),subscribeAccountStateProp(e,t,s){const n=s||is.activeChain;return n?ie(is.chains.get(n)?.accountState||{},e,t):()=>{}},subscribeChainProp(e,t,s){let n;return se(is.chains,(()=>{const r=s||is.activeChain;if(r){const s=is.chains.get(r)?.[e];n!==s&&(n=s,t(s))}}))},initialize(e,t,s){const{chainId:n,namespace:r}=ue.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=je.state.enableEmbedded?new Set([...a]):new Set([...t?.map((e=>e.chainNamespace))??[]]);0!==e?.length&&o||(is.noAdapters=!0),is.noAdapters||(is.activeChain=o?.namespace,is.activeCaipNetwork=i,as.setChainNetworkData(o?.namespace,{caipNetwork:i}),is.activeChain&&Lt.set({activeChain:o?.namespace})),c.forEach((e=>{const n=t?.filter((t=>t.chainNamespace===e)),r=ue.getPreferredAccountTypes()||{},i={...je.state.defaultAccountTypes,...r};as.state.chains.set(e,{namespace:e,networkState:te({...rs,caipNetwork:n?.[0]}),accountState:te({...ns,preferredAccountType:i[e]}),caipNetworks:n??[],...s}),as.setRequestedCaipNetworks(n??[],e)}))},removeAdapter(e){if(is.activeChain===e){const t=Array.from(is.chains.entries()).find((([t])=>t!==e));if(t){const e=t[1]?.caipNetworks?.[0];e&&as.setActiveCaipNetwork(e)}}is.chains.delete(e)},addAdapter(e,{connectionControllerClient:t},s){if(!e.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");is.chains.set(e.namespace,{namespace:e.namespace,networkState:{...rs,caipNetwork:s[0]},accountState:{...ns},caipNetworks:s,connectionControllerClient:t}),as.setRequestedCaipNetworks(s?.filter((t=>t.chainNamespace===e.namespace))??[],e.namespace)},addNetwork(e){const t=is.chains.get(e.chainNamespace);if(t){const s=[...t.caipNetworks||[]];t.caipNetworks?.find((t=>t.id===e.id))||s.push(e),is.chains.set(e.chainNamespace,{...t,caipNetworks:s}),as.setRequestedCaipNetworks(s,e.chainNamespace),Ot.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){const s=is.chains.get(e);if(s){const n=is.activeCaipNetwork?.id===t,r=[...s.caipNetworks?.filter((e=>e.id!==t))||[]];n&&s?.caipNetworks?.[0]&&as.setActiveCaipNetwork(s.caipNetworks[0]),is.chains.set(e,{...s,caipNetworks:r}),as.setRequestedCaipNetworks(r||[],e),0===r.length&&Ot.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){const s=is.chains.get(e);s&&(s.networkState={...s.networkState||rs,...t},is.chains.set(e,s))},setChainAccountData(e,t,s=!0){if(!e)throw new Error("Chain is required to update chain account data");const n=is.chains.get(e);if(n){const s={...n.accountState||ns,...t};is.chains.set(e,{...n,accountState:s}),1!==is.chains.size&&is.activeChain!==e||t.caipAddress&&(is.activeCaipAddress=t.caipAddress)}},setChainNetworkData(e,t){if(!e)return;const s=is.chains.get(e);if(s){const n={...s.networkState||rs,...t};is.chains.set(e,{...s,networkState:n})}},setAccountProp(e,t,s,n=!0){as.setChainAccountData(s,{[e]:t},n)},setActiveNamespace(e){is.activeChain=e;const t=e?is.chains.get(e):void 0,s=t?.networkState?.caipNetwork;s?.id&&e&&(is.activeCaipAddress=t?.accountState?.caipAddress,is.activeCaipNetwork=s,as.setChainNetworkData(e,{caipNetwork:s}),ue.setActiveCaipNetworkId(s?.caipNetworkId),Lt.set({activeChain:e,selectedNetworkId:s?.caipNetworkId}))},setActiveCaipNetwork(e){if(!e)return;const t=is.activeChain===e.chainNamespace;t||as.setIsSwitchingNamespace(!0);const s=is.chains.get(e.chainNamespace);is.activeChain=e.chainNamespace,is.activeCaipNetwork=e,as.setChainNetworkData(e.chainNamespace,{caipNetwork:e});let n=s?.accountState?.address;if(n)is.activeCaipAddress=`${e.chainNamespace}:${e.id}:${n}`;else if(t&&is.activeCaipAddress){const{address:t}=T.parseCaipAddress(is.activeCaipAddress);n=t,is.activeCaipAddress=`${e.caipNetworkId}:${n}`}else is.activeCaipAddress=void 0;as.setChainAccountData(e.chainNamespace,{address:n,caipAddress:is.activeCaipAddress}),ss.resetSend(),Lt.set({activeChain:is.activeChain,selectedNetworkId:is.activeCaipNetwork?.caipNetworkId}),ue.setActiveCaipNetworkId(e.caipNetworkId);as.checkIfSupportedNetwork(e.chainNamespace)||!je.state.enableNetworkSwitch||je.state.allowUnsupportedChain||qt.state.wcBasic||as.showUnsupportedChainUI()},addCaipNetwork(e){if(!e)return;const t=is.chains.get(e.chainNamespace);t&&t?.caipNetworks?.push(e)},async switchActiveNamespace(e){if(!e)return;const t=e!==as.state.activeChain,s=as.getNetworkData(e)?.caipNetwork,n=as.getCaipNetworkByNamespace(e,s?.id);t&&n&&await as.switchActiveNetwork(n)},async switchActiveNetwork(e,{throwOnFailure:t=!1}={}){const s=as.state.activeChain;if(!s)throw new Error("ChainController:switchActiveNetwork - namespace is required");const n="AUTH"===Zt.getProviderId(is.activeChain),r=as.getAccountData(s)?.address,i=a.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(e.chainNamespace);try{if(r&&e.chainNamespace===s||n&&i){const t=Jt.get(e.chainNamespace);if(!t)throw new Error("Adapter not found");await t.switchNetwork({caipNetwork:e})}as.setActiveCaipNetwork(e)}catch(e){if(t)throw e}ht.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})},getConnectionControllerClient(e){const t=e||is.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");const s=is.chains.get(t);if(!s?.connectionControllerClient)throw new Error("ConnectionController client not set");return s.connectionControllerClient},getNetworkProp(e,t){const s=is.chains.get(t)?.networkState;if(s)return s[e]},getRequestedCaipNetworks(e){const t=is.chains.get(e),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:n=[]}=t?.networkState||{};return pe.sortRequestedNetworks(s,n).filter((e=>e?.id))},getAllRequestedCaipNetworks(){const e=[];return is.chains.forEach((t=>{if(!t.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const s=as.getRequestedCaipNetworks(t.namespace);e.push(...s)})),e},setRequestedCaipNetworks(e,t){as.setAdapterNetworkState(t,{requestedCaipNetworks:e});const s=as.getAllRequestedCaipNetworks().map((e=>e.chainNamespace)),n=Array.from(new Set(s));Ot.filterByNamespaces(n)},getAllApprovedCaipNetworkIds(){const e=[];return is.chains.forEach((t=>{if(!t.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const s=as.getApprovedCaipNetworkIds(t.namespace);e.push(...s)})),e},getActiveCaipNetwork:e=>e?is.chains.get(e)?.networkState?.caipNetwork:is.activeCaipNetwork,getActiveCaipAddress:()=>is.activeCaipAddress,getApprovedCaipNetworkIds(e){const t=is.chains.get(e);return t?.networkState?.approvedCaipNetworkIds||[]},setApprovedCaipNetworksData(e,t){as.setAdapterNetworkState(e,t)},checkIfSupportedNetwork(e,t){const s=t||is.activeCaipNetwork?.caipNetworkId,n=as.getRequestedCaipNetworks(e);return!n.length||n?.some((e=>e.caipNetworkId===s))},checkIfSupportedChainId(e){if(!is.activeChain)return!0;const t=as.getRequestedCaipNetworks(is.activeChain);return t?.some((t=>t.id===e))},checkIfSmartAccountEnabled(){const e=c.caipNetworkIdToNumber(is.activeCaipNetwork?.caipNetworkId);if(!is.activeChain||!e)return!1;const t=Ce.get(me)?.split(",")||[];return Boolean(t?.includes(e.toString()))},showUnsupportedChainUI(){ds.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const e=is.activeCaipNetwork;return Boolean(e?.chainNamespace&&he.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){as.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=as.state.chains.get(t)?.accountState?.preferredAccountType,n=je.state.defaultAccountTypes[t];is.activeCaipAddress=void 0,as.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"}),Ot.removeConnectorId(t)},setIsSwitchingNamespace(e){is.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){const e=[];let t;if(is.chains.forEach((t=>{a.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?is.chains.get(s)?.caipNetworks?.[0]:void 0,t}},getAccountData(e){const t=e||is.activeChain;if(t)return as.state.chains.get(t)?.accountState},getNetworkData(e){const t=e||is.activeChain;if(t)return as.state.chains.get(t)?.networkState},getCaipNetworkByNamespace(e,t){if(!e)return;const s=as.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=Ot.state.filterByNamespace;return(e?[is.chains.get(e)]:Array.from(is.chains.values())).flatMap((e=>e?.caipNetworks||[])).map((e=>e.caipNetworkId))},getCaipNetworks:e=>e?as.getRequestedCaipNetworks(e):as.getAllRequestedCaipNetworks(),getCaipNetworkById:(e,t)=>os.getCaipNetworks(t).find((t=>t.id.toString()===e.toString()||t.caipNetworkId.toString()===e.toString())),setLastConnectedSIWECaipNetwork(e){is.lastConnectedSIWECaipNetwork=e},getLastConnectedSIWECaipNetwork:()=>is.lastConnectedSIWECaipNetwork,async fetchTokenBalance(e){const t=as.getAccountData();if(!t)return[];const s=as.state.activeCaipNetwork?.caipNetworkId,n=as.state.activeCaipNetwork?.chainNamespace,r=as.state.activeCaipAddress,i=r?pe.getPlainAddress(r):void 0;if(as.setAccountProp("balanceLoading",!0,n),t.lastRetry&&!pe.isAllowedRetry(t.lastRetry,30*he.ONE_SEC_MS))return as.setAccountProp("balanceLoading",!1,n),[];try{if(i&&s&&n){const e=await Kt.getMyTokensWithBalance();return as.setAccountProp("tokenBalance",e,n),as.setAccountProp("lastRetry",void 0,n),as.setAccountProp("balanceLoading",!1,n),e}}catch(t){as.setAccountProp("lastRetry",Date.now(),n),e?.(t),qe.showError("Token Balance Unavailable")}finally{as.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(e){const t=e.chainNamespace,s=Boolean(as.getAccountData(t)?.caipAddress),n=as.getAllApprovedCaipNetworkIds(),r=!1!==as.getNetworkProp("supportsAllNetworks",t),i=Ot.getConnectorId(t),o=Ot.getAuthConnector(),c=i===a.CONNECTOR_ID.AUTH&&o;return!(!s||r||c)&&!n?.includes(e.caipNetworkId)}},as=Qe(os),cs={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){const s=as.state.activeCaipNetwork,n=as.state.activeChain,r=vt.state.data;if(e.id===s?.id)return;const i=Boolean(as.getAccountData(n)?.address),o=Boolean(as.getAccountData(e.chainNamespace)?.address),c=e.chainNamespace!==n,l=Ot.getConnectorId(n)===a.CONNECTOR_ID.AUTH,d=a.AUTH_CONNECTOR_SUPPORTED_CHAINS.find((t=>t===e.chainNamespace));t||l&&d?vt.push("SwitchNetwork",{...r,network:e}):i&&c&&!o?vt.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):vt.push("SwitchNetwork",{...r,network:e})}},ls=te({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),ds=Qe({state:ls,subscribe:e=>se(ls,(()=>e(ls))),subscribeKey:(e,t)=>ie(ls,e,t),async open(e){const t=e?.namespace,s=as.state.activeChain,n=t&&t!==s,r=as.getAccountData(e?.namespace)?.caipAddress,i=as.state.noAdapters;if(qt.state.wcBasic?gt.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await gt.prefetch(),Ot.setFilterByNamespace(e?.namespace),ds.setLoading(!0,t),t&&n){const e=as.getNetworkData(t)?.caipNetwork||as.getRequestedCaipNetworks(t)[0];e&&(i?(await as.switchActiveNetwork(e),vt.push("ConnectingWalletConnectBasic")):cs.onSwitchNetwork({network:e,ignoreSwitchConfirmation:!0}))}else je.state.manualWCControl||i&&!r?pe.isMobile()?vt.reset("AllWallets"):vt.reset("ConnectingWalletConnectBasic"):e?.view?vt.reset(e.view,e.data):r?vt.reset("Account"):vt.reset("Connect");ls.open=!0,Lt.set({open:!0}),ht.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:Boolean(r)}})},close(){const e=je.state.enableEmbedded,t=Boolean(as.state.activeCaipAddress);ls.open&&ht.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),ls.open=!1,vt.reset("Connect"),ds.clearLoading(),e?t?vt.replace("Account"):vt.push("Connect"):Lt.set({open:!1}),qt.resetUri()},setLoading(e,t){t&&ls.loadingNamespaceMap.set(t,e),ls.loading=e,Lt.set({loading:e})},clearLoading(){ls.loadingNamespaceMap.clear(),ls.loading=!1,Lt.set({loading:!1})},shake(){ls.shake||(ls.shake=!0,setTimeout((()=>{ls.shake=!1}),500))}}),hs={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"}]},us={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},ps=te({providers:de,selectedProvider:null,error:null,purchaseCurrency:hs,paymentCurrency:us,purchaseCurrencies:[hs],paymentCurrencies:[],quotesLoading:!1}),fs=Qe({state:ps,subscribe:e=>se(ps,(()=>e(ps))),subscribeKey:(e,t)=>ie(ps,e,t),setSelectedProvider(e){if(e&&"meld"===e.name){const t=as.state.activeChain,s=t===a.CHAIN.SOLANA?"SOL":"USDC",n=t?as.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",je.state.projectId),ps.selectedProvider={...e,url:r.toString()}}else ps.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every((e=>"string"==typeof e))){const t=e,s=de.filter((e=>t.includes(e.name)));ps.providers=s}else ps.providers=[]},setPurchaseCurrency(e){ps.purchaseCurrency=e},setPaymentCurrency(e){ps.paymentCurrency=e},setPurchaseAmount(e){fs.state.purchaseAmount=e},setPaymentAmount(e){fs.state.paymentAmount=e},async getAvailableCurrencies(){const e=await Ve.getOnrampOptions();ps.purchaseCurrencies=e.purchaseCurrencies,ps.paymentCurrencies=e.paymentCurrencies,ps.paymentCurrency=e.paymentCurrencies[0]||us,ps.purchaseCurrency=e.purchaseCurrencies[0]||hs,await gt.fetchCurrencyImages(e.paymentCurrencies.map((e=>e.id))),await gt.fetchTokenImages(e.purchaseCurrencies.map((e=>e.symbol)))},async getQuote(){ps.quotesLoading=!0;try{const e=await Ve.getOnrampQuote({purchaseCurrency:ps.purchaseCurrency,paymentCurrency:ps.paymentCurrency,amount:ps.paymentAmount?.toString()||"0",network:ps.purchaseCurrency?.symbol});return ps.quotesLoading=!1,ps.purchaseAmount=Number(e?.purchaseAmount.amount),e}catch(e){return ps.error=e.message,ps.quotesLoading=!1,null}finally{ps.quotesLoading=!1}},resetState(){ps.selectedProvider=null,ps.error=null,ps.purchaseCurrency=hs,ps.paymentCurrency=us,ps.purchaseCurrencies=[hs],ps.paymentCurrencies=[],ps.paymentAmount=void 0,ps.purchaseAmount=void 0,ps.quotesLoading=!1}});class gs extends t.IEvents{constructor(e){super()}}const ms=t.cjs.FIVE_SECONDS,ys="heartbeat_pulse";class ws extends gs{constructor(t){super(t),this.events=new e.EventEmitter,this.interval=ms,this.interval=t?.interval||ms}static async init(e){const t=new ws(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()),t.cjs.toMiliseconds(this.interval))}pulse(){this.events.emit(ys)}}var bs={},vs={};Object.defineProperty(vs,"__esModule",{value:!0}),vs.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}},vs.safeJsonStringify=function(e){return"string"==typeof e?e:JSON.stringify(e,((e,t)=>void 0===t?null:t))};var Es,Cs={exports:{}};var Ns,As={},Is={};var Ss,_s,Os={};Object.defineProperty(bs,"__esModule",{value:!0}),bs.KeyValueStorage=void 0;const Ts=s.require$$0,ks=vs,xs=Ts.__importDefault((Es||(Es=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!==n.commonjsGlobal&&n.commonjsGlobal.localStorage?Cs.exports=n.commonjsGlobal.localStorage:"undefined"!=typeof window&&window.localStorage?Cs.exports=window.localStorage:Cs.exports=new t}()),Cs.exports)),Ps=(_s||(_s=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=s.require$$0;t.__exportStar((Ns||(Ns=1,Object.defineProperty(Is,"__esModule",{value:!0}),Is.IKeyValueStorage=void 0,Is.IKeyValueStorage=class{}),Is),e),t.__exportStar(function(){if(Ss)return Os;Ss=1,Object.defineProperty(Os,"__esModule",{value:!0}),Os.parseEntry=void 0;const e=vs;return Os.parseEntry=function(t){var s;return[t[0],e.safeJsonParse(null!==(s=t[1])&&void 0!==s?s:"")]},Os}(),e)}(As)),As);class Rs{constructor(){this.localStorage=xs.default}getKeys(){return Ts.__awaiter(this,void 0,void 0,(function*(){return Object.keys(this.localStorage)}))}getEntries(){return Ts.__awaiter(this,void 0,void 0,(function*(){return Object.entries(this.localStorage).map(Ps.parseEntry)}))}getItem(e){return Ts.__awaiter(this,void 0,void 0,(function*(){const t=this.localStorage.getItem(e);if(null!==t)return ks.safeJsonParse(t)}))}setItem(e,t){return Ts.__awaiter(this,void 0,void 0,(function*(){this.localStorage.setItem(e,ks.safeJsonStringify(t))}))}removeItem(e){return Ts.__awaiter(this,void 0,void 0,(function*(){this.localStorage.removeItem(e)}))}}bs.KeyValueStorage=Rs;var Us=bs.default=Rs,Ls={exports:{}};function Ds(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var Ms=function(e,t,s){var n=s&&s.stringify||Ds;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 Bs=Ms;Ls.exports=Vs;const js=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||{},$s={mapHttpRequest:Zs,mapHttpResponse:Zs,wrapRequestSerializer:Qs,wrapResponseSerializer:Qs,wrapErrorSerializer:Qs,req:Zs,res:Zs,err:Ys,errWithCause:Ys};function Fs(e,t){return"silent"===e?1/0:t.levels.values[e]}const qs=Symbol("pino.logFuncs"),Ws=Symbol("pino.hierarchy"),Hs={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function zs(e,t){const s={logger:t,parent:e[Ws]};t[Ws]=s}function Vs(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||js;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=en),function(e,t,s){const n={};t.forEach((e=>{n[e]=s[e]?s[e]:js[e]||js[Hs[e]||"log"]||en})),e[qs]=n}(l,a,s),zs({},l),Object.defineProperty(l,"levelVal",{get:function(){return Fs(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,Ks(this,d,l,"error"),Ks(this,d,l,"fatal"),Ks(this,d,l,"warn"),Ks(this,d,l,"info"),Ks(this,d,l,"debug"),Ks(this,d,l,"trace"),o.forEach((e=>{Ks(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:Xs(e),messageKey:e.messageKey||"msg",onChild:e.onChild||en};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,Gs([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=Js([].concat(e._logEvent.bindings,i)))}d.prototype=this;const u=new d(this);return zs(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({},Vs.levels.values,t),n=Object.assign({},Vs.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=en,l.serializers=n,l._serialize=r,l._stdErrSerialize=i,l.child=function(...e){return h.call(this,d,...e)},t&&(l._logEvent=Js()),l}function Ks(e,t,s,n){if(Object.defineProperty(e,n,{value:Fs(e.level,s)>Fs(n,s)?en:s[qs][n],writable:!0,enumerable:!0,configurable:!0}),e[n]===en){if(!t.transmit)return;const r=Fs(t.transmit.level||e.level,s);if(Fs(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)===js?js:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(t.serialize&&(Gs(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?Bs(a.shift(),a):void 0}else"string"==typeof c&&(c=Bs(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=Fs(r,s),c=Fs(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||Gs(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=Js(l)}(this,{ts:i,methodLevel:n,methodValue:c,transmitLevel:r,transmitValue:s.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Fs(e._level,s)},o,l)}}}(e[qs][n])}(e,t,s,n);const r=function(e){const t=[];e.bindings&&t.push(e.bindings);let s=e[Ws];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 Gs(e,t,s,n){for(const r in e)if(n&&e[r]instanceof Error)e[r]=Vs.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 Js(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function Ys(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 Xs(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?tn:sn}function Zs(){return{}}function Qs(e){return e}function en(){}function tn(){return!1}function sn(){return Date.now()}Vs.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"}},Vs.stdSerializers=$s,Vs.stdTimeFunctions=Object.assign({},{nullTime:tn,epochTime:sn,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),Ls.exports.default=Vs,Ls.exports.pino=Vs;const nn="info",rn="custom_context",on=1024e3;var an=Object.defineProperty,cn=(e,t,s)=>((e,t,s)=>t in e?an(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ln{constructor(e){cn(this,"nodeValue"),cn(this,"sizeInBytes"),cn(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 dn{constructor(e){cn(this,"lengthInNodes"),cn(this,"sizeInBytes"),cn(this,"head"),cn(this,"tail"),cn(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new ln(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 hn(e){return"string"==typeof e?e:(e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t)))(e)||""}var un=Object.defineProperty,pn=(e,t,s)=>((e,t,s)=>t in e?un(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class fn{constructor(e,t=on){pn(this,"logs"),pn(this,"level"),pn(this,"levelValue"),pn(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=Ls.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new dn(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===Ls.exports.levels.values.error?console.error(e):t===Ls.exports.levels.values.warn?console.warn(e):t===Ls.exports.levels.values.debug?console.debug(e):t===Ls.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(hn({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 dn(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(hn({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var gn=Object.defineProperty,mn=(e,t,s)=>((e,t,s)=>t in e?gn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class yn{constructor(e,t=on){mn(this,"baseChunkLogger"),this.baseChunkLogger=new fn(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 wn=Object.defineProperty,bn=(e,t,s)=>((e,t,s)=>t in e?wn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class vn{constructor(e,t=on){bn(this,"baseChunkLogger"),this.baseChunkLogger=new fn(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 En=Object.defineProperty,Cn=Object.defineProperties,Nn=Object.getOwnPropertyDescriptors,An=Object.getOwnPropertySymbols,In=Object.prototype.hasOwnProperty,Sn=Object.prototype.propertyIsEnumerable,_n=(e,t,s)=>t in e?En(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,On=(e,t)=>{for(var s in t||(t={}))In.call(t,s)&&_n(e,s,t[s]);if(An)for(var s of An(t))Sn.call(t,s)&&_n(e,s,t[s]);return e},Tn=(e,t)=>Cn(e,Nn(t));function kn(e,t=rn){return e[t]||""}function xn(e,t,s=rn){const n=function(e,t,s=rn){const n=kn(e,s);return n.trim()?`${n}/${t}`:t}(e,t,s);return function(e,t,s=rn){return e[s]=t,e}(e.child({context:n}),n,s)}function Pn(e){var t;if(typeof e.loggerOverride<"u"&&"string"!=typeof e.loggerOverride)return{logger:e.loggerOverride,chunkLoggerController:null};const s=Tn(On({},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 yn(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:Ls.exports(Tn(On({},e.opts),{level:"trace",browser:Tn(On({},null==(s=e.opts)?void 0:s.browser),{write:e=>n.write(e)})})),chunkLoggerController:n}}(Tn(On({},e),{opts:s})):function(e){var t,s;const n=new vn(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:Ls.exports(Tn(On({},e.opts),{level:"trace",browser:Tn(On({},null==(s=e.opts)?void 0:s.browser),{write:e=>n.write(e)})}),n),chunkLoggerController:n}}(Tn(On({},e),{opts:s}))}var Rn=Object.defineProperty,Un=(e,t,s)=>((e,t,s)=>t in e?Rn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ln extends t.IEvents{constructor(e){super(),this.opts=e,Un(this,"protocol","wc"),Un(this,"version",2)}}var Dn=Object.defineProperty,Mn=(e,t,s)=>((e,t,s)=>t in e?Dn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Bn extends t.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,Mn(this,"records",new Map)}}class jn{constructor(e,t){this.logger=e,this.core=t}}class $n extends t.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Fn extends t.IEvents{constructor(e){super()}}class qn{constructor(e,t,s,n){this.core=e,this.logger=t,this.name=s}}class Wn extends t.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Hn extends t.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}}class zn{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}}class Vn{constructor(e,t){this.projectId=e,this.logger=t}}class Kn{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}}var Gn=Object.defineProperty,Jn=(e,t,s)=>((e,t,s)=>t in e?Gn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Yn{constructor(e){this.opts=e,Jn(this,"protocol","wc"),Jn(this,"version",2)}}class Xn{constructor(e){this.client=e}}function Zn(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 Qn(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 er="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,tr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function sr(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)),Zn(e),e}class nr{clone(){return this._cloneInto()}}function rr(e=32){if(er&&"function"==typeof er.getRandomValues)return er.getRandomValues(new Uint8Array(e));if(er&&"function"==typeof er.randomBytes)return er.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}class ir extends nr{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=tr(this.buffer)}update(e){Qn(this);const{view:t,buffer:s,blockLen:n}=this,r=(e=sr(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=tr(e);for(;n<=r-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qn(this),function(e,t){Zn(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=tr(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 or=BigInt(2**32-1),ar=BigInt(32);function cr(e,t=!1){return t?{h:Number(e&or),l:Number(e>>ar&or)}:{h:0|Number(e>>ar&or),l:0|Number(e&or)}}const lr={fromBig:cr,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}=cr(e[r],t);[s[r],n[r]]=[i,o]}return[s,n]},toBig:(e,t)=>BigInt(e>>>0)<<ar|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)},[dr,hr]=lr.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)))),ur=new Uint32Array(80),pr=new Uint32Array(80);class fr extends ir{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)ur[s]=e.getUint32(t),pr[s]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ur[e-15],s=0|pr[e-15],n=lr.rotrSH(t,s,1)^lr.rotrSH(t,s,8)^lr.shrSH(t,s,7),r=lr.rotrSL(t,s,1)^lr.rotrSL(t,s,8)^lr.shrSL(t,s,7),i=0|ur[e-2],o=0|pr[e-2],a=lr.rotrSH(i,o,19)^lr.rotrBH(i,o,61)^lr.shrSH(i,o,6),c=lr.rotrSL(i,o,19)^lr.rotrBL(i,o,61)^lr.shrSL(i,o,6),l=lr.add4L(r,c,pr[e-7],pr[e-16]),d=lr.add4H(l,n,a,ur[e-7],ur[e-16]);ur[e]=0|d,pr[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=lr.rotrSH(d,h,14)^lr.rotrSH(d,h,18)^lr.rotrBH(d,h,41),w=lr.rotrSL(d,h,14)^lr.rotrSL(d,h,18)^lr.rotrBL(d,h,41),b=d&u^~d&f,v=h&p^~h&g,E=lr.add5L(y,w,v,hr[e],pr[e]),C=lr.add5H(E,m,t,b,dr[e],ur[e]),N=0|E,A=lr.rotrSH(s,n,28)^lr.rotrBH(s,n,34)^lr.rotrBH(s,n,39),I=lr.rotrSL(s,n,28)^lr.rotrBL(s,n,34)^lr.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}=lr.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=lr.add3L(N,I,_);s=lr.add3H(O,C,A,S),n=0|O}({h:s,l:n}=lr.add(0|this.Ah,0|this.Al,0|s,0|n)),({h:r,l:i}=lr.add(0|this.Bh,0|this.Bl,0|r,0|i)),({h:o,l:a}=lr.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=lr.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:d,l:h}=lr.add(0|this.Eh,0|this.El,0|d,0|h)),({h:u,l:p}=lr.add(0|this.Fh,0|this.Fl,0|u,0|p)),({h:f,l:g}=lr.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=lr.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(){ur.fill(0),pr.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 gr=function(e){const t=t=>e().update(sr(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}((()=>new fr)),mr=BigInt(0),yr=BigInt(1),wr=BigInt(2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function br(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function vr(e){if(!br(e))throw new Error("Uint8Array expected")}function Er(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const Cr=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Nr(e){vr(e);let t="";for(let s=0;s<e.length;s++)t+=Cr[e[s]];return t}function Ar(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?mr:BigInt("0x"+e)}const Ir={_0:48,_9:57,A:65,F:70,a:97,f:102};function Sr(e){return e>=Ir._0&&e<=Ir._9?e-Ir._0:e>=Ir.A&&e<=Ir.F?e-(Ir.A-10):e>=Ir.a&&e<=Ir.f?e-(Ir.a-10):void 0}function _r(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=Sr(e.charCodeAt(r)),i=Sr(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 Or(e){return vr(e),Ar(Nr(Uint8Array.from(e).reverse()))}function Tr(e,t){return _r(e.toString(16).padStart(2*t,"0"))}function kr(e,t){return Tr(e,t).reverse()}function xr(e,t,s){let n;if("string"==typeof t)try{n=_r(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!br(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 Pr(...e){let t=0;for(let s=0;s<e.length;s++){const n=e[s];vr(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 Rr=e=>"bigint"==typeof e&&mr<=e;function Ur(e,t,s,n){if(!function(e,t,s){return Rr(e)&&Rr(t)&&Rr(s)&&t<=e&&e<s}(t,s,n))throw new Error("expected valid "+e+": "+s+" <= n < "+n+", got "+t)}const Lr=e=>(wr<<BigInt(e-1))-yr,Dr={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||br(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 Mr(e,t,s={}){const n=(t,s,n)=>{const r=Dr[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 Br(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 jr=BigInt(0),$r=BigInt(1),Fr=BigInt(2),qr=BigInt(3),Wr=BigInt(4),Hr=BigInt(5),zr=BigInt(8);function Vr(e,t){const s=e%t;return s>=jr?s:t+s}function Kr(e,t,s){if(t<jr)throw new Error("invalid exponent, negatives unsupported");if(s<=jr)throw new Error("invalid modulus");if(s===$r)return jr;let n=$r;for(;t>jr;)t&$r&&(n=n*e%s),e=e*e%s,t>>=$r;return n}function Gr(e,t,s){let n=e;for(;t-- >jr;)n*=n,n%=s;return n}function Jr(e,t){if(e===jr)throw new Error("invert: expected non-zero number");if(t<=jr)throw new Error("invert: expected positive modulus, got "+t);let s=Vr(e,t),n=t,r=jr,i=$r;for(;s!==jr;){const e=n%s,t=r-i*(n/s);n=s,s=e,r=i,i=t}if(n!==$r)throw new Error("invert: does not exist");return Vr(r,t)}function Yr(e){if(e%Wr===qr){const t=(e+$r)/Wr;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%zr===Hr){const t=(e-Hr)/zr;return function(e,s){const n=e.mul(s,Fr),r=e.pow(n,t),i=e.mul(s,r),o=e.mul(e.mul(i,Fr),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-$r)/Fr;let s,n,r;for(s=e-$r,n=0;s%Fr===jr;s/=Fr,n++);for(r=Fr;r<e&&Kr(r,t,e)!==e-$r;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===n){const t=(e+$r)/Wr;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+$r)/Fr;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,$r<<BigInt(a-t-1));c=e.sqr(s),l=e.mul(l,s),d=e.mul(d,c),a=t}return l}}(e)}const Xr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Zr(e,t){const s=void 0!==t?t:e.toString(2).length;return{nBitLength:s,nByteLength:Math.ceil(s/8)}}function Qr(e,t,s=!1,n={}){if(e<=jr)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:i}=Zr(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:Lr(r),ZERO:jr,ONE:$r,create:t=>Vr(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return jr<=t&&t<e},is0:e=>e===jr,isOdd:e=>(e&$r)===$r,neg:t=>Vr(-t,e),eql:(e,t)=>e===t,sqr:t=>Vr(t*t,e),add:(t,s)=>Vr(t+s,e),sub:(t,s)=>Vr(t-s,e),mul:(t,s)=>Vr(t*s,e),pow:(e,t)=>function(e,t,s){if(s<jr)throw new Error("invalid exponent, negatives unsupported");if(s===jr)return e.ONE;if(s===$r)return t;let n=e.ONE,r=t;for(;s>jr;)s&$r&&(n=e.mul(n,r)),r=e.sqr(r),s>>=$r;return n}(a,e,t),div:(t,s)=>Vr(t*Jr(s,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Jr(t,e),sqrt:n.sqrt||(t=>(o||(o=Yr(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?kr(e,i):Tr(e,i),fromBytes:e=>{if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);return s?Or(e):function(e){return Ar(Nr(e))}(e)}});return Object.freeze(a)}const ei=BigInt(0),ti=BigInt(1);function si(e,t){const s=t.negate();return e?s:t}function ni(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ri(e,t){ni(e,t);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const ii=new WeakMap,oi=new WeakMap;function ai(e){return oi.get(e)||1}function ci(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>mr;e>>=yr,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 li(e){return function(e){const t=Xr.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});Mr(e,t)}(e.Fp),Mr(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Zr(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const di=BigInt(0),hi=BigInt(1),ui=BigInt(2),pi=BigInt(8),fi={zip215:!0};function gi(e){const t=function(e){const t=li(e);return Mr(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=ui<<BigInt(8*a)-hi,d=s.create,h=Qr(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:di}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,s)=>{if(Er("phflag",s),t.length||s)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){Ur("coordinate "+e,t,di,l)}function m(e){if(!(e instanceof b))throw new Error("ExtendedPoint expected")}const y=Br(((e,t)=>{const{ex:n,ey:r,ez:i}=e,o=e.is0();null==t&&(t=o?pi:s.inv(i));const a=d(n*t),c=d(r*t),l=d(i*t);if(o)return{x:di,y:hi};if(l!==hi)throw new Error("invZ was invalid");return{x:a,y:c}})),w=Br((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,hi,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 ci(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(ui*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===di)return this.double();const n=d(o*ui*u),p=d(a*ui*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;Ur("scalar",t,hi,n);const{p:s,f:r}=this.wNAF(t);return b.normalizeZ([s,r])[0]}multiplyUnsafe(e,t=b.ZERO){const s=e;return Ur("scalar",s,di,n),s===di?E:this.is0()||s===hi?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===hi?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:r,a:i}=t,o=s.BYTES;e=xr("pointHex",e,o),Er("zip215",n);const a=e.slice(),c=e[o-1];a[o-1]=-129&c;const h=Or(a),p=n?l:s.ORDER;Ur("pointHex.y",h,di,p);const f=d(h*h),g=d(f-hi),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&hi)===hi,E=0!=(128&c);if(!n&&w===di&&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=kr(t,s.BYTES);return n[n.length-1]|=e&hi?128:0,n}toHex(){return Nr(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,hi,d(t.Gx*t.Gy)),b.ZERO=new b(di,hi,hi,di);const{BASE:v,ZERO:E}=b,C=function(e,t){return{constTimeNegate:si,hasPrecomputes:e=>1!==ai(e),unsafeLadder(t,s,n=e.ZERO){let r=t;for(;s>ei;)s&ti&&(n=n.add(r)),r=r.double(),s>>=ti;return n},precomputeWindow(e,s){const{windows:n,windowSize:r}=ri(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}=ri(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+=ti);const i=t,u=t+Math.abs(s)-1,p=e%2!=0,f=s<0;0===s?c=c.add(si(p,n[i])):a=a.add(si(f,n[u]))}return{p:a,f:c}},wNAFUnsafe(s,n,r,i=e.ZERO){const{windows:o,windowSize:a}=ri(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===ei)break;let s=Number(r&c);if(r>>=d,s>a&&(s-=l,r+=ti),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=ii.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&ii.set(t,s(n))),n},wNAFCached(e,t,s){const n=ai(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)},wNAFCachedUnsafe(e,t,s,n){const r=ai(e);return 1===r?this.unsafeLadder(e,t,n):this.wNAFUnsafe(r,this.getPrecomputes(r,e,s),t,n)},setWindowSize(e,s){ni(s,t),oi.set(e,s),ii.delete(e)}}}(b,8*a);function N(e){return Vr(e,n)}function A(e){return N(Or(e))}function I(e){const t=s.BYTES;e=xr("private key",e,t);const n=xr("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=Pr(...t);return A(i(f(s,xr("context",e),!!r)))}const _=fi;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t,i={}){e=xr("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 Ur("signature.s",h,di,n),xr("result",Pr(d,kr(h,s.BYTES)),2*s.BYTES)},verify:function(e,t,n,i=_){const{context:o,zip215:a}=i,c=s.BYTES;e=xr("signature",e,2*c),t=xr("message",t),n=xr("publicKey",n,c),void 0!==a&&Er("zip215",a),r&&(t=r(t));const l=Or(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 mi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),yi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const wi=BigInt(1),bi=BigInt(2);BigInt(3);const vi=BigInt(5),Ei=BigInt(8);function Ci(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Ni(e,t){const s=mi,n=Vr(t*t*t,s),r=function(e){const t=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=mi,o=e*e%i*e%i,a=Gr(o,bi,i)*o%i,c=Gr(a,wi,i)*e%i,l=Gr(c,vi,i)*c%i,d=Gr(l,t,i)*l%i,h=Gr(d,s,i)*d%i,u=Gr(h,n,i)*h%i,p=Gr(u,r,i)*u%i,f=Gr(p,r,i)*u%i,g=Gr(f,t,i)*l%i;return{pow_p_5_8:Gr(g,bi,i)*e%i,b2:o}}(e*Vr(n*n*t,s)).pow_p_5_8;let i=Vr(e*n*r,s);const o=Vr(t*i*i,s),a=i,c=Vr(i*yi,s),l=o===e,d=o===Vr(-e,s),h=o===Vr(-e*yi,s);return l&&(i=a),(d||h)&&(i=c),((e,t)=>(Vr(e,t)&$r)===$r)(i,s)&&(i=Vr(-i,s)),{isValid:l||d,value:i}}const Ai=Qr(mi,void 0,!0),Ii=gi({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ai,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ei,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gr,randomBytes:rr,adjustScalarBytes:Ci,uvRatio:Ni}),Si=".",_i="base64url",Oi="utf8",Ti="utf8",ki=":",xi="did",Pi="key",Ri="base58btc",Ui="z",Li="K36";function Di(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function Mi(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?Di(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Bi(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const s=Mi(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return Di(s)}var ji=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`)}}},$i=ji;const Fi=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 qi{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 Wi{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 zi(this,e)}}class Hi{constructor(e){this.decoders=e}or(e){return zi(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 zi=(e,t)=>new Hi({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Vi{constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new qi(e,t,s),this.decoder=new Wi(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ki=({name:e,prefix:t,encode:s,decode:n})=>new Vi(e,t,s,n),Gi=({prefix:e,name:t,alphabet:s})=>{const{encode:n,decode:r}=$i(s,t);return Ki({prefix:e,name:t,encode:n,decode:e=>Fi(r(e))})},Ji=({name:e,prefix:t,bitsPerChar:s,alphabet:n})=>Ki({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)}),Yi=Ki({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var Xi=Object.freeze({__proto__:null,identity:Yi});const Zi=Ji({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qi=Object.freeze({__proto__:null,base2:Zi});const eo=Ji({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var to=Object.freeze({__proto__:null,base8:eo});const so=Gi({prefix:"9",name:"base10",alphabet:"0123456789"});var no=Object.freeze({__proto__:null,base10:so});const ro=Ji({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),io=Ji({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var oo=Object.freeze({__proto__:null,base16:ro,base16upper:io});const ao=Ji({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),co=Ji({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),lo=Ji({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ho=Ji({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uo=Ji({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),po=Ji({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fo=Ji({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),go=Ji({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mo=Ji({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var yo=Object.freeze({__proto__:null,base32:ao,base32upper:co,base32pad:lo,base32padupper:ho,base32hex:uo,base32hexupper:po,base32hexpad:fo,base32hexpadupper:go,base32z:mo});const wo=Gi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bo=Gi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vo=Object.freeze({__proto__:null,base36:wo,base36upper:bo});const Eo=Gi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Co=Gi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var No=Object.freeze({__proto__:null,base58btc:Eo,base58flickr:Co});const Ao=Ji({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Io=Ji({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),So=Ji({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_o=Ji({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Oo=Object.freeze({__proto__:null,base64:Ao,base64pad:Io,base64url:So,base64urlpad:_o});const To=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ko=To.reduce(((e,t,s)=>(e[s]=t,e)),[]),xo=To.reduce(((e,t,s)=>(e[t.codePointAt(0)]=s,e)),[]);const Po=Ki({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=ko[t]),"")},decode:function(e){const t=[];for(const s of e){const e=xo[s.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${s}`);t.push(e)}return new Uint8Array(t)}});var Ro=Object.freeze({__proto__:null,base256emoji:Po}),Uo=function e(t,s,n){s=s||[];for(var r=n=n||0;t>=Mo;)s[n++]=255&t|Lo,t/=128;for(;t&Do;)s[n++]=255&t|Lo,t>>>=7;return s[n]=0|t,e.bytes=n-r+1,s},Lo=128,Do=-128,Mo=Math.pow(2,31);var Bo=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&$o)<<i:(n&$o)*Math.pow(2,i),i+=7}while(n>=jo);return e.bytes=o-s,r},jo=128,$o=127;var Fo=Math.pow(2,7),qo=Math.pow(2,14),Wo=Math.pow(2,21),Ho=Math.pow(2,28),zo=Math.pow(2,35),Vo=Math.pow(2,42),Ko=Math.pow(2,49),Go=Math.pow(2,56),Jo=Math.pow(2,63),Yo={encode:Uo,decode:Bo,encodingLength:function(e){return e<Fo?1:e<qo?2:e<Wo?3:e<Ho?4:e<zo?5:e<Vo?6:e<Ko?7:e<Go?8:e<Jo?9:10}},Xo=Yo;const Zo=(e,t,s=0)=>(Xo.encode(e,t,s),t),Qo=e=>Xo.encodingLength(e),ea=(e,t)=>{const s=t.byteLength,n=Qo(e),r=n+Qo(s),i=new Uint8Array(r+s);return Zo(e,i,0),Zo(s,i,n),i.set(t,r),new ta(e,s,t,i)};class ta{constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}}const sa=({name:e,code:t,encode:s})=>new na(e,t,s);class na{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?ea(this.code,t):t.then((e=>ea(this.code,e)))}throw Error("Unknown type, must be binary type")}}const ra=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),ia=sa({name:"sha2-256",code:18,encode:ra("SHA-256")}),oa=sa({name:"sha2-512",code:19,encode:ra("SHA-512")});Object.freeze({__proto__:null,sha256:ia,sha512:oa});const aa=Fi,ca={code:0,name:"identity",encode:aa,digest:e=>ea(0,aa(e))};Object.freeze({__proto__:null,identity:ca});new TextEncoder,new TextDecoder;const la={...Xi,...Qi,...to,...no,...oo,...yo,...vo,...No,...Oo,...Ro};function da(e,t,s,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:n}}}const ha=da("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),ua=da("ascii","a",(e=>{let t="a";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t}),(e=>{const t=Mi((e=e.substring(1)).length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t})),pa={utf8:ha,"utf-8":ha,hex:la.base16,latin1:ua,ascii:ua,binary:ua,...la};function fa(e,t="utf8"){const s=pa[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 ga(e,t="utf8"){const s=pa[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}`):Di(globalThis.Buffer.from(e,"utf-8"))}function ma(e){return t.safeJsonParse(fa(ga(e,_i),Oi))}function ya(e){return fa(ga(t.safeJsonStringify(e),Oi),_i)}function wa(e){const t=ga(Li,Ri),s=Ui+fa(Bi([t,e]),Ri);return[xi,Pi,s].join(ki)}function ba(e){return fa(e,_i)}function va(e){const t=e.split(Si),s=ma(t[0]),n=ma(t[1]),r=function(e){return ga(e,_i)}(t[2]);return{header:s,payload:n,signature:r,data:ga(t.slice(0,2).join(Si),Ti)}}function Ea(e=rr(32)){const t=Ii.getPublicKey(e);return{secretKey:Bi([e,t]),publicKey:t}}async function Ca(e,s,n,r,i=t.cjs.fromMiliseconds(Date.now())){const o={alg:"EdDSA",typ:"JWT"},a={iss:wa(r.publicKey),sub:e,aud:s,iat:i,exp:i+n},c=function(e){return ga([ya(e.header),ya(e.payload)].join(Si),Ti)}({header:o,payload:a});return function(e){return[ya(e.header),ya(e.payload),ba(e.signature)].join(Si)}({header:o,payload:a,signature:Ii.sign(c,r.secretKey.slice(0,32))})}
2
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Na(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Aa(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every((e=>"string"==typeof e)):t.every((e=>Number.isSafeInteger(e)))))}function Ia(e){if("function"!=typeof e)throw new Error("function expected");return!0}function Sa(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function _a(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function Oa(e){if(!Array.isArray(e))throw new Error("array expected")}function Ta(e,t){if(!Aa(!0,t))throw new Error(`${e}: array of strings expected`)}function ka(e,t){if(!Aa(!1,t))throw new Error(`${e}: array of numbers expected`)}function xa(...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 Pa(e){const t="string"==typeof e?e.split(""):e,s=t.length;Ta("alphabet",t);const n=new Map(t.map(((e,t)=>[e,t])));return{encode:n=>(Oa(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=>(Oa(t),t.map((t=>{Sa("alphabet.decode",t);const s=n.get(t);if(void 0===s)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return s})))}}function Ra(e=""){return Sa("join",e),{encode:t=>(Ta("join.decode",t),t.join(e)),decode:t=>(Sa("join.decode",t),t.split(e))}}function Ua(e,t="="){return _a(e),Sa("padding",t),{encode(s){for(Ta("padding.encode",s);s.length*e%8;)s.push(t);return s},decode(s){Ta("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 La(e){return Ia(e),{encode:e=>e,decode:t=>e(t)}}function Da(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(Oa(e),!e.length)return[];let n=0;const r=[],i=Array.from(e,(e=>{if(_a(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 Ma=(e,t)=>0===t?e:Ma(t,e%t),Ba=(e,t)=>e+(t-Ma(e,t)),ja=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function $a(e,t,s,n){if(Oa(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(Ba(t,s)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${s} carryBits=${Ba(t,s)}`);let r=0,i=0;const o=ja[t],a=ja[s]-1,c=[];for(const n of e){if(_a(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=ja[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 Fa(e,t=!1){if(_a(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Ba(8,e)>32||Ba(e,8)>32)throw new Error("radix2: carry overflow");return{encode:s=>{if(!Na(s))throw new Error("radix2.encode input should be Uint8Array");return $a(Array.from(s),8,e,!t)},decode:s=>(ka("radix2.decode",s),Uint8Array.from($a(s,e,8,t)))}}function qa(e){return Ia(e),function(...t){try{return e.apply(null,t)}catch(e){}}}xa(Fa(4),Pa("0123456789ABCDEF"),Ra(""));const Wa=xa(Fa(5),Pa("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ua(5),Ra(""));xa(Fa(5),Pa("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ra("")),xa(Fa(5),Pa("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Ua(5),Ra("")),xa(Fa(5),Pa("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Ra("")),xa(Fa(5),Pa("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Ra(""),La((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))));const Ha=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)();Ha||xa(Fa(6),Pa("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ua(6),Ra("")),xa(Fa(6),Pa("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ra("")),Ha||xa(Fa(6),Pa("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Ua(6),Ra("")),xa(Fa(6),Pa("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Ra(""));const za=e=>{return xa((_a(t=58),{encode:e=>{if(!Na(e))throw new Error("radix.encode input should be Uint8Array");return Da(Array.from(e),256,t)},decode:e=>(ka("radix.decode",e),Uint8Array.from(Da(e,t,256)))}),Pa(e),Ra(""));var t},Va=za("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");za("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),za("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const Ka=xa(Pa("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Ra("")),Ga=[996825010,642813549,513874426,1027748829,705979059];function Ja(e){const t=e>>25;let s=(33554431&e)<<5;for(let e=0;e<Ga.length;e++)1==(t>>e&1)&&(s^=Ga[e]);return s}function Ya(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=Ja(r)^s>>5}r=Ja(r);for(let t=0;t<n;t++)r=Ja(r)^31&e.charCodeAt(t);for(let e of t)r=Ja(r)^e;for(let e=0;e<6;e++)r=Ja(r);return r^=s,Ka.encode($a([r%ja[30]],30,5,!1))}function Xa(e){const t="bech32"===e?1:734539939,s=Fa(5),n=s.decode,r=s.encode,i=qa(n);function o(e,s,n=90){Sa("bech32.encode prefix",e),Na(s)&&(s=Array.from(s)),ka("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=Ya(o,s,t);return`${o}1${Ka.encode(s)}${a}`}function a(e,s=90){Sa("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=Ka.decode(a).slice(0,-6),l=Ya(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:qa(a),fromWords:n,fromWordsUnsafe:i,toWords:r}}Xa("bech32"),Xa("bech32m");(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||xa(Fa(4),Pa("0123456789abcdef"),Ra(""),La((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 Za={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"}},Qa=":";function ec(e){const[t,s]=e.split(Qa);return{namespace:t,reference:s}}function tc(e,t){return e.includes(":")?[e]:t.chains||[]}const sc={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}},nc={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 rc(e,t){const{message:s,code:n}=nc[e];return{message:t?`${s} ${t}`:s,code:n}}function ic(e,t){const{message:s,code:n}=sc[e];return{message:t?`${s} ${t}`:s,code:n}}var oc=Object.defineProperty,ac=Object.defineProperties,cc=Object.getOwnPropertyDescriptors,lc=Object.getOwnPropertySymbols,dc=Object.prototype.hasOwnProperty,hc=Object.prototype.propertyIsEnumerable,uc=(e,t,s)=>t in e?oc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,pc=(e,t)=>{for(var s in t||(t={}))dc.call(t,s)&&uc(e,s,t[s]);if(lc)for(var s of lc(t))hc.call(t,s)&&uc(e,s,t[s]);return e},fc=(e,t,s)=>uc(e,"symbol"!=typeof t?t+"":t,s);const gc="ReactNative",mc={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},yc="js";function wc(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function bc(){return!t.getDocument_1()&&!!t.getNavigator_1()&&navigator.product===gc}function vc(){return!wc()&&!!t.getNavigator_1()&&!!t.getDocument_1()}function Ec(){return bc()?mc.reactNative:wc()?mc.node:vc()?mc.browser:mc.unknown}function Cc(){var e;try{return bc()&&typeof global<"u"&&typeof(null==global?void 0:global.Application)<"u"?null==(e=global.Application)?void 0:e.applicationId:void 0}catch{return}}function Nc(e){var t,s;const n=Ac();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)=>ac(e,cc(t)))(pc(pc({},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 Ac(){return t.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function Ic(e,s,n){const r=function(){if(Ec()===mc.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=t.detect();if(null===e)return"unknown";const s=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[s,e.name,e.version].join("-"):[s,e.version].join("-")}(),i=function(){var e;const s=Ec();return s===mc.browser?[s,(null==(e=t.getLocation_1())?void 0:e.host)||"unknown"].join(":"):s}();return[[e,s].join("-"),[yc,n].join("-"),r,i].join("/")}function Sc({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:Ic(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 _c(e,t){return e.filter((e=>t.includes(e))).length===e.length}function Oc(e){return Object.fromEntries(e.entries())}function Tc(e){return new Map(Object.entries(e))}function kc(e=t.cjs.FIVE_MINUTES,s){const n=t.cjs.toMiliseconds(e||t.cjs.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,t)=>{if(a)return e(a);o=setTimeout((()=>{const e=rc("EXPIRED"),n=new Error(s||e.message);n.code=e.code,t(n)}),n),r=e,i=t}))}}function xc(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 Pc(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 Rc(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 Uc(e,s){return t.cjs.fromMiliseconds((s||Date.now())+t.cjs.toMiliseconds(e))}function Lc(e){return Date.now()>=t.cjs.toMiliseconds(e)}function Dc(e,t){return`${e}${t?`:${t}`:""}`}function Mc(e=[],t=[]){return[...new Set([...e,...t])]}async function Bc({id:e,topic:s,wcDeepLink:n}){var r;try{if(!n)return;const i="string"==typeof n?JSON.parse(n):n,o=i?.href;if("string"!=typeof o)return;const a=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}(o,e,s),c=Ec();if(c===mc.browser){if(null==(r=t.getDocument_1())||!r.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")}(a)}else c===mc.reactNative&&typeof(null==global?void 0:global.Linking)<"u"&&await global.Linking.openURL(a)}catch(e){console.error(e)}}function jc(e,t){if(!e.includes(t))return null;const s=e.split(/([&,?,=])/),n=s.indexOf(t);return s[n+2]}function $c(){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 Fc(){return typeof process<"u"&&"true"===process.env.IS_VITEST}function qc(e){return Buffer.from(e,"base64").toString("utf-8")}class Wc{constructor({limit:e}){fc(this,"limit"),fc(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 Hc=BigInt(2**32-1),zc=BigInt(32);function Vc(e,t=!1){return t?{h:Number(e&Hc),l:Number(e>>zc&Hc)}:{h:0|Number(e>>zc&Hc),l:0|Number(e&Hc)}}function Kc(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}=Vc(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}const Gc=(e,t,s)=>e>>>s,Jc=(e,t,s)=>e<<32-s|t>>>s,Yc=(e,t,s)=>e>>>s|t<<32-s,Xc=(e,t,s)=>e<<32-s|t>>>s,Zc=(e,t,s)=>e<<64-s|t>>>s-32,Qc=(e,t,s)=>e>>>s-32|t<<64-s,el=(e,t)=>t,tl=(e,t)=>e;function sl(e,t,s,n){const r=(t>>>0)+(n>>>0);return{h:e+s+(r/2**32|0)|0,l:0|r}}const nl=(e,t,s)=>(e>>>0)+(t>>>0)+(s>>>0),rl=(e,t,s,n)=>t+s+n+(e/2**32|0)|0,il=(e,t,s,n)=>(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),ol=(e,t,s,n,r)=>t+s+n+r+(e/2**32|0)|0,al=(e,t,s,n,r)=>(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0)+(r>>>0),cl=(e,t,s,n,r,i)=>t+s+n+r+i+(e/2**32|0)|0,ll="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function dl(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function hl(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ul(e,...t){if(!dl(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 pl(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");hl(e.outputLen),hl(e.blockLen)}function fl(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 gl(e,t){ul(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function ml(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function yl(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function wl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function bl(e,t){return e<<32-t|e>>>t}const vl=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function El(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Cl=vl?e=>e:e=>El(e);const Nl=vl?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=El(e[t]);return e},Al="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,Il=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Sl(e){if(ul(e),Al)return e.toHex();let t="";for(let s=0;s<e.length;s++)t+=Il[e[s]];return t}const _l={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ol(e){return e>=_l._0&&e<=_l._9?e-_l._0:e>=_l.A&&e<=_l.F?e-(_l.A-10):e>=_l.a&&e<=_l.f?e-(_l.a-10):void 0}function Tl(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Al)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=Ol(e.charCodeAt(r)),i=Ol(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 kl(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function xl(e){return"string"==typeof e&&(e=kl(e)),ul(e),e}function Pl(...e){let t=0;for(let s=0;s<e.length;s++){const n=e[s];ul(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 Rl{}function Ul(e){const t=t=>e().update(xl(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}function Ll(e=32){if(ll&&"function"==typeof ll.getRandomValues)return ll.getRandomValues(new Uint8Array(e));if(ll&&"function"==typeof ll.randomBytes)return Uint8Array.from(ll.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const Dl=BigInt(0),Ml=BigInt(1),Bl=BigInt(2),jl=BigInt(7),$l=BigInt(256),Fl=BigInt(113),ql=[],Wl=[],Hl=[];for(let e=0,t=Ml,s=1,n=0;e<24;e++){[s,n]=[n,(2*s+3*n)%5],ql.push(2*(5*n+s)),Wl.push((e+1)*(e+2)/2%64);let r=Dl;for(let e=0;e<7;e++)t=(t<<Ml^(t>>jl)*Fl)%$l,t&Bl&&(r^=Ml<<(Ml<<BigInt(e))-Ml);Hl.push(r)}const zl=Kc(Hl,!0),Vl=zl[0],Kl=zl[1],Gl=(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),Jl=(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 Yl extends Rl{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,hl(s),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ml(this.state)}clone(){return this._cloneInto()}keccak(){Nl(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=Gl(i,o,1)^s[n],c=Jl(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=Wl[s],i=Gl(t,r,n),o=Jl(t,r,n),a=ql[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]^=Vl[n],e[1]^=Kl[n]}yl(s)}(this.state32,this.rounds),Nl(this.state32),this.posOut=0,this.pos=0}update(e){fl(this),ul(e=xl(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){fl(this,!1),ul(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 hl(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(gl(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,yl(this.state)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:n,rounds:r,enableXOF:i}=this;return e||(e=new Yl(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 Xl=((e,t,s)=>Ul((()=>new Yl(t,e,s))))(1,136,32);function Zl(e,t,s){return e&t^~e&s}function Ql(e,t,s){return e&t^e&s^t&s}class ed extends Rl{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=wl(this.buffer)}update(e){fl(this),ul(e=xl(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=wl(e);for(;n<=r-i;i+=n)this.process(t,i)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){fl(this),gl(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:n,isLE:r}=this;let{pos:i}=this;t[i++]=128,yl(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=wl(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 td=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),sd=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),nd=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),rd=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]),id=new Uint32Array(64);class od extends ed{constructor(e=32){super(64,e,8,!1),this.A=0|td[0],this.B=0|td[1],this.C=0|td[2],this.D=0|td[3],this.E=0|td[4],this.F=0|td[5],this.G=0|td[6],this.H=0|td[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)id[s]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=id[e-15],s=id[e-2],n=bl(t,7)^bl(t,18)^t>>>3,r=bl(s,17)^bl(s,19)^s>>>10;id[e]=r+id[e-7]+n+id[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+(bl(o,6)^bl(o,11)^bl(o,25))+Zl(o,a,c)+rd[e]+id[e]|0,d=(bl(s,2)^bl(s,13)^bl(s,22))+Ql(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(){yl(id)}destroy(){this.set(0,0,0,0,0,0,0,0),yl(this.buffer)}}const ad=Kc(["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)))),cd=ad[0],ld=ad[1],dd=new Uint32Array(80),hd=new Uint32Array(80);class ud extends ed{constructor(e=64){super(128,e,16,!1),this.Ah=0|nd[0],this.Al=0|nd[1],this.Bh=0|nd[2],this.Bl=0|nd[3],this.Ch=0|nd[4],this.Cl=0|nd[5],this.Dh=0|nd[6],this.Dl=0|nd[7],this.Eh=0|nd[8],this.El=0|nd[9],this.Fh=0|nd[10],this.Fl=0|nd[11],this.Gh=0|nd[12],this.Gl=0|nd[13],this.Hh=0|nd[14],this.Hl=0|nd[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)dd[s]=e.getUint32(t),hd[s]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|dd[e-15],s=0|hd[e-15],n=Yc(t,s,1)^Yc(t,s,8)^Gc(t,0,7),r=Xc(t,s,1)^Xc(t,s,8)^Jc(t,s,7),i=0|dd[e-2],o=0|hd[e-2],a=Yc(i,o,19)^Zc(i,o,61)^Gc(i,0,6),c=Xc(i,o,19)^Qc(i,o,61)^Jc(i,o,6),l=il(r,c,hd[e-7],hd[e-16]),d=ol(l,n,a,dd[e-7],dd[e-16]);dd[e]=0|d,hd[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=Yc(d,h,14)^Yc(d,h,18)^Zc(d,h,41),w=Xc(d,h,14)^Xc(d,h,18)^Qc(d,h,41),b=d&u^~d&f,v=al(y,w,h&p^~h&g,ld[e],hd[e]),E=cl(v,m,t,b,cd[e],dd[e]),C=0|v,N=Yc(s,n,28)^Zc(s,n,34)^Zc(s,n,39),A=Xc(s,n,28)^Qc(s,n,34)^Qc(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}=sl(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 _=nl(C,A,S);s=rl(_,E,N,I),n=0|_}({h:s,l:n}=sl(0|this.Ah,0|this.Al,0|s,0|n)),({h:r,l:i}=sl(0|this.Bh,0|this.Bl,0|r,0|i)),({h:o,l:a}=sl(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:l}=sl(0|this.Dh,0|this.Dl,0|c,0|l)),({h:d,l:h}=sl(0|this.Eh,0|this.El,0|d,0|h)),({h:u,l:p}=sl(0|this.Fh,0|this.Fl,0|u,0|p)),({h:f,l:g}=sl(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=sl(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(){yl(dd,hd)}destroy(){yl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class pd extends ud{constructor(){super(48),this.Ah=0|sd[0],this.Al=0|sd[1],this.Bh=0|sd[2],this.Bl=0|sd[3],this.Ch=0|sd[4],this.Cl=0|sd[5],this.Dh=0|sd[6],this.Dl=0|sd[7],this.Eh=0|sd[8],this.El=0|sd[9],this.Fh=0|sd[10],this.Fl=0|sd[11],this.Gh=0|sd[12],this.Gl=0|sd[13],this.Hh=0|sd[14],this.Hl=0|sd[15]}}const fd=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class gd extends ud{constructor(){super(32),this.Ah=0|fd[0],this.Al=0|fd[1],this.Bh=0|fd[2],this.Bl=0|fd[3],this.Ch=0|fd[4],this.Cl=0|fd[5],this.Dh=0|fd[6],this.Dl=0|fd[7],this.Eh=0|fd[8],this.El=0|fd[9],this.Fh=0|fd[10],this.Fl=0|fd[11],this.Gh=0|fd[12],this.Gl=0|fd[13],this.Hh=0|fd[14],this.Hl=0|fd[15]}}const md=Ul((()=>new od)),yd=Ul((()=>new ud)),wd=Ul((()=>new pd)),bd=Ul((()=>new gd)),vd=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]),Ed=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Cd=new Uint32Array(32);function Nd(e,t,s,n,r,i){const o=r[i],a=r[i+1];let c=Cd[2*e],l=Cd[2*e+1],d=Cd[2*t],h=Cd[2*t+1],u=Cd[2*s],p=Cd[2*s+1],f=Cd[2*n],g=Cd[2*n+1],m=nl(c,d,o);l=rl(m,l,h,a),c=0|m,({Dh:g,Dl:f}={Dh:g^l,Dl:f^c}),({Dh:g,Dl:f}={Dh:el(0,f),Dl:tl(g)}),({h:p,l:u}=sl(p,u,g,f)),({Bh:h,Bl:d}={Bh:h^p,Bl:d^u}),({Bh:h,Bl:d}={Bh:Yc(h,d,24),Bl:Xc(h,d,24)}),Cd[2*e]=c,Cd[2*e+1]=l,Cd[2*t]=d,Cd[2*t+1]=h,Cd[2*s]=u,Cd[2*s+1]=p,Cd[2*n]=f,Cd[2*n+1]=g}function Ad(e,t,s,n,r,i){const o=r[i],a=r[i+1];let c=Cd[2*e],l=Cd[2*e+1],d=Cd[2*t],h=Cd[2*t+1],u=Cd[2*s],p=Cd[2*s+1],f=Cd[2*n],g=Cd[2*n+1],m=nl(c,d,o);l=rl(m,l,h,a),c=0|m,({Dh:g,Dl:f}={Dh:g^l,Dl:f^c}),({Dh:g,Dl:f}={Dh:Yc(g,f,16),Dl:Xc(g,f,16)}),({h:p,l:u}=sl(p,u,g,f)),({Bh:h,Bl:d}={Bh:h^p,Bl:d^u}),({Bh:h,Bl:d}={Bh:Zc(h,d,63),Bl:Qc(h,d,63)}),Cd[2*e]=c,Cd[2*e+1]=l,Cd[2*t]=d,Cd[2*t+1]=h,Cd[2*s]=u,Cd[2*s+1]=p,Cd[2*n]=f,Cd[2*n+1]=g}class Id extends Rl{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,hl(e),hl(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=ml(this.buffer)}update(e){fl(this),ul(e=xl(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&&(Nl(n),this.compress(n,0,!1),Nl(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));Nl(e);for(let s=0;a+t<r;s+=n.length,a+=t)this.length+=t,this.compress(e,s,!1);Nl(e)}}return this}digestInto(e){fl(this),gl(e,this);const{pos:t,buffer32:s}=this;this.finished=!0,yl(this.buffer.subarray(t)),Nl(s),this.compress(s,0,!0),Nl(s);const n=ml(e);this.get().forEach(((e,t)=>n[t]=Cl(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 Sd extends Id{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|Ed[0],this.v0h=0|Ed[1],this.v1l=0|Ed[2],this.v1h=0|Ed[3],this.v2l=0|Ed[4],this.v2h=0|Ed[5],this.v3l=0|Ed[6],this.v3h=0|Ed[7],this.v4l=0|Ed[8],this.v4h=0|Ed[9],this.v5l=0|Ed[10],this.v5h=0|Ed[11],this.v6l=0|Ed[12],this.v6h=0|Ed[13],this.v7l=0|Ed[14],this.v7h=0|Ed[15],function(e,t={},s,n,r){if(hl(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=xl(s),i=s.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,void 0!==r){r=xl(r);const e=ml(r);this.v4l^=Cl(e[0]),this.v4h^=Cl(e[1]),this.v5l^=Cl(e[2]),this.v5h^=Cl(e[3])}if(void 0!==n){n=xl(n);const e=ml(n);this.v6l^=Cl(e[0]),this.v6h^=Cl(e[1]),this.v7l^=Cl(e[2]),this.v7h^=Cl(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)=>Cd[t]=e)),Cd.set(Ed,16);let{h:n,l:r}=Vc(BigInt(this.length));Cd[24]=Ed[8]^r,Cd[25]=Ed[9]^n,s&&(Cd[28]=~Cd[28],Cd[29]=~Cd[29]);let i=0;const o=vd;for(let s=0;s<12;s++)Nd(0,4,8,12,e,t+2*o[i++]),Ad(0,4,8,12,e,t+2*o[i++]),Nd(1,5,9,13,e,t+2*o[i++]),Ad(1,5,9,13,e,t+2*o[i++]),Nd(2,6,10,14,e,t+2*o[i++]),Ad(2,6,10,14,e,t+2*o[i++]),Nd(3,7,11,15,e,t+2*o[i++]),Ad(3,7,11,15,e,t+2*o[i++]),Nd(0,5,10,15,e,t+2*o[i++]),Ad(0,5,10,15,e,t+2*o[i++]),Nd(1,6,11,12,e,t+2*o[i++]),Ad(1,6,11,12,e,t+2*o[i++]),Nd(2,7,8,13,e,t+2*o[i++]),Ad(2,7,8,13,e,t+2*o[i++]),Nd(3,4,9,14,e,t+2*o[i++]),Ad(3,4,9,14,e,t+2*o[i++]);this.v0l^=Cd[0]^Cd[16],this.v0h^=Cd[1]^Cd[17],this.v1l^=Cd[2]^Cd[18],this.v1h^=Cd[3]^Cd[19],this.v2l^=Cd[4]^Cd[20],this.v2h^=Cd[5]^Cd[21],this.v3l^=Cd[6]^Cd[22],this.v3h^=Cd[7]^Cd[23],this.v4l^=Cd[8]^Cd[24],this.v4h^=Cd[9]^Cd[25],this.v5l^=Cd[10]^Cd[26],this.v5h^=Cd[11]^Cd[27],this.v6l^=Cd[12]^Cd[28],this.v6h^=Cd[13]^Cd[29],this.v7l^=Cd[14]^Cd[30],this.v7h^=Cd[15]^Cd[31],yl(Cd)}destroy(){this.destroyed=!0,yl(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const _d=function(e){const t=(t,s)=>e(s).update(xl(t)).digest(),s=e({});return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=t=>e(t),t}((e=>new Sd(e))),Od="https://rpc.walletconnect.org/v1";function Td(e){const t=`Ethereum Signed Message:\n${e.length}`,s=(new TextEncoder).encode(t+e);return"0x"+Buffer.from(Xl(s)).toString("hex")}async function kd(e,s,n,r,i,o){switch(n.t){case"eip191":return await function(e,s,n){const r=t.fromHex(n);return t.recoverAddress({payload:Td(s),signature:r}).toLowerCase()===e.toLowerCase()}(e,s,n.s);case"eip1271":return await async function(e,t,s,n,r,i){const o=ec(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:Td(t)).substring(2)+a+l+c,h=await fetch(`${i||Od}/?chainId=${n}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:xd(),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,s,n.s,r,i,o);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function xd(){return Date.now()+Math.floor(1e3*Math.random())}function Pd(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=_d(n,{dkLen:32});return Va.encode(r)}function Rd(e){const t=new Uint8Array(md(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 Va.encode(t)}function Ud(e){const s=Buffer.from(e,"base64"),n=t.decode(s).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=t.encode(n),i=Buffer.from("TX"),o=Buffer.concat([i,Buffer.from(r)]),a=bd(o);return Wa.encode(a).replace(/=+$/,"")}function Ld(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 Dd(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(Ld(t.length)),r.push(t),r.push(Buffer.from([18])),r.push(Ld(s.length)),r.push(s),r.push(Buffer.from([26])),r.push(Ld(n.length)),r.push(n);const i=Buffer.concat(r),o=md(i);return Buffer.from(o).toString("hex").toUpperCase()}var Md=Object.defineProperty,Bd=Object.defineProperties,jd=Object.getOwnPropertyDescriptors,$d=Object.getOwnPropertySymbols,Fd=Object.prototype.hasOwnProperty,qd=Object.prototype.propertyIsEnumerable,Wd=(e,t,s)=>t in e?Md(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Hd=(e,t)=>{for(var s in t||(t={}))Fd.call(t,s)&&Wd(e,s,t[s]);if($d)for(var s of $d(t))qd.call(t,s)&&Wd(e,s,t[s]);return e},zd=(e,t)=>Bd(e,jd(t));const Vd="did:pkh:",Kd={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},Gd=e=>e?.split(":"),Jd=e=>{const t=e&&Gd(e);if(t)return t[2]+":"+t[3]},Yd=e=>{const t=e&&Gd(e);if(t)return t.pop()};async function Xd(e){const{cacao:t,projectId:s}=e,{s:n,p:r}=t,i=Zd(r,r.iss),o=Yd(r.iss);return await kd(o,i,n,Jd(r.iss),s)}const Zd=(e,t)=>{const s=(e=>{const t=e&&Gd(e);if(t)return e.includes(Vd)?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?Kd[e]||e:"")(s)} account:`,r=Yd(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&&Gd(e);if(t)return e.includes(Vd)?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=ah(e.resources);if(g){i=function(e="",t){Qd(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,sh(g))}return[n,r,"",i,"",o,a,c,l,d,h,u,p,f].filter((e=>null!=e)).join("\n")};function Qd(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 eh(e,t,s={}){t=t?.sort(((e,t)=>e.localeCompare(t)));const n=t.map((t=>({[`${e}/${t}`]:[s]})));return Object.assign({},...n)}function th(e){return Qd(e),`urn:recap:${function(e){return Buffer.from(JSON.stringify(e)).toString("base64")}(e).replace(/=/g,"")}`}function sh(e){const t=function(e){return JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}(e.replace("urn:recap:",""));return Qd(t),t}function nh(e,t,s){const n=function(e,t,s,n={}){return s?.sort(((e,t)=>e.localeCompare(t))),{att:{[e]:eh(t,s,n)}}}(e,t,s);return th(n)}function rh(e,t){const s=function(e,t){Qd(e),Qd(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]=zd(Hd({},n.att[s]),{[r]:(null==(i=e.att[s])?void 0:i[r])||(null==(o=t.att[s])?void 0:o[r])})}))})),n}(sh(e),sh(t));return th(s)}function ih(e){var t;const s=sh(e);Qd(s);const n=null==(t=s.att)?void 0:t.eip155;return n?Object.keys(n).map((e=>e.split("/")[1])):[]}function oh(e){const t=sh(e);Qd(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 ah(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 ch(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function lh(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function dh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function hh(e,...t){if(!ch(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 uh(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 ph(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function fh(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const gh=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function mh(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(!ch(e))throw new Error("Uint8Array expected, got "+typeof e);e=vh(e)}return e}function yh(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 wh(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 bh(e,t,s){lh(s);const n=new Uint8Array(16),r=function(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}(n);return wh(r,0,BigInt(t),s),wh(r,8,BigInt(e),s),n}function vh(e){return Uint8Array.from(e)}const Eh=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),Ch=Eh("expand 16-byte k"),Nh=Eh("expand 32-byte k"),Ah=ph(Ch),Ih=ph(Nh);function Sh(e,t){return e<<t|e>>>32-t}function _h(e){return e.byteOffset%4==0}const Oh=64,Th=16,kh=2**32-1,xh=new Uint32Array;const Ph=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Rh{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,hh(e=mh(e),32);const t=Ph(e,0),s=Ph(e,2),n=Ph(e,4),r=Ph(e,6),i=Ph(e,8),o=Ph(e,10),a=Ph(e,12),c=Ph(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]=Ph(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=Ph(e,t+0),y=Ph(e,t+2),w=Ph(e,t+4),b=Ph(e,t+6),v=Ph(e,t+8),E=Ph(e,t+10),C=Ph(e,t+12),N=Ph(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)),x=r[7]+(8191&(E>>>11|C<<5)),P=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)+x*(5*l)+P*(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)+x*(5*d)+P*(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)+x*(5*h)+P*(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)+x*(5*u)+P*(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)+x*(5*p)+P*(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)+x*(5*f)+P*(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+x*(5*g)+P*(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+x*o+P*(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+x*a+P*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+x*c+P*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;fh(s)}update(e){uh(this),hh(e=mh(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(){fh(this.h,this.r,this.buffer,this.pad)}digestInto(e){uh(this),function(e,t){hh(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 Uh=function(e){const t=(t,s)=>e(s).update(mh(t)).digest(),s=e(new Uint8Array(32));return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=t=>e(t),t}((e=>new Rh(e)));const Lh=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 dh(r),dh(o),lh(i),lh(s),(t,a,c,l,d=0)=>{hh(t),hh(a),hh(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),hh(l),dh(d),d<0||d>=kh)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=vh(t)),f=Ih;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=Ah,u.push(p)}_h(a)||u.push(a=vh(a));const m=ph(p);if(n){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");n(f,m,ph(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=ph(a);return function(e,t,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(Oh),d=ph(l),h=_h(r)&&_h(i),u=h?ph(r):xh,p=h?ph(i):xh;for(let f=0;f<c;o++){if(e(t,s,n,d,o,a),o>=kh)throw new Error("arx: counter overflow");const g=Math.min(Oh,c-f);if(h&&g===Oh){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,s=0;s<Th;s++)t=e+s,p[t]=u[t]^d[s];f+=Oh}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),fh(...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,x=g,P=m,R=y,U=w,L=b,D=v,M=E;for(let e=0;e<i;e+=2)C=C+S|0,U=Sh(U^C,16),k=k+U|0,S=Sh(S^k,12),C=C+S|0,U=Sh(U^C,8),k=k+U|0,S=Sh(S^k,7),N=N+_|0,L=Sh(L^N,16),x=x+L|0,_=Sh(_^x,12),N=N+_|0,L=Sh(L^N,8),x=x+L|0,_=Sh(_^x,7),A=A+O|0,D=Sh(D^A,16),P=P+D|0,O=Sh(O^P,12),A=A+O|0,D=Sh(D^A,8),P=P+D|0,O=Sh(O^P,7),I=I+T|0,M=Sh(M^I,16),R=R+M|0,T=Sh(T^R,12),I=I+T|0,M=Sh(M^I,8),R=R+M|0,T=Sh(T^R,7),C=C+_|0,M=Sh(M^C,16),P=P+M|0,_=Sh(_^P,12),C=C+_|0,M=Sh(M^C,8),P=P+M|0,_=Sh(_^P,7),N=N+O|0,U=Sh(U^N,16),R=R+U|0,O=Sh(O^R,12),N=N+O|0,U=Sh(U^N,8),R=R+U|0,O=Sh(O^R,7),A=A+T|0,L=Sh(L^A,16),k=k+L|0,T=Sh(T^k,12),A=A+T|0,L=Sh(L^A,8),k=k+L|0,T=Sh(T^k,7),I=I+S|0,D=Sh(D^I,16),x=x+D|0,S=Sh(S^x,12),I=I+S|0,D=Sh(D^I,8),x=x+D|0,S=Sh(S^x,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+x|0,n[B++]=m+P|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}),Dh=new Uint8Array(16),Mh=(e,t)=>{e.update(t);const s=t.length%16;s&&e.update(Dh.subarray(s))},Bh=new Uint8Array(32);function jh(e,t,s,n,r){const i=e(t,s,Bh),o=Uh.create(i);r&&Mh(o,r),Mh(o,n);const a=bh(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return fh(i,a),c}const $h=((e,t)=>{function s(s,...n){if(hh(s),!gh)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?hh(t):hh(t,e.nonceLength)}const r=e.tagLength;r&&void 0!==n[1]&&hh(n[1]);const i=t(s,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");hh(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,hh(e),o(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(hh(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=yh(o+16,i,!1)).set(r);const a=i.subarray(0,-16);e(t,s,a,a,1);const c=jh(e,t,s,a,n);return i.set(c,o),fh(c),i},decrypt(r,i){i=yh(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=jh(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),fh(c),i}}))(Lh));class Fh extends Rl{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,pl(e);const s=xl(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),yl(r)}update(e){return fl(this),this.iHash.update(e),this}digestInto(e){fl(this),ul(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 qh=(e,t,s)=>new Fh(e,t).update(s).digest();qh.create=(e,t)=>new Fh(e,t);const Wh=Uint8Array.from([0]),Hh=Uint8Array.of();const zh=(e,t,s,n,r)=>function(e,t,s,n=32){pl(e),hl(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=Hh);const o=new Uint8Array(i*r),a=qh.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let e=0;e<i;e++)Wh[0]=e+1,c.update(0===e?Hh:l).update(s).update(Wh).digestInto(l),o.set(l,r*e),a._cloneInto(c);return a.destroy(),c.destroy(),yl(l,Wh),o.slice(0,n)}(e,function(e,t,s){return pl(e),void 0===s&&(s=new Uint8Array(e.outputLen)),qh(e,xl(s),xl(t))}(e,t,s),n,r),Vh=md,Kh=BigInt(0),Gh=BigInt(1);function Jh(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function Yh(e,t,s=""){const n=dl(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 Xh(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Zh(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Kh:BigInt("0x"+e)}function Qh(e){return Zh(Sl(e))}function eu(e){return ul(e),Zh(Sl(Uint8Array.from(e).reverse()))}function tu(e,t){return Tl(e.toString(16).padStart(2*t,"0"))}function su(e,t){return tu(e,t).reverse()}function nu(e,t,s){let n;if("string"==typeof t)try{n=Tl(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!dl(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 ru=e=>"bigint"==typeof e&&Kh<=e;function iu(e,t,s,n){if(!function(e,t,s){return ru(e)&&ru(t)&&ru(s)&&t<=e&&e<s}(t,s,n))throw new Error("expected valid "+e+": "+s+" <= n < "+n+", got "+t)}function ou(e){let t;for(t=0;e>Kh;e>>=Gh,t+=1);return t}const au=e=>(Gh<<BigInt(e))-Gh;function cu(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 lu(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 du=BigInt(0),hu=BigInt(1),uu=BigInt(2),pu=BigInt(3),fu=BigInt(4),gu=BigInt(5),mu=BigInt(7),yu=BigInt(8),wu=BigInt(9),bu=BigInt(16);function vu(e,t){const s=e%t;return s>=du?s:t+s}function Eu(e,t,s){let n=e;for(;t-- >du;)n*=n,n%=s;return n}function Cu(e,t){if(e===du)throw new Error("invert: expected non-zero number");if(t<=du)throw new Error("invert: expected positive modulus, got "+t);let s=vu(e,t),n=t,r=du,i=hu;for(;s!==du;){const e=n%s,t=r-i*(n/s);n=s,s=e,r=i,i=t}if(n!==hu)throw new Error("invert: does not exist");return vu(r,t)}function Nu(e,t,s){if(!e.eql(e.sqr(t),s))throw new Error("Cannot find square root")}function Au(e,t){const s=(e.ORDER+hu)/fu,n=e.pow(t,s);return Nu(e,n,t),n}function Iu(e,t){const s=(e.ORDER-gu)/yu,n=e.mul(t,uu),r=e.pow(n,s),i=e.mul(t,r),o=e.mul(e.mul(i,uu),r),a=e.mul(i,e.sub(o,e.ONE));return Nu(e,a,t),a}function Su(e){if(e<pu)throw new Error("sqrt is not defined for small field");let t=e-hu,s=0;for(;t%uu===du;)t/=uu,s++;let n=uu;const r=Pu(e);for(;1===ku(r,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===s)return Au;let i=r.pow(n,t);const o=(t+hu)/uu;return function(e,n){if(e.is0(n))return n;if(1!==ku(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=hu<<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 _u(e){return e%fu===pu?Au:e%yu===gu?Iu:e%bu===wu?function(e){const t=Pu(e),s=Su(e),n=s(t,t.neg(t.ONE)),r=s(t,n),i=s(t,t.neg(n)),o=(e+mu)/bu;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 Nu(e,p,t),p}}(e):Su(e)}const Ou=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Tu(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 ku(e,t){const s=(e.ORDER-hu)/uu,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 xu(e,t){void 0!==t&&hl(t);const s=void 0!==t?t:e.toString(2).length;return{nBitLength:s,nByteLength:Math.ceil(s/8)}}function Pu(e,t,s=!1,n={}){if(e<=du)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}=xu(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:au(c),ZERO:du,ONE:hu,allowedLengths:o,create:t=>vu(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return du<=t&&t<e},is0:e=>e===du,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&hu)===hu,neg:t=>vu(-t,e),eql:(e,t)=>e===t,sqr:t=>vu(t*t,e),add:(t,s)=>vu(t+s,e),sub:(t,s)=>vu(t-s,e),mul:(t,s)=>vu(t*s,e),pow:(e,t)=>function(e,t,s){if(s<du)throw new Error("invalid exponent, negatives unsupported");if(s===du)return e.ONE;if(s===hu)return t;let n=e.ONE,r=t;for(;s>du;)s&hu&&(n=e.mul(n,r)),r=e.sqr(r),s>>=hu;return n}(h,e,t),div:(t,s)=>vu(t*Cu(s,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Cu(t,e),sqrt:i||(t=>(d||(d=_u(e)),d(h,t))),toBytes:e=>s?su(e,l):tu(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?eu(t):Qh(t);if(a&&(r=vu(r,e)),!n&&!h.isValid(r))throw new Error("invalid field element: outside of range 0..ORDER");return r},invertBatch:e=>Tu(h,e),cmov:(e,t,s)=>s?t:e});return Object.freeze(h)}function Ru(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 Uu(e){const t=Ru(e);return t+Math.ceil(t/2)}const Lu=BigInt(0),Du=BigInt(1);function Mu(e,t){const s=t.negate();return e?s:t}function Bu(e,t){const s=Tu(e.Fp,t.map((e=>e.Z)));return t.map(((t,n)=>e.fromAffine(t.toAffine(s[n]))))}function ju(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function $u(e,t){ju(e,t);const s=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:au(e),maxNumber:s,shiftBy:BigInt(e)}}function Fu(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+=Du);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 qu=new WeakMap,Wu=new WeakMap;function Hu(e){return Wu.get(e)||1}function zu(e){if(e!==Lu)throw new Error("invalid wNAF")}class Vu{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>Lu;)t&Du&&(s=s.add(n)),n=n.double(),t>>=Du;return s}precomputeWindow(e,t){const{windows:s,windowSize:n}=$u(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=$u(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:d,offsetF:h}=Fu(s,e,i);s=o,c?r=r.add(Mu(d,t[h])):n=n.add(Mu(l,t[a]))}return zu(s),{p:n,f:r}}wNAFUnsafe(e,t,s,n=this.ZERO){const r=$u(e,this.bits);for(let e=0;e<r.windows&&s!==Lu;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=Fu(s,e,r);if(s=i,!a){const e=t[o];n=n.add(c?e.negate():e)}}return zu(s),n}getPrecomputes(e,t,s){let n=qu.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof s&&(n=s(n)),qu.set(t,n))),n}cached(e,t,s){const n=Hu(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){const r=Hu(e);return 1===r?this._unsafeLadder(e,t,n):this.wNAFUnsafe(r,this.getPrecomputes(r,e,s),t,n)}createCache(e,t){ju(t,this.bits),Wu.set(e,t),qu.delete(e)}hasCache(e){return 1!==Hu(e)}}function Ku(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=ou(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=au(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 Gu(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=Ou.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});cu(e,t)}(t),t}return Pu(e,{isLE:s})}BigInt(0),BigInt(1),BigInt(2),BigInt(8),kl("HashToScalar-");const Ju=BigInt(0),Yu=BigInt(1),Xu=BigInt(2);function Zu(e){const t=function(e){return cu(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||Ll,l=a?255:448,d=a?32:56,h=BigInt(a?9:5),u=BigInt(a?121665:39081),p=a?Xu**BigInt(254):Xu**BigInt(447),f=a?BigInt(8)*Xu**BigInt(251)-Yu:BigInt(4)*Xu**BigInt(445)-Yu,g=p+f+Yu,m=e=>vu(e,s),y=w(h);function w(e){return su(m(e),d)}function b(e,t){const n=function(e,t){iu("u",e,Ju,s),iu("scalar",t,p,g);const n=t,r=e;let o=Yu,a=Ju,c=e,d=Yu,h=Ju;for(let e=BigInt(l-1);e>=Ju;e--){const t=n>>e&Yu;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=nu("u coordinate",e,d);return a&&(t[31]&=127),m(eu(t))}(t),function(e){return eu(r(nu("scalar",e,d)))}(e));if(n===Ju)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))=>(ul(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 Qu=BigInt(1),ep=BigInt(2),tp=BigInt(3),sp=BigInt(5),np=BigInt(8),rp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function ip(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const op=Pu({p:rp,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:np,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}.p,{isLE:!0}),ap=(()=>{const e=op.ORDER;return Zu({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=rp,o=e*e%i*e%i,a=Eu(o,ep,i)*o%i,c=Eu(a,Qu,i)*e%i,l=Eu(c,sp,i)*c%i,d=Eu(l,t,i)*l%i,h=Eu(d,s,i)*d%i,u=Eu(h,n,i)*h%i,p=Eu(u,r,i)*u%i,f=Eu(p,r,i)*u%i,g=Eu(f,t,i)*l%i;return{pow_p_5_8:Eu(g,ep,i)*e%i,b2:o}}(t);return vu(Eu(s,tp,e)*n,e)},adjustScalarBytes:ip})})(),cp=(e,t)=>(e+(e>=0?t:-t)/gp)/t;function lp(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function dp(e,t){const s={};for(let n of Object.keys(t))s[n]=void 0===e[n]?t[n]:e[n];return Jh(s.lowS,"lowS"),Jh(s.prehash,"prehash"),void 0!==s.format&&lp(s.format),s}class hp extends Error{constructor(e=""){super(e)}}const up={Err:hp,_tlv:{encode:(e,t)=>{const{Err:s}=up;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=Xh(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?Xh(r.length/2|128):"";return Xh(e)+i+r+t},decode(e,t){const{Err:s}=up;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}=up;if(e<pp)throw new t("integer: negative integers are not allowed");let s=Xh(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}=up;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 Qh(e)}},toSig(e){const{Err:t,_int:s,_tlv:n}=up,r=nu("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}=up,n=t.encode(2,s.encode(e.r))+t.encode(2,s.encode(e.s));return t.encode(48,n)}},pp=BigInt(0),fp=BigInt(1),gp=BigInt(2),mp=BigInt(3),yp=BigInt(4);function wp(e,t){const{BYTES:s}=e;let n;if("bigint"==typeof t)n=t;else{let r=nu("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 bp(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>Lu))throw new Error(`CURVE.${e} must be positive bigint`)}const r=Gu(t.p,s.Fp,n),i=Gu(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;cu(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=Ep(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(Jh(s,"isCompressed"),s){d();return Pl(vp(!n.isOdd(i)),o)}return Pl(Uint8Array.of(4),o,n.toBytes(i))},u=t.fromBytes||function(e){Yh(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,mp),yp),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=cp(o*e,s),c=cp(-r*e,s);let l=e-a*n-c*i,d=-a*r-c*o;const h=l<pp,u=d<pp;h&&(l=-l),u&&(d=-d);const p=au(Math.ceil(ou(s)/2))+fp;if(l<pp||l>=p||d<pp||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=lu(((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=lu((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=Mu(r,t),s=Mu(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(Yh(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return N.fromBytes(nu("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(mp),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,mp),{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,mp);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=>Bu(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 Bu(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===pp||n.is0())return N.ZERO;if(e===fp)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>Lu||n>Lu;)s&Du&&(i=i.add(r)),n&Du&&(o=o.add(r)),r=r.double(),s>>=Du,n>>=Du;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===fp||(e?e(N,this):I.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===fp?this:e?e(N,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return Jh(e,"isCompressed"),this.assertValidity(),h(N,this,e)}toHex(e=!0){return Sl(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 Bu(N,e)}static msm(e,t){return Ku(N,r,e,t)}static fromPrivateKey(e){return N.BASE.multiply(wp(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 Vu(N,t.endo?Math.ceil(A/2):A);return N.BASE.precompute(8),N}function vp(e){return Uint8Array.of(e?2:3)}function Ep(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Cp(e,t={}){const{Fn:s}=e,n=t.randomBytes||Ll,r=Object.assign(Ep(e.Fp,s),{seed:Uu(s.ORDER)});function i(e){try{return!!wp(s,e)}catch{return!1}}function o(e=n(r.seed)){return function(e,t,s=!1){const n=e.length,r=Ru(t),i=Uu(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=vu(s?eu(e):Qh(e),t-hu)+hu;return s?su(o,r):tu(o,r)}(Yh(e,r.seed,"seed"),s.ORDER)}function a(t,n=!0){return e.BASE.multiply(wp(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=nu("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=wp(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=>wp(s,e),precompute:(t=8,s=e.BASE)=>s.precompute(t,!1)},lengths:r})}function Np(e,t,s={}){pl(t),cu(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||Ll,r=s.hmac||((e,...s)=>qh(t,e,Pl(...s))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:u,lengths:p}=Cp(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>>fp}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){lp(t);const s=p.signature;Yh(e,"compact"===t?s:"recovered"===t?s+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:s}=up.toSig(Yh(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(Tl(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*gp<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(Pl(vp(0==(1&c)),d)),u=o.inv(l),p=v(nu("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(lp(e),"der"===e)return Tl(up.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 Pl(Uint8Array.of(this.recovery),t,s)}return Pl(t,s)}toHex(e){return Sl(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(nu("sig",e),"compact")}static fromDER(e){return w.fromBytes(nu("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 Sl(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Sl(this.toBytes("compact"))}}const b=s.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Qh(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=au(c);function C(e){return iu("num < 2^"+c,e,pp,E),o.toBytes(e)}function N(e,s){return Yh(e,void 0,"message"),s?Yh(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=nu("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}=dp(r,f);t=N(t,a);const l=v(t),d=wp(o,s),h=[C(d),C(l)];if(null!=c&&!1!==c){const e=!0===c?n(p.secretKey):c;h.push(nu("extraEntropy",e))}const u=Pl(...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===pp)return;const c=o.create(n*o.create(g+a*d));if(c===pp)return;let l=(r.x===a?0:2)|Number(r.y&fp),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 Pl(...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}=dp(r,f);if(n=nu("publicKey",n),s=N(nu("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||dl(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(nu("sig",e),"der")}catch(e){if(!(e instanceof up.Err))throw e}if(!t)try{t=w.fromBytes(nu("sig",e),"compact")}catch{return!1}}return t||!1}(t):w.fromBytes(nu("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}=dp(s,f);return t=N(t,n),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function Ap(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:Pu(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 Ip(e){const{CURVE:t,curveOpts:s,hash:n,ecdsaOpts:r}=Ap(e);return function(e,t){const s=t.Point;return Object.assign({},t,{ProjectivePoint:s,CURVE:Object.assign({},e,xu(s.Fn.ORDER,s.Fn.BITS))})}(e,Np(bp(t,s),n,r))}function Sp(e,t){const s=t=>Ip({...e,hash:t});return{...s(t),create:s}}const _p={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Op={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Tp={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},kp=Pu(_p.p),xp=Pu(Op.p),Pp=Pu(Tp.p),Rp=Sp({..._p,Fp:kp,lowS:!1},md);Sp({...Op,Fp:xp,lowS:!1},wd),Sp({...Tp,Fp:Pp,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},yd);const Up=Rp,Lp="base10",Dp="base16",Mp="base64pad",Bp="base64url",jp="utf8",$p=0,Fp=1,qp=2,Wp=0,Hp=1,zp=12,Vp=32;function Kp(){const e=Ll(Vp);return t.toString(e,Dp)}function Gp(e){const s=Vh(t.fromString(e,Dp));return t.toString(s,Dp)}function Jp(e){const s=Vh(t.fromString(e,jp));return t.toString(s,Dp)}function Yp(e){return t.fromString(`${e}`,Lp)}function Xp(e){return Number(t.toString(e,Lp))}function Zp(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Qp(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=(4-t.length%4)%4;return t+"=".repeat(s)}function ef(e){if(Xp(e.type)===qp)return t.toString(t.concat([e.type,e.sealed]),Mp);if(Xp(e.type)===Fp){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return t.toString(t.concat([e.type,e.senderPublicKey,e.iv,e.sealed]),Mp)}return t.toString(t.concat([e.type,e.iv,e.sealed]),Mp)}function tf(e){const s=(e.encoding||Mp)===Bp?Qp(e.encoded):e.encoded,n=t.fromString(s,Mp),r=n.slice(Wp,Hp),i=Hp;if(Xp(r)===Fp){const e=i+Vp,t=e+zp,s=n.slice(i,e),o=n.slice(e,t);return{type:r,sealed:n.slice(t),iv:o,senderPublicKey:s}}if(Xp(r)===qp){return{type:r,sealed:n.slice(i),iv:Ll(zp)}}const o=i+zp,a=n.slice(i,o);return{type:r,sealed:n.slice(o),iv:a}}function sf(e){const t=e?.type||$p;if(t===Fp){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 nf(e){return e.type===Fp&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function rf(e){return e.type===qp}function of(e,s){const[n,r,i]=e.split("."),o=Buffer.from(Qp(i),"base64");if(64!==o.length)throw new Error("Invalid signature length");const a=o.slice(0,32),c=o.slice(32,64),l=Vh(`${n}.${r}`),d=function(e){const s=Buffer.from(e.x,"base64"),n=Buffer.from(e.y,"base64");return t.concat([new Uint8Array([4]),s,n])}(s);if(!Up.verify(t.concat([a,c]),l,d))throw new Error("Invalid signature");return va(e).payload}function af(e){return e?.relay||{protocol:"irn"}}function cf(e){const t=Za[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}var lf=Object.defineProperty,df=Object.defineProperties,hf=Object.getOwnPropertyDescriptors,uf=Object.getOwnPropertySymbols,pf=Object.prototype.hasOwnProperty,ff=Object.prototype.propertyIsEnumerable,gf=(e,t,s)=>t in e?lf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,mf=(e,t)=>{for(var s in t||(t={}))pf.call(t,s)&&gf(e,s,t[s]);if(uf)for(var s of uf(t))ff.call(t,s)&&gf(e,s,t[s]);return e};function yf(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 wf(e){if(!e.includes("wc:")){const t=qc(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:bf(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:yf(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function bf(e){return e.startsWith("//")?e.substring(2):e}function vf(e){const t=new URLSearchParams,s=mf(mf(((e,t)=>df(e,hf(t)))(mf({},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 Ef(e,t,s){return`${e}?wc_ev=${s}&topic=${t}`}var Cf=Object.defineProperty,Nf=Object.defineProperties,Af=Object.getOwnPropertyDescriptors,If=Object.getOwnPropertySymbols,Sf=Object.prototype.hasOwnProperty,_f=Object.prototype.propertyIsEnumerable,Of=(e,t,s)=>t in e?Cf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Tf=(e,t)=>{for(var s in t||(t={}))Sf.call(t,s)&&Of(e,s,t[s]);if(If)for(var s of If(t))_f.call(t,s)&&Of(e,s,t[s]);return e},kf=(e,t)=>Nf(e,Af(t));function xf(e){const t=[];return e.forEach((e=>{const[s,n]=e.split(":");t.push(`${s}:${n}`)})),t}function Pf(e){const t=[];return Object.values(e).forEach((e=>{t.push(...xf(e.accounts))})),[...new Set(t)]}function Rf(e){return e.includes(":")}function Uf(e){return Rf(e)?e.split(":")[0]:e}function Lf(e){var t,s,n;const r={};if(!Bf(e))return r;for(const[i,o]of Object.entries(e)){const e=Rf(i)?[i]:o.chains,a=o.methods||[],c=o.events||[],l=Uf(i);r[l]=kf(Tf({},r[l]),{chains:Mc(e,null==(t=r[l])?void 0:t.chains),methods:Mc(a,null==(s=r[l])?void 0:s.methods),events:Mc(c,null==(n=r[l])?void 0:n.events)})}return r}function Df(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=Mc(n.methods,e):n.methods=e,n.events=["chainChanged","accountsChanged"];return s}function Mf(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function Bf(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function jf(e){return typeof e>"u"}function $f(e,t){return!(!t||!jf(e))||"string"==typeof e&&!!e.trim().length}function Ff(e,t){return!(!t||!jf(e))||"number"==typeof e&&!isNaN(e)}function qf(e){return!(!$f(e,!1)||!e.includes(":"))&&2===e.split(":").length}function Wf(e){let t=!0;return Mf(e)?e.length&&(t=e.every((e=>$f(e,!1)))):t=!1,t}function Hf(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 Mf(t)&&t.length?t.forEach((e=>{n||qf(e)||(n=ic("UNSUPPORTED_CHAINS",`${s}, chain ${e} should be a string and conform to "namespace:chainId" format`))})):qf(e)||(n=ic("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,tc(e,r),`${t} ${s}`);i&&(n=i)})),n}function zf(e,t){let s=null;return Mf(e)?e.forEach((e=>{s||function(e){if($f(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&qf(e)}}return!1}(e)||(s=ic("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))})):s=ic("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function Vf(e,t){let s=null;return Object.values(e).forEach((e=>{if(s)return;const n=function(e,t){let s=null;return Wf(e?.methods)?Wf(e?.events)||(s=ic("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):s=ic("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 Kf(e,t){let s=null;if(e&&Bf(e)){const n=Vf(e,t);n&&(s=n);const r=function(e,t){let s=null;return Object.values(e).forEach((e=>{if(s)return;const n=zf(e?.accounts,`${t} namespace`);n&&(s=n)})),s}(e,t);r&&(s=r)}else s=rc("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return s}function Gf(e){return $f(e.protocol,!0)}function Jf(e){return typeof e<"u"&&null!==typeof e}function Yf(e,t){return!(!qf(t)||!Pf(e).includes(t))}function Xf(e,t,s){return!!$f(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach((e=>{xf(e.accounts).includes(t)&&s.push(...e.methods)})),s}(e,t).includes(s)}function Zf(e,t,s){return!!$f(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach((e=>{xf(e.accounts).includes(t)&&s.push(...e.events)})),s}(e,t).includes(s)}function Qf(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=xf(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=eg(Object.keys(e)),l=eg(Object.keys(t)),d=c.filter((e=>!l.includes(e)));return d.length&&(n=rc("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(t).toString()}`)),_c(o,a)||(n=rc("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=xf(t[e].accounts);r.includes(e)||(n=rc("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${r.toString()}`))})),o.forEach((e=>{n||(_c(r[e].methods,i[e].methods)?_c(r[e].events,i[e].events)||(n=rc("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${e}`)):n=rc("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${e}`))})),n}function eg(e){return[...new Set(e.map((e=>e.includes(":")?e.split(":")[0]:e)))]}function tg(){const e=Ec();return new Promise((t=>{switch(e){case mc.browser:t(vc()&&navigator?.onLine);break;case mc.reactNative:t(async function(){if(bc()&&typeof global<"u"&&null!=global&&global.NetInfo){const e=await(null==global?void 0:global.NetInfo.fetch());return e?.isConnected}return!0}());break;case mc.node:default:t(!0)}}))}function sg(e){switch(Ec()){case mc.browser:!function(e){!bc()&&vc()&&(window.addEventListener("online",(()=>e(!0))),window.addEventListener("offline",(()=>e(!1))))}(e);break;case mc.reactNative:!function(e){bc()&&typeof global<"u"&&null!=global&&global.NetInfo&&global?.NetInfo.addEventListener((t=>e(t?.isConnected)))}(e)}}const ng={};class rg{static get(e){return ng[e]}static set(e,t){ng[e]=t}static delete(e){delete ng[e]}}function ig({publicKey:e,signature:t,payload:s}){var n;const r=og(s.method),i=128|parseInt((null==(n=s.version)?void 0:n.toString())||"4"),o=function(e){const t=Va.decode(e)[0];return 42===t?0:60===t?2:1}(s.address),a="00"===s.era?new Uint8Array([0]):og(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 og(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map((e=>parseInt(e,16))))}function ag(e){const s=Uint8Array.from(Buffer.from(e.signature,"hex")),n=function(e){const t=Va.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}(e.transaction.address),r=ig({publicKey:n,signature:s,payload:e.transaction});return function(e){const s=og(e),n=t.blakejs.blake2b(s,void 0,32);return"0x"+Buffer.from(n).toString("hex")}(Buffer.from(r).toString("hex"))}function cg({logger:e,name:t}){const s="string"==typeof e?Pn({opts:{level:e,name:t}}).logger:e;return s.level="string"==typeof e?e:e.level,s}class lg extends t.IJsonRpcProvider{constructor(t){super(t),this.events=new e.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),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,s){return this.requestStrict(t.formatJsonRpcRequest(e.method,e.params||[],e.id||t.getBigIntRpcId().toString()),s)}async requestStrict(e,s){return new Promise((async(n,r)=>{if(!this.connection.connected)try{await this.open()}catch(e){r(e)}this.events.on(`${e.id}`,(e=>{t.isJsonRpcError(e)?r(e.error):n(e.result)}));try{await this.connection.send(e,s)}catch(e){r(e)}}))}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),t.isJsonRpcResponse(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 dg=e=>e.split("?")[0],hg=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 ug{constructor(s){if(this.url=s,this.events=new e.EventEmitter,this.registering=!1,!t.isWsUrl(s))throw new Error(`Provided URL is not compatible with WebSocket connection: ${s}`);this.url=s}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(t.safeJsonStringify(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!t.isWsUrl(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(((s,n)=>{const r=t.cjs$1.isReactNative()?void 0:{rejectUnauthorized:!t.isLocalhostUrl(e)},i=new hg(e,[],r);typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u"?i.onerror=e=>{const t=e;n(this.emitError(t.error))}:i.on("error",(e=>{n(this.emitError(e))})),i.onopen=()=>{this.onOpen(i),s(i)}}))}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 s="string"==typeof e.data?t.safeJsonParse(e.data):e.data;this.events.emit("payload",s)}onError(e,s){const n=this.parseError(s),r=n.message||n.toString(),i=t.formatJsonRpcError(e,r);this.events.emit("payload",i)}parseError(e,s=this.url){return t.parseConnectionError(e,dg(s),"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: ${dg(this.url)}`));return this.events.emit("register_error",t),t}}const pg="core",fg=`wc@2:${pg}:`,gg="error",mg={database:":memory:"},yg="client_ed25519_seed",wg=t.cjs.ONE_DAY,bg=t.cjs.SIX_HOURS,vg="wss://relay.walletconnect.org",Eg="relayer_message",Cg="relayer_message_ack",Ng="relayer_connect",Ag="relayer_disconnect",Ig="relayer_error",Sg="relayer_connection_stalled",_g="relayer_publish",Og="payload",Tg="connect",kg="disconnect",xg="error",Pg="2.23.7",Rg={link_mode:"link_mode",relay:"relay"},Ug="inbound",Lg="outbound",Dg="WALLETCONNECT_LINK_MODE_APPS",Mg="subscription_created",Bg="subscription_deleted",jg="subscription_sync",$g="subscription_resubscribed",Fg={wc_pairingDelete:{req:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:t.cjs.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:t.cjs.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:0},res:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:0}}},qg="pairing_create",Wg="pairing_expire",Hg="pairing_delete",zg="pairing_ping",Vg="history_created",Kg="history_updated",Gg="history_deleted",Jg="history_sync",Yg="expirer_created",Xg="expirer_deleted",Zg="expirer_expired",Qg="expirer_sync",em="https://verify.walletconnect.org",tm=em,sm=`${tm}/v3`,nm=["https://verify.walletconnect.com",em],rm="pairing_started",im="pairing_uri_validation_success",om="pairing_uri_not_expired",am="store_new_pairing",cm="subscribing_pairing_topic",lm="subscribe_pairing_topic_success",dm="existing_pairing",hm="pairing_not_expired",um="emit_inactive_pairing",pm="emit_session_proposal",fm="no_internet_connection",gm="malformed_pairing_uri",mm="active_pairing_already_exists",ym="subscribe_pairing_topic_failure",wm="pairing_expired",bm="proposal_listener_not_found",vm="session_approve_started",Em="session_namespaces_validation_success",Cm="subscribing_session_topic",Nm="subscribe_session_topic_success",Am="session_approve_publish_success",Im="store_session",Sm="session_request_response_started",_m="session_request_response_validation_success",Om="session_request_response_publish_started",Tm="no_internet_connection",km="proposal_expired",xm="subscribe_session_topic_failure",Pm="session_approve_namespace_validation_failure",Rm="proposal_not_found",Um="session_request_response_validation_failure",Lm="session_request_response_publish_failure",Dm="authenticated_session_approve_started",Mm="create_authenticated_session_topic",Bm="cacaos_verified",jm="store_authenticated_session",$m="subscribing_authenticated_session_topic",Fm="subscribe_authenticated_session_topic_success",qm="publishing_authenticated_session_approve",Wm="no_internet_connection",Hm="invalid_cacao",zm="subscribe_authenticated_session_topic_failure",Vm="authenticated_session_approve_publish_failure",Km="authenticated_session_pending_request_not_found";var Gm=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`)}}},Jm=Gm;const Ym=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 Xm{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 Zm{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 ey(this,e)}}class Qm{constructor(e){this.decoders=e}or(e){return ey(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 ey=(e,t)=>new Qm({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class ty{constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Xm(e,t,s),this.decoder=new Zm(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const sy=({name:e,prefix:t,encode:s,decode:n})=>new ty(e,t,s,n),ny=({prefix:e,name:t,alphabet:s})=>{const{encode:n,decode:r}=Jm(s,t);return sy({prefix:e,name:t,encode:n,decode:e=>Ym(r(e))})},ry=({name:e,prefix:t,bitsPerChar:s,alphabet:n})=>sy({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)}),iy=sy({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var oy=Object.freeze({__proto__:null,identity:iy});const ay=ry({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cy=Object.freeze({__proto__:null,base2:ay});const ly=ry({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var dy=Object.freeze({__proto__:null,base8:ly});const hy=ny({prefix:"9",name:"base10",alphabet:"0123456789"});var uy=Object.freeze({__proto__:null,base10:hy});const py=ry({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),fy=ry({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gy=Object.freeze({__proto__:null,base16:py,base16upper:fy});const my=ry({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yy=ry({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),wy=ry({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),by=ry({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vy=ry({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ey=ry({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cy=ry({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ny=ry({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ay=ry({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Iy=Object.freeze({__proto__:null,base32:my,base32upper:yy,base32pad:wy,base32padupper:by,base32hex:vy,base32hexupper:Ey,base32hexpad:Cy,base32hexpadupper:Ny,base32z:Ay});const Sy=ny({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_y=ny({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Oy=Object.freeze({__proto__:null,base36:Sy,base36upper:_y});const Ty=ny({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ky=ny({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xy=Object.freeze({__proto__:null,base58btc:Ty,base58flickr:ky});const Py=ry({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ry=ry({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Uy=ry({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ly=ry({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Dy=Object.freeze({__proto__:null,base64:Py,base64pad:Ry,base64url:Uy,base64urlpad:Ly});const My=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),By=My.reduce(((e,t,s)=>(e[s]=t,e)),[]),jy=My.reduce(((e,t,s)=>(e[t.codePointAt(0)]=s,e)),[]);const $y=sy({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=By[t]),"")},decode:function(e){const t=[];for(const s of e){const e=jy[s.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${s}`);t.push(e)}return new Uint8Array(t)}});var Fy=Object.freeze({__proto__:null,base256emoji:$y}),qy=function e(t,s,n){s=s||[];for(var r=n=n||0;t>=zy;)s[n++]=255&t|Wy,t/=128;for(;t&Hy;)s[n++]=255&t|Wy,t>>>=7;return s[n]=0|t,e.bytes=n-r+1,s},Wy=128,Hy=-128,zy=Math.pow(2,31);var Vy=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&Gy)<<i:(n&Gy)*Math.pow(2,i),i+=7}while(n>=Ky);return e.bytes=o-s,r},Ky=128,Gy=127;var Jy=Math.pow(2,7),Yy=Math.pow(2,14),Xy=Math.pow(2,21),Zy=Math.pow(2,28),Qy=Math.pow(2,35),ew=Math.pow(2,42),tw=Math.pow(2,49),sw=Math.pow(2,56),nw=Math.pow(2,63),rw={encode:qy,decode:Vy,encodingLength:function(e){return e<Jy?1:e<Yy?2:e<Xy?3:e<Zy?4:e<Qy?5:e<ew?6:e<tw?7:e<sw?8:e<nw?9:10}},iw=rw;const ow=(e,t,s=0)=>(iw.encode(e,t,s),t),aw=e=>iw.encodingLength(e),cw=(e,t)=>{const s=t.byteLength,n=aw(e),r=n+aw(s),i=new Uint8Array(r+s);return ow(e,i,0),ow(s,i,n),i.set(t,r),new lw(e,s,t,i)};class lw{constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}}const dw=({name:e,code:t,encode:s})=>new hw(e,t,s);class hw{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?cw(this.code,t):t.then((e=>cw(this.code,e)))}throw Error("Unknown type, must be binary type")}}const uw=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),pw=dw({name:"sha2-256",code:18,encode:uw("SHA-256")}),fw=dw({name:"sha2-512",code:19,encode:uw("SHA-512")});Object.freeze({__proto__:null,sha256:pw,sha512:fw});const gw=Ym,mw={code:0,name:"identity",encode:gw,digest:e=>cw(0,gw(e))};Object.freeze({__proto__:null,identity:mw});new TextEncoder,new TextDecoder;const yw={...oy,...cy,...dy,...uy,...gy,...Iy,...Oy,...xy,...Dy,...Fy};function ww(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function bw(e,t,s,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:n}}}const vw=bw("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ew=bw("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?ww(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})),Cw={utf8:vw,"utf-8":vw,hex:yw.base16,latin1:Ew,ascii:Ew,binary:Ew,...yw};var Nw=Object.defineProperty,Aw=(e,t,s)=>((e,t,s)=>t in e?Nw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Iw{constructor(e,t){this.core=e,this.logger=t,Aw(this,"keychain",new Map),Aw(this,"name","keychain"),Aw(this,"version","0.3"),Aw(this,"initialized",!1),Aw(this,"storagePrefix",fg),Aw(this,"init",(async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}})),Aw(this,"has",(e=>(this.isInitialized(),this.keychain.has(e)))),Aw(this,"set",(async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()})),Aw(this,"get",(e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=rc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t})),Aw(this,"del",(async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()})),this.core=e,this.logger=xn(t,this.name)}get context(){return kn(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Oc(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Tc(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=rc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Sw=Object.defineProperty,_w=(e,t,s)=>((e,t,s)=>t in e?Sw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ow{constructor(e,s,n){this.core=e,this.logger=s,_w(this,"name","crypto"),_w(this,"keychain"),_w(this,"randomSessionIdentifier",Kp()),_w(this,"initialized",!1),_w(this,"clientId"),_w(this,"init",(async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)})),_w(this,"hasKeys",(e=>(this.isInitialized(),this.keychain.has(e)))),_w(this,"getClientId",(async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const e=wa(Ea(await this.getClientSeed()).publicKey);return this.clientId=e,e})),_w(this,"generateKeyPair",(()=>{this.isInitialized();const e=function(){const e=ap.utils.randomPrivateKey(),s=ap.getPublicKey(e);return{privateKey:t.toString(e,Dp),publicKey:t.toString(s,Dp)}}();return this.setPrivateKey(e.publicKey,e.privateKey)})),_w(this,"signJWT",(async e=>{this.isInitialized();const t=Ea(await this.getClientSeed()),s=this.randomSessionIdentifier,n=wg;return await Ca(s,e,n,t)})),_w(this,"generateSharedKey",((e,s,n)=>{this.isInitialized();const r=function(e,s){const n=ap.getSharedSecret(t.fromString(e,Dp),t.fromString(s,Dp)),r=zh(Vh,n,void 0,void 0,Vp);return t.toString(r,Dp)}(this.getPrivateKey(e),s);return this.setSymKey(r,n)})),_w(this,"setSymKey",(async(e,t)=>{this.isInitialized();const s=t||Gp(e);return await this.keychain.set(s,e),s})),_w(this,"deleteKeyPair",(async e=>{this.isInitialized(),await this.keychain.del(e)})),_w(this,"deleteSymKey",(async e=>{this.isInitialized(),await this.keychain.del(e)})),_w(this,"encode",(async(e,s,n)=>{this.isInitialized();const r=sf(n),i=t.safeJsonStringify(s);if(rf(r))return function(e,s){const n=Yp(qp),r=Ll(zp),i=ef({type:n,sealed:t.fromString(e,jp),iv:r});return s===Bp?Zp(i):i}(i,n?.encoding);if(nf(r)){const t=r.senderPublicKey,s=r.receiverPublicKey;e=await this.generateSharedKey(t,s)}const o=this.getSymKey(e),{type:a,senderPublicKey:c}=r;return function(e){const s=Yp(typeof e.type<"u"?e.type:$p);if(Xp(s)===Fp&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof e.senderPublicKey<"u"?t.fromString(e.senderPublicKey,Dp):void 0,r=typeof e.iv<"u"?t.fromString(e.iv,Dp):Ll(zp),i=t.fromString(e.symKey,Dp),o=ef({type:s,sealed:$h(i,r).encrypt(t.fromString(e.message,jp)),iv:r,senderPublicKey:n});return e.encoding===Bp?Zp(o):o}({type:a,symKey:o,message:i,senderPublicKey:c,encoding:n?.encoding})})),_w(this,"decode",(async(e,s,n)=>{this.isInitialized();const r=function(e,s){const n=tf({encoded:e,encoding:s?.encoding});return sf({type:Xp(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?t.toString(n.senderPublicKey,Dp):void 0,receiverPublicKey:s?.receiverPublicKey})}(s,n);if(rf(r)){const e=function(e,s){const{sealed:n}=tf({encoded:e,encoding:s});return t.toString(n,jp)}(s,n?.encoding);return t.safeJsonParse(e)}if(nf(r)){const t=r.receiverPublicKey,s=r.senderPublicKey;e=await this.generateSharedKey(t,s)}try{const r=function(e){const s=t.fromString(e.symKey,Dp),{sealed:n,iv:r}=tf({encoded:e.encoded,encoding:e.encoding}),i=$h(s,r).decrypt(n);if(null===i)throw new Error("Failed to decrypt");return t.toString(i,jp)}({symKey:this.getSymKey(e),encoded:s,encoding:n?.encoding});return t.safeJsonParse(r)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}})),_w(this,"getPayloadType",((e,t=Mp)=>Xp(tf({encoded:e,encoding:t}).type))),_w(this,"getPayloadSenderPublicKey",((e,s=Mp)=>{const n=tf({encoded:e,encoding:s});return n.senderPublicKey?t.toString(n.senderPublicKey,Dp):void 0})),this.core=e,this.logger=xn(s,this.name),this.keychain=n||new Iw(this.core,this.logger)}get context(){return kn(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(yg)}catch{e=Kp(),await this.keychain.set(yg,e)}return function(e,t="utf8"){const s=Cw[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}`):ww(globalThis.Buffer.from(e,"utf-8"))}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=rc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Tw=Object.defineProperty,kw=Object.defineProperties,xw=Object.getOwnPropertyDescriptors,Pw=Object.getOwnPropertySymbols,Rw=Object.prototype.hasOwnProperty,Uw=Object.prototype.propertyIsEnumerable,Lw=(e,t,s)=>t in e?Tw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Dw=(e,t,s)=>Lw(e,"symbol"!=typeof t?t+"":t,s);class Mw extends jn{constructor(e,t){super(e,t),this.logger=e,this.core=t,Dw(this,"messages",new Map),Dw(this,"messagesWithoutClientAck",new Map),Dw(this,"name","messages"),Dw(this,"version","0.3"),Dw(this,"initialized",!1),Dw(this,"storagePrefix",fg),Dw(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}}})),Dw(this,"set",(async(e,t,s)=>{this.isInitialized();const n=Jp(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===Ug){const s=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,((e,t)=>kw(e,xw(t)))(((e,t)=>{for(var s in t||(t={}))Rw.call(t,s)&&Lw(e,s,t[s]);if(Pw)for(var s of Pw(t))Uw.call(t,s)&&Lw(e,s,t[s]);return e})({},s),{[n]:t}))}return await this.persist(),n})),Dw(this,"get",(e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t})),Dw(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})),Dw(this,"has",((e,t)=>{this.isInitialized();return typeof this.get(e)[Jp(t)]<"u"})),Dw(this,"ack",(async(e,t)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(e);if(typeof s>"u")return;delete s[Jp(t)],0===Object.keys(s).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,s),await this.persist()})),Dw(this,"del",(async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()})),this.logger=xn(e,this.name),this.core=t}get context(){return kn(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,Oc(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Oc(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Tc(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Tc(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=rc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Bw=Object.defineProperty,jw=Object.defineProperties,$w=Object.getOwnPropertyDescriptors,Fw=Object.getOwnPropertySymbols,qw=Object.prototype.hasOwnProperty,Ww=Object.prototype.propertyIsEnumerable,Hw=(e,t,s)=>t in e?Bw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,zw=(e,t)=>{for(var s in t||(t={}))qw.call(t,s)&&Hw(e,s,t[s]);if(Fw)for(var s of Fw(t))Ww.call(t,s)&&Hw(e,s,t[s]);return e},Vw=(e,t)=>jw(e,$w(t)),Kw=(e,t,s)=>Hw(e,"symbol"!=typeof t?t+"":t,s);class Gw extends $n{constructor(s,n){super(s,n),this.relayer=s,this.logger=n,Kw(this,"events",new e.EventEmitter),Kw(this,"name","publisher"),Kw(this,"queue",new Map),Kw(this,"publishTimeout",t.cjs.toMiliseconds(t.cjs.ONE_MINUTE)),Kw(this,"initialPublishTimeout",t.cjs.toMiliseconds(15*t.cjs.ONE_SECOND)),Kw(this,"needsTransportRestart",!1),Kw(this,"publish",(async(e,s,n)=>{var r,i,o,a,c;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:s,opts:n}});const l=n?.ttl||bg,d=n?.prompt||!1,h=n?.tag||0,u=n?.id||t.getBigIntRpcId().toString(),p=cf(af().protocol),f={id:u,method:n?.publishMethod||p.publish,params:zw({topic:e,message:s,ttl:l,prompt:d,tag:h,attestation:n?.attestation},n?.tvf)},g=`Failed to publish payload, please try again. id:${u} tag:${h}`;try{jf(null==(r=f.params)?void 0:r.prompt)&&(null==(i=f.params)||delete i.prompt),jf(null==(o=f.params)?void 0:o.tag)&&(null==(a=f.params)||delete a.tag);const t=new Promise((async e=>{const t=({id:s})=>{var n;(null==(n=f.id)?void 0:n.toString())===s.toString()&&(this.removeRequestFromQueue(s),this.relayer.events.removeListener(_g,t),e())};this.relayer.events.on(_g,t);const s=xc(new Promise(((e,t)=>{this.rpcPublish(f,n).then(e).catch((e=>{this.logger.warn(e,e?.message),t(e)}))})),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${h}`);try{await s,this.events.removeListener(_g,t)}catch(e){this.queue.set(u,{request:f,opts:n,attempt:1}),this.logger.warn(e,e?.message)}}));this.logger.trace({type:"method",method:"publish",params:{id:u,topic:e,message:s,opts:n}}),await xc(t,this.publishTimeout,g)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),null!=(c=n?.internal)&&c.throwOnFailedPublish)throw e}finally{this.queue.delete(u)}})),Kw(this,"publishCustom",(async e=>{var s,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=t.cjs.FIVE_MINUTES}=c,g=c.id||t.getBigIntRpcId().toString(),m=cf(af().protocol),y=h||m.publish,w={id:g,method:y,params:zw(Vw(zw({},a),{ttl:f,prompt:u,tag:p,attestation:l}),d)},b=`Failed to publish custom payload, please try again. id:${g} tag:${p}`;try{jf(null==(s=w.params)?void 0:s.prompt)&&(null==(n=w.params)||delete n.prompt),jf(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(_g,t),e())};this.relayer.events.on(_g,t);const s=xc(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(_g,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 xc(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)}})),Kw(this,"on",((e,t)=>{this.events.on(e,t)})),Kw(this,"once",((e,t)=>{this.events.once(e,t)})),Kw(this,"off",((e,t)=>{this.events.off(e,t)})),Kw(this,"removeListener",((e,t)=>{this.events.removeListener(e,t)})),this.relayer=s,this.logger=xn(n,this.name),this.registerEventListeners()}get context(){return kn(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(_g,zw(zw({},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,Vw(zw({},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(ys,(()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(Sg);this.checkQueue()})),this.relayer.on(Cg,(e=>{this.removeRequestFromQueue(e.id.toString())}))}}var Jw=Object.defineProperty,Yw=(e,t,s)=>((e,t,s)=>t in e?Jw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Xw{constructor(){Yw(this,"map",new Map),Yw(this,"set",((e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])})),Yw(this,"get",(e=>this.map.get(e)||[])),Yw(this,"exists",((e,t)=>this.get(e).includes(t))),Yw(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)})),Yw(this,"clear",(()=>{this.map.clear()}))}get topics(){return Array.from(this.map.keys())}}var Zw=Object.defineProperty,Qw=Object.defineProperties,eb=Object.getOwnPropertyDescriptors,tb=Object.getOwnPropertySymbols,sb=Object.prototype.hasOwnProperty,nb=Object.prototype.propertyIsEnumerable,rb=(e,t,s)=>t in e?Zw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ib=(e,t)=>{for(var s in t||(t={}))sb.call(t,s)&&rb(e,s,t[s]);if(tb)for(var s of tb(t))nb.call(t,s)&&rb(e,s,t[s]);return e},ob=(e,t)=>Qw(e,eb(t)),ab=(e,t,s)=>rb(e,"symbol"!=typeof t?t+"":t,s);class cb extends Wn{constructor(s,n){super(s,n),this.relayer=s,this.logger=n,ab(this,"subscriptions",new Map),ab(this,"topicMap",new Xw),ab(this,"events",new e.EventEmitter),ab(this,"name","subscription"),ab(this,"version","0.3"),ab(this,"pending",new Map),ab(this,"cached",[]),ab(this,"initialized",!1),ab(this,"storagePrefix",fg),ab(this,"subscribeTimeout",t.cjs.toMiliseconds(t.cjs.ONE_MINUTE)),ab(this,"initialSubscribeTimeout",t.cjs.toMiliseconds(15*t.cjs.ONE_SECOND)),ab(this,"clientId"),ab(this,"batchSubscribeTopicsLimit",500),ab(this,"init",(async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0})),ab(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=af(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}})),ab(this,"unsubscribe",(async(e,t)=>{this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)})),ab(this,"isSubscribed",(e=>new Promise((t=>{t(this.topicMap.topics.includes(e))})))),ab(this,"isKnownTopic",(e=>new Promise((t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some((t=>t.topic===e)))})))),ab(this,"on",((e,t)=>{this.events.on(e,t)})),ab(this,"once",((e,t)=>{this.events.once(e,t)})),ab(this,"off",((e,t)=>{this.events.off(e,t)})),ab(this,"removeListener",((e,t)=>{this.events.removeListener(e,t)})),ab(this,"start",(async()=>{await this.onConnect()})),ab(this,"stop",(async()=>{await this.onDisconnect()})),ab(this,"restart",(async()=>{await this.restore(),await this.onRestart()})),ab(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)})),ab(this,"registerEventListeners",(()=>{this.relayer.core.heartbeat.on(ys,(async()=>{await this.checkPending()})),this.events.on(Mg,(async e=>{const t=Mg;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(Bg,(async e=>{const t=Bg;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))})),this.relayer=s,this.logger=xn(n,this.name),this.clientId=""}get context(){return kn(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=af(s);await this.restartToComplete({topic:e,id:t,relay:n}),await this.rpcUnsubscribe(e,t,n);const r=ic("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,s,n){var r,i;const o=await this.getSubscriptionId(e);if(null!=(r=n?.internal)&&r.skipSubscribe)return o;(!n||n?.transportType===Rg.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const a={method:cf(s.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===Rg.link_mode)return setTimeout((()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch((e=>this.logger.warn(e)))}),t.cjs.toMiliseconds(t.cjs.ONE_SECOND)),o;const s=new Promise((async t=>{const s=n=>{n.topic===e&&(this.events.removeListener(Mg,s),t(n.id))};this.events.on(Mg,s);try{const n=await xc(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(Mg,s),t(n)}catch{}})),r=await xc(s,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(Sg),c)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const t={method:cf(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 xc(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(Sg),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const t={method:cf(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 xc(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(Sg)}return s}rpcUnsubscribe(e,t,s){const n={method:cf(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,ob(ib({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,ib({},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,ib({},t)),this.topicMap.set(t.topic,e),this.events.emit(Mg,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}=rc("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(Bg,ob(ib({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(jg)}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($g)}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}=rc("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=>ob(ib({},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 s=await this.rpcBatchFetchMessages(e);s&&s.messages&&(await function(e){return new Promise((t=>setTimeout(t,e)))}(t.cjs.toMiliseconds(t.cjs.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(s.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=rc("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 Jp(e+await this.getClientId())}}var lb=Object.defineProperty,db=Object.getOwnPropertySymbols,hb=Object.prototype.hasOwnProperty,ub=Object.prototype.propertyIsEnumerable,pb=(e,t,s)=>t in e?lb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,fb=(e,t)=>{for(var s in t||(t={}))hb.call(t,s)&&pb(e,s,t[s]);if(db)for(var s of db(t))ub.call(t,s)&&pb(e,s,t[s]);return e},gb=(e,t,s)=>pb(e,"symbol"!=typeof t?t+"":t,s);class mb extends Fn{constructor(s){var n;super(s),gb(this,"protocol","wc"),gb(this,"version",2),gb(this,"core"),gb(this,"logger"),gb(this,"events",new e.EventEmitter),gb(this,"provider"),gb(this,"messages"),gb(this,"subscriber"),gb(this,"publisher"),gb(this,"name","relayer"),gb(this,"transportExplicitlyClosed",!1),gb(this,"initialized",!1),gb(this,"connectionAttemptInProgress",!1),gb(this,"relayUrl"),gb(this,"projectId"),gb(this,"packageName"),gb(this,"bundleId"),gb(this,"hasExperiencedNetworkDisruption",!1),gb(this,"pingTimeout"),gb(this,"heartBeatTimeout",t.cjs.toMiliseconds(t.cjs.THIRTY_SECONDS+t.cjs.FIVE_SECONDS)),gb(this,"reconnectTimeout"),gb(this,"connectPromise"),gb(this,"reconnectInProgress",!1),gb(this,"requestsInFlight",[]),gb(this,"connectTimeout",t.cjs.toMiliseconds(15*t.cjs.ONE_SECOND)),gb(this,"stalledRestartInProgress",!1),gb(this,"stalledRestartTimeout"),gb(this,"stalledRestartBackoff",0),gb(this,"stalledRestartBaseInterval",t.cjs.toMiliseconds(2*t.cjs.ONE_SECOND)),gb(this,"stalledRestartMaxInterval",t.cjs.toMiliseconds(t.cjs.THIRTY_SECONDS)),gb(this,"request",(async e=>{var s,n;this.logger.debug("Publishing Request Payload");const r=e.id||t.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:r,method:e.method,topic:null==(s=e.params)?void 0:s.topic},"relayer.request - publishing...");const t=`${r}:${(null==(n=e.params)?void 0:n.tag)||""}`;this.requestsInFlight.push(t);const i=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter((e=>e!==t)),i}catch(e){throw this.logger.debug(`Failed to Publish Request: ${r}`),e}})),gb(this,"resetPingTimeout",(()=>{wc()&&(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))})),gb(this,"onPayloadHandler",(e=>{this.onProviderPayload(e),this.resetPingTimeout()})),gb(this,"onConnectHandler",(()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Ng)})),gb(this,"onDisconnectHandler",(()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()})),gb(this,"onProviderErrorHandler",(e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(Ig,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)))})),gb(this,"registerProviderListeners",(()=>{this.provider.on(Og,this.onPayloadHandler),this.provider.on(Tg,this.onConnectHandler),this.provider.on(kg,this.onDisconnectHandler),this.provider.on(xg,this.onProviderErrorHandler)})),this.core=s.core,this.logger=cg({logger:null!=(n=s.logger)?n:"error",name:this.name}),this.messages=new Mw(this.logger,s.core),this.subscriber=new cb(this,this.logger),this.publisher=new Gw(this,this.logger),this.projectId=s?.projectId,this.relayUrl=s?.relayUrl||vg,bc()&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"&&"android"===(null==global?void 0:global.Platform.OS)?this.packageName=Cc():bc()&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"&&"ios"===(null==global?void 0:global.Platform.OS)&&(this.bundleId=Cc()),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 kn(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:Rg.relay},Lg)}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(Mg,c),o())};return await Promise.all([new Promise((e=>{o=e,this.subscriber.on(Mg,c)})),new Promise((async(s,n)=>{a=await this.subscriber.subscribe(e,fb({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 xc(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 tg())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,s){const{topic:n}=e;if(!s.sessionExists){const e={topic:n,expiry:Uc(t.cjs.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,e)}this.events.emit(Eg,e),await this.recordMessageEvent(e,Ug)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise((async(e,t)=>{const s=()=>{t(new Error("Connection interrupted while trying to connect"))};this.provider.once(kg,s),await xc(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(kg,s),clearTimeout(this.reconnectTimeout)})),await new Promise((async(e,s)=>{const n=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(kg,n),await this.subscriber.start().then(e).catch(s).finally((()=>{this.provider.off(kg,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: ${s}`);break}await new Promise((e=>setTimeout(e,t.cjs.toMiliseconds(1*s)))),s++}}startPingTimeout(){var e,t,s,n,r;if(wc())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 lg(new ug(Sc({sdkVersion:Pg,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.isJsonRpcRequest(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:Rg.relay,attestation:i};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(fb({type:"event",event:t.id},o)),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else t.isJsonRpcResponse(e)&&this.events.emit(Cg,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Ug),this.events.emit(Eg,e))}async acknowledgePayload(e){const s=t.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Og,this.onPayloadHandler),this.provider.off(Tg,this.onConnectHandler),this.provider.off(kg,this.onDisconnectHandler),this.provider.off(xg,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await tg();sg((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(ys,(async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&function(){var e;return!vc()||!t.getDocument_1()||"visible"===(null==(e=t.getDocument_1())?void 0:e.visibilityState)}())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}})),this.events.on(Sg,(()=>{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(Ag),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}),t.cjs.toMiliseconds(.1)))))}isInitialized(){if(!this.initialized){const{message:e}=rc("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 yb(e){return Object.getOwnPropertySymbols(e).filter((t=>Object.prototype.propertyIsEnumerable.call(e,t)))}function wb(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const bb="[object RegExp]",vb="[object String]",Eb="[object Number]",Cb="[object Boolean]",Nb="[object Arguments]",Ab="[object Symbol]",Ib="[object Date]",Sb="[object Map]",_b="[object Set]",Ob="[object Array]",Tb="[object Function]",kb="[object ArrayBuffer]",xb="[object Object]",Pb="[object Error]",Rb="[object DataView]",Ub="[object Uint8Array]",Lb="[object Uint8ClampedArray]",Db="[object Uint16Array]",Mb="[object Uint32Array]",Bb="[object BigUint64Array]",jb="[object Int8Array]",$b="[object Int16Array]",Fb="[object Int32Array]",qb="[object BigInt64Array]",Wb="[object Float32Array]",Hb="[object Float64Array]";function zb(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 Vb(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 Kb(e,t,i,o)}return Kb(e,t,i,o)}function Kb(e,t,s,n){if(Object.is(e,t))return!0;let r=wb(e),i=wb(t);if(r===Nb&&(r=xb),i===Nb&&(i=xb),r!==i)return!1;switch(r){case vb:return e.toString()===t.toString();case Eb:return function(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}(e.valueOf(),t.valueOf());case Cb:case Ib:case Ab:return Object.is(e.valueOf(),t.valueOf());case bb:return e.source===t.source&&e.flags===t.flags;case Tb: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 Sb:if(e.size!==t.size)return!1;for(const[r,i]of e.entries())if(!t.has(r)||!Vb(i,t.get(r),r,e,t,s,n))return!1;return!0;case _b:{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=>Vb(a,r,void 0,e,t,s,n)));if(-1===c)return!1;i.splice(c,1)}return!0}case Ob:case Ub:case Lb:case Db:case Mb:case Bb:case jb:case $b:case Fb:case qb:case Wb:case Hb: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(!Vb(e[r],t[r],r,e,t,s,n))return!1;return!0;case kb:return e.byteLength===t.byteLength&&Kb(new Uint8Array(e),new Uint8Array(t),s,n);case Rb:return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&Kb(new Uint8Array(e),new Uint8Array(t),s,n);case Pb:return e.name===t.name&&e.message===t.message;case xb:{if(!(Kb(e.constructor,t.constructor,s,n)||zb(e)&&zb(t)))return!1;const r=[...Object.keys(e),...yb(e)],i=[...Object.keys(t),...yb(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(!Vb(a,t[o],o,e,t,s,n))return!1}return!0}default:return!1}}finally{s.delete(e),s.delete(t)}}function Gb(){}function Jb(e,t){return function(e,t,s){return Vb(e,t,void 0,void 0,void 0,void 0,s)}(e,t,Gb)}var Yb=Object.defineProperty,Xb=Object.getOwnPropertySymbols,Zb=Object.prototype.hasOwnProperty,Qb=Object.prototype.propertyIsEnumerable,ev=(e,t,s)=>t in e?Yb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,tv=(e,t)=>{for(var s in t||(t={}))Zb.call(t,s)&&ev(e,s,t[s]);if(Xb)for(var s of Xb(t))Qb.call(t,s)&&ev(e,s,t[s]);return e},sv=(e,t,s)=>ev(e,"symbol"!=typeof t?t+"":t,s);class nv extends qn{constructor(e,t,s,n=fg,r=void 0){super(e,t,s,n),this.core=e,this.logger=t,this.name=s,sv(this,"map",new Map),sv(this,"version","0.3"),sv(this,"cached",[]),sv(this,"initialized",!1),sv(this,"getKey"),sv(this,"storagePrefix",fg),sv(this,"recentlyDeleted",[]),sv(this,"recentlyDeletedLimit",200),sv(this,"init",(async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!jf(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)})),sv(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())})),sv(this,"get",(e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)))),sv(this,"getAll",(e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((s=>Jb(t[s],e[s]))))):this.values))),sv(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=tv(tv({},this.getData(e)),t);this.map.set(e,s),await this.persist()})),sv(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=xn(t,this.name),this.storagePrefix=n,this.getKey=r}get context(){return kn(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}=rc("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=rc("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}=rc("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}=rc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var rv=Object.defineProperty,iv=(e,t,s)=>((e,t,s)=>t in e?rv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ov{constructor(e,s){this.core=e,this.logger=s,iv(this,"name","pairing"),iv(this,"version","0.3"),iv(this,"events",new i.default),iv(this,"pairings"),iv(this,"initialized",!1),iv(this,"storagePrefix",fg),iv(this,"ignoredPayloadTypes",[Fp]),iv(this,"registeredMethods",[]),iv(this,"init",(async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))})),iv(this,"register",(({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]})),iv(this,"create",(async e=>{this.isInitialized();const s=Kp(),n=await this.core.crypto.setSymKey(s),r=Uc(t.cjs.FIVE_MINUTES),i={protocol:"irn"},o={topic:n,expiry:r,relay:i,active:!1,methods:e?.methods},a=vf({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:i,expiryTimestamp:r,methods:e?.methods});return this.events.emit(qg,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}})),iv(this,"pair",(async e=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[rm]}});this.isValidPair(e,s);const{topic:n,symKey:r,relay:i,expiryTimestamp:o,methods:a}=wf(e.uri);let c;if(s.props.properties.topic=n,s.addTrace(im),s.addTrace(om),this.pairings.keys.includes(n)){if(c=this.pairings.get(n),s.addTrace(dm),c.active)throw s.setError(mm),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(hm)}const l=o||Uc(t.cjs.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),s.addTrace(am),e.activatePairing&&await this.activate({topic:n}),this.events.emit(qg,d),s.addTrace(um),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(r,n),s.addTrace(cm);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(fm)}try{await this.core.relayer.subscribe(n,{relay:i})}catch(e){throw s.setError(ym),e}return s.addTrace(lm),d})),iv(this,"activate",(async({topic:e})=>{this.isInitialized();const s=Uc(t.cjs.FIVE_MINUTES);this.core.expirer.set(e,s),await this.pairings.update(e,{active:!0,expiry:s})})),iv(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}=kc();this.events.once(Dc("pairing_ping",e),(({error:e})=>{e?r(e):n()})),await s()}})),iv(this,"updateExpiry",(async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})})),iv(this,"updateMetadata",(async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})})),iv(this,"getPairings",(()=>(this.isInitialized(),this.pairings.values))),iv(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",ic("USER_DISCONNECTED")),await this.deletePairing(t))})),iv(this,"formatUriFromPairing",(e=>{this.isInitialized();const{topic:t,relay:s,expiry:n,methods:r}=e,i=this.core.crypto.keychain.get(t);return vf({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:i,relay:s,expiryTimestamp:n,methods:r})})),iv(this,"sendRequest",(async(e,s,n)=>{const r=t.formatJsonRpcRequest(s,n),i=await this.core.crypto.encode(e,r),o=Fg[s].req;return this.core.history.set(e,r),this.core.relayer.publish(e,i,o),r.id})),iv(this,"sendResult",(async(e,s,n)=>{const r=t.formatJsonRpcResult(e,n),i=await this.core.crypto.encode(s,r),o=(await this.core.history.get(s,e)).request.method,a=Fg[o].res;await this.core.relayer.publish(s,i,a),await this.core.history.resolve(r)})),iv(this,"sendError",(async(e,s,n)=>{const r=t.formatJsonRpcError(e,n),i=await this.core.crypto.encode(s,r),o=(await this.core.history.get(s,e)).request.method,a=Fg[o]?Fg[o].res:Fg.unregistered_method.res;await this.core.relayer.publish(s,i,a),await this.core.history.resolve(r)})),iv(this,"deletePairing",(async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,ic("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])})),iv(this,"cleanup",(async()=>{const e=this.pairings.getAll().filter((e=>Lc(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))})),iv(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)}})),iv(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)})),iv(this,"onPairingPingRequest",(async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.events.emit(zg,{id:s,topic:e})}catch(t){await this.sendError(s,e,t),this.logger.error(t)}})),iv(this,"onPairingPingResponse",((e,s)=>{const{id:n}=s;setTimeout((()=>{t.isJsonRpcResult(s)?this.events.emit(Dc("pairing_ping",n),{}):t.isJsonRpcError(s)&&this.events.emit(Dc("pairing_ping",n),{error:s.error})}),500)})),iv(this,"onPairingDeleteRequest",(async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(Hg,{id:s,topic:e})}catch(t){await this.sendError(s,e,t),this.logger.error(t)}})),iv(this,"onUnknownRpcMethodRequest",(async(e,t)=>{const{id:s,method:n}=t;try{if(this.registeredMethods.includes(n))return;const t=ic("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)}})),iv(this,"onUnknownRpcMethodResponse",(e=>{this.registeredMethods.includes(e)||this.logger.error(ic("WC_METHOD_UNSUPPORTED",e))})),iv(this,"isValidPair",((e,s)=>{var n;if(!Jf(e)){const{message:t}=rc("MISSING_OR_INVALID",`pair() params: ${e}`);throw s.setError(gm),new Error(t)}if(!function(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if($f(e,!1))return!!t(e)||t(qc(e))}catch{}return!1}(e.uri)){const{message:t}=rc("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw s.setError(gm),new Error(t)}const r=wf(e?.uri);if(null==(n=r?.relay)||!n.protocol){const{message:e}=rc("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(gm),new Error(e)}if(null==r||!r.symKey){const{message:e}=rc("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(gm),new Error(e)}if(null!=r&&r.expiryTimestamp&&t.cjs.toMiliseconds(r?.expiryTimestamp)<Date.now()){s.setError(wm);const{message:e}=rc("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}})),iv(this,"isValidPing",(async e=>{if(!Jf(e)){const{message:t}=rc("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)})),iv(this,"isValidDisconnect",(async e=>{if(!Jf(e)){const{message:t}=rc("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)})),iv(this,"isValidPairingTopic",(async e=>{if(!$f(e,!1)){const{message:t}=rc("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=rc("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Lc(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=rc("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}})),this.core=e,this.logger=xn(s,this.name),this.pairings=new nv(this.core,this.logger,this.name,this.storagePrefix)}get context(){return kn(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=rc("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Eg,(async e=>{const{topic:s,message:n,transportType:r}=e;if(this.pairings.keys.includes(s)&&r!==Rg.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const e=await this.core.crypto.decode(s,n);t.isJsonRpcRequest(e)?(this.core.history.set(s,e),await this.onRelayEventRequest({topic:s,payload:e})):t.isJsonRpcResponse(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:s,payload:e}),this.core.history.delete(s,e.id)),await this.core.relayer.messages.ack(s,n)}catch(e){this.logger.error(e)}}))}registerExpirerEvents(){this.core.expirer.on(Zg,(async e=>{const{topic:t}=Rc(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Wg,{topic:t}))}))}}var av=Object.defineProperty,cv=(e,t,s)=>((e,t,s)=>t in e?av(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class lv extends Bn{constructor(s,n){super(s,n),this.core=s,this.logger=n,cv(this,"records",new Map),cv(this,"events",new e.EventEmitter),cv(this,"name","history"),cv(this,"version","0.3"),cv(this,"cached",[]),cv(this,"initialized",!1),cv(this,"storagePrefix",fg),cv(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)})),cv(this,"set",((e,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:s,chainId:n}),this.records.has(s.id))return;const r={id:s.id,topic:e,request:{method:s.method,params:s.params||null},chainId:n,expiry:Uc(t.cjs.THIRTY_DAYS)};this.records.set(r.id,r),this.persist(),this.events.emit(Vg,r)})),cv(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 s=await this.getRecord(e.id);typeof s.response>"u"&&(s.response=t.isJsonRpcError(e)?{error:e.error}:{result:e.result},this.records.set(s.id,s),this.persist(),this.events.emit(Kg,s))})),cv(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)))),cv(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(Gg,s)}})),this.persist()})),cv(this,"exists",(async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e))),cv(this,"on",((e,t)=>{this.events.on(e,t)})),cv(this,"once",((e,t)=>{this.events.once(e,t)})),cv(this,"off",((e,t)=>{this.events.off(e,t)})),cv(this,"removeListener",((e,t)=>{this.events.removeListener(e,t)})),this.logger=xn(n,this.name)}get context(){return kn(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((s=>{if(typeof s.response<"u")return;const n={topic:s.topic,request:t.formatJsonRpcRequest(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(n)})),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}=rc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Jg)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=rc("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(Vg,(e=>{const t=Vg;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(Kg,(e=>{const t=Kg;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(Gg,(e=>{const t=Gg;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.core.heartbeat.on(ys,(()=>{this.cleanup()}))}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach((s=>{t.cjs.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Gg,s,!1),e=!0)})),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=rc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var dv=Object.defineProperty,hv=(e,t,s)=>((e,t,s)=>t in e?dv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class uv extends Hn{constructor(t,s){super(t,s),this.core=t,this.logger=s,hv(this,"expirations",new Map),hv(this,"events",new e.EventEmitter),hv(this,"name","expirer"),hv(this,"version","0.3"),hv(this,"cached",[]),hv(this,"initialized",!1),hv(this,"storagePrefix",fg),hv(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)})),hv(this,"has",(e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}})),hv(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(Yg,{target:s,expiration:n})})),hv(this,"get",(e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)})),hv(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(Xg,{target:t,expiration:s})}})),hv(this,"on",((e,t)=>{this.events.on(e,t)})),hv(this,"once",((e,t)=>{this.events.once(e,t)})),hv(this,"off",((e,t)=>{this.events.off(e,t)})),hv(this,"removeListener",((e,t)=>{this.events.removeListener(e,t)})),this.logger=xn(s,this.name)}get context(){return kn(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 Pc("topic",e)}(e);if("number"==typeof e)return function(e){return Pc("id",e)}(e);const{message:t}=rc("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(Qg)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=rc("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}=rc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,s){const{expiry:n}=s;t.cjs.toMiliseconds(n)-Date.now()<=0&&this.expire(e,s)}expire(e,t){this.expirations.delete(e),this.events.emit(Zg,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(ys,(()=>this.checkExpirations())),this.events.on(Yg,(e=>{const t=Yg;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Zg,(e=>{const t=Zg;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(Xg,(e=>{const t=Xg;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=rc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var pv=Object.defineProperty,fv=(e,t,s)=>((e,t,s)=>t in e?pv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class gv extends zn{constructor(e,s,n){super(e,s,n),this.core=e,this.logger=s,this.store=n,fv(this,"name","verify-api"),fv(this,"abortController"),fv(this,"isDevEnv"),fv(this,"verifyUrlV3",sm),fv(this,"storagePrefix",fg),fv(this,"version",2),fv(this,"publicKey"),fv(this,"fetchPromise"),fv(this,"init",(async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&t.cjs.toMiliseconds(null==(e=this.publicKey)?void 0:e.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))})),fv(this,"register",(async e=>{if(!vc()||this.isDevEnv)return;const s=window.location.origin,{id:n,decryptedId:r}=e,i=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${n}&decryptedId=${r}`;try{const e=t.getDocument_1(),s=this.startAbortTimer(5*t.cjs.ONE_SECOND),r=await new Promise(((t,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(va(i.attestation).payload.id!==n)return;clearInterval(s),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),t(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""})),fv(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(va(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)})),fv(this,"fetchAttestation",(async(e,s)=>{this.logger.debug(`resolving attestation: ${e} from url: ${s}`);const n=this.startAbortTimer(5*t.cjs.ONE_SECOND),r=await fetch(`${s}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(n),200===r.status?await r.json():void 0})),fv(this,"getVerifyUrl",(e=>{let t=e||tm;return nm.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${tm}`),t=tm),t})),fv(this,"fetchPublicKey",(async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(t.cjs.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await s.json()}catch(e){this.logger.warn(e)}})),fv(this,"persistPublicKey",(async e=>{this.logger.debug(e,"persisting public key to local storage"),await this.store.setItem(this.storeKey,e),this.publicKey=e})),fv(this,"removePublicKey",(async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0})),fv(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")}})),fv(this,"getPublicKey",(async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey())),fv(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})),fv(this,"validateAttestation",((e,s)=>{const n=of(e,s.publicKey),r={hasExpired:t.cjs.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=xn(s,this.name),this.abortController=new AbortController,this.isDevEnv=Fc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return kn(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout((()=>this.abortController.abort()),t.cjs.toMiliseconds(e))}}var mv=Object.defineProperty,yv=(e,t,s)=>((e,t,s)=>t in e?mv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class wv extends Vn{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,yv(this,"context","echo"),yv(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=xn(t,this.context)}}var bv=Object.defineProperty,vv=Object.getOwnPropertySymbols,Ev=Object.prototype.hasOwnProperty,Cv=Object.prototype.propertyIsEnumerable,Nv=(e,t,s)=>t in e?bv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Av=(e,t)=>{for(var s in t||(t={}))Ev.call(t,s)&&Nv(e,s,t[s]);if(vv)for(var s of vv(t))Cv.call(t,s)&&Nv(e,s,t[s]);return e},Iv=(e,t,s)=>Nv(e,"symbol"!=typeof t?t+"":t,s);class Sv extends Kn{constructor(e,s,n=!0){super(e,s,n),this.core=e,this.logger=s,Iv(this,"context","event-client"),Iv(this,"storagePrefix",fg),Iv(this,"storageVersion",.1),Iv(this,"events",new Map),Iv(this,"shouldPersist",!1),Iv(this,"init",(async()=>{if(!Fc())try{const e={eventId:$c(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ic(this.core.relayer.protocol,this.core.relayer.version,Pg)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}})),Iv(this,"createEvent",(e=>{const{event:t="ERROR",type:s="",properties:{topic:n,trace:r}}=e,i=$c(),o=this.core.projectId||"",a=Date.now(),c=Av({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})),Iv(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?Av(Av({},n),this.setMethods(n.eventId)):void 0})),Iv(this,"deleteEvent",(e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0})),Iv(this,"setEventListeners",(()=>{this.core.heartbeat.on(ys,(async()=>{this.shouldPersist&&await this.persist(),this.events.forEach((e=>{t.cjs.fromMiliseconds(Date.now())-t.cjs.fromMiliseconds(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)}))}))})),Iv(this,"setMethods",(e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)}))),Iv(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)})),Iv(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)})),Iv(this,"persist",(async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1})),Iv(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,Av(Av({},e),this.setMethods(e.eventId)))}))}catch(e){this.logger.warn(e)}})),Iv(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)}})),Iv(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-${Pg}${t}`,{method:"POST",body:JSON.stringify(e)})})),Iv(this,"getAppDomain",(()=>Ac().url)),this.logger=xn(s,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 _v=Object.defineProperty,Ov=Object.getOwnPropertySymbols,Tv=Object.prototype.hasOwnProperty,kv=Object.prototype.propertyIsEnumerable,xv=(e,t,s)=>t in e?_v(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Pv=(e,t)=>{for(var s in t||(t={}))Tv.call(t,s)&&xv(e,s,t[s]);if(Ov)for(var s of Ov(t))kv.call(t,s)&&xv(e,s,t[s]);return e},Rv=(e,t,s)=>xv(e,"symbol"!=typeof t?t+"":t,s);class Uv extends Ln{constructor(t){var s;super(t),Rv(this,"protocol","wc"),Rv(this,"version",2),Rv(this,"name",pg),Rv(this,"relayUrl"),Rv(this,"projectId"),Rv(this,"customStoragePrefix"),Rv(this,"events",new e.EventEmitter),Rv(this,"logger"),Rv(this,"heartbeat"),Rv(this,"relayer"),Rv(this,"crypto"),Rv(this,"storage"),Rv(this,"history"),Rv(this,"expirer"),Rv(this,"pairing"),Rv(this,"verify"),Rv(this,"echoClient"),Rv(this,"linkModeSupportedApps"),Rv(this,"eventClient"),Rv(this,"initialized",!1),Rv(this,"logChunkController"),Rv(this,"on",((e,t)=>this.events.on(e,t))),Rv(this,"once",((e,t)=>this.events.once(e,t))),Rv(this,"off",((e,t)=>this.events.off(e,t))),Rv(this,"removeListener",((e,t)=>this.events.removeListener(e,t))),Rv(this,"dispatchEnvelope",(({topic:e,message:t,sessionExists:s})=>{if(!e||!t)return;const n={topic:e,message:t,publishedAt:Date.now(),transportType:Rg.link_mode};this.relayer.onLinkMessageEvent(n,{sessionExists:s})}));const n=this.getGlobalCore(t?.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=t?.projectId,this.relayUrl=t?.relayUrl||vg,this.customStoragePrefix=null!=t&&t.customStoragePrefix?`:${t.customStoragePrefix}`:"";const r=function(e){return Tn(On({},e),{level:e?.level||nn})}({level:"string"==typeof t?.logger&&t.logger?t.logger:gg,name:pg}),{logger:i,chunkLoggerController:o}=Pn({opts:r,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.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=xn(i,this.name),this.heartbeat=new ws,this.crypto=new Ow(this,this.logger,t?.keychain),this.history=new lv(this,this.logger),this.expirer=new uv(this,this.logger),this.storage=null!=t&&t.storage?t.storage:new Us(Pv(Pv({},mg),t?.storageOptions)),this.relayer=new mb({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new ov(this,this.logger),this.verify=new gv(this,this.logger,this.storage),this.echoClient=new wv(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Sv(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Uv(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem("WALLETCONNECT_CLIENT_ID",s),t}get context(){return kn(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(Dg,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(Dg)||[],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 Lv=Uv,Dv="client",Mv=`wc@2:${Dv}:`,Bv=Dv,jv="error",$v="WALLETCONNECT_DEEPLINK_CHOICE",Fv="Proposal expired",qv=t.cjs.SEVEN_DAYS,Wv={wc_sessionPropose:{req:{ttl:t.cjs.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:t.cjs.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:t.cjs.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:t.cjs.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:t.cjs.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:t.cjs.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1104},res:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1106},res:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:3*t.cjs.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:3*t.cjs.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:t.cjs.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:t.cjs.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1112},res:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1114},res:{ttl:t.cjs.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:t.cjs.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:t.cjs.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:t.cjs.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:t.cjs.FIVE_MINUTES,prompt:!1,tag:1119}}},Hv={min:t.cjs.FIVE_MINUTES,max:t.cjs.SEVEN_DAYS},zv="IDLE",Vv="ACTIVE",Kv={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:""}},Gv=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Jv="wc@1.5:auth:",Yv=`${Jv}:PUB_KEY`;var Xv=Object.defineProperty,Zv=Object.defineProperties,Qv=Object.getOwnPropertyDescriptors,eE=Object.getOwnPropertySymbols,tE=Object.prototype.hasOwnProperty,sE=Object.prototype.propertyIsEnumerable,nE=(e,t,s)=>t in e?Xv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,rE=(e,t)=>{for(var s in t||(t={}))tE.call(t,s)&&nE(e,s,t[s]);if(eE)for(var s of eE(t))sE.call(t,s)&&nE(e,s,t[s]);return e},iE=(e,t)=>Zv(e,Qv(t)),oE=(e,t,s)=>nE(e,"symbol"!=typeof t?t+"":t,s);class aE extends Xn{constructor(e){super(e),oE(this,"name","engine"),oE(this,"events",new i.default),oE(this,"initialized",!1),oE(this,"requestQueue",{state:zv,queue:[]}),oE(this,"sessionRequestQueue",{state:zv,queue:[]}),oE(this,"emittedSessionRequests",new Wc({limit:500})),oE(this,"requestQueueDelay",t.cjs.ONE_SECOND),oE(this,"expectedPairingMethodMap",new Map),oE(this,"recentlyDeletedMap",new Map),oE(this,"recentlyDeletedLimit",200),oE(this,"relayMessageCache",[]),oE(this,"pendingSessions",new Map),oE(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(Wv)}),this.initialized=!0,setTimeout((async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()}),t.cjs.toMiliseconds(this.requestQueueDelay)))})),oE(this,"connect",(async e=>{var s;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=iE(rE({},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=Lf(e),l=Lf(t),d={},h=Object.keys(c).concat(Object.keys(l));for(const e of h)d[e]={chains:Mc(null==(s=c[e])?void 0:s.chains,null==(n=l[e])?void 0:n.chains),methods:Mc(null==(r=c[e])?void 0:r.methods,null==(i=l[e])?void 0:i.methods),events:Mc(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==(s=d?.[0])?void 0:s.ttl)||Wv.wc_sessionPropose.req.ttl||t.cjs.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}=rc("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(e)}const m=await this.client.core.crypto.generateKeyPair(),y=Uc(u),w=rE(iE(rE(rE({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:t.payloadId()}),(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=Dc("session_connect",w.id),{reject:v,resolve:E,done:C}=kc(u,Fv),N=({id:e})=>{e===w.id&&(this.client.events.off("proposal_expire",N),this.pendingSessions.delete(w.id),this.events.emit(b,{error:{message:Fv,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}})),oE(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}})),oE(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:[vm]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw r.setError(Tm),e}try{await this.isValidProposalId(e?.id)}catch(t){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),r.setError(Rm),t}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(Pm),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:vm,properties:{topic:p,trace:[vm,Em]}}));const w=await this.client.core.crypto.generateKeyPair(),b=f.publicKey,v=await this.client.core.crypto.generateSharedKey(w,b),E=iE(rE(rE(rE({relay:{protocol:o??"irn"},namespaces:a,controller:{publicKey:w,metadata:this.client.metadata},expiry:Uc(qv)},c&&{sessionProperties:c}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),{proposalRequestsResponses:h}),C=Rg.relay;y.addTrace(Cm);try{await this.client.core.relayer.subscribe(v,{transportType:C,internal:{skipSubscribe:!0}})}catch(e){throw y.setError(xm),e}y.addTrace(Nm);const N=iE(rE({},E),{topic:v,requiredNamespaces:g,optionalNamespaces:m,pairingTopic:p,acknowledged:!1,self:E.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:w,transportType:Rg.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(v,N),y.addTrace(Im);try{await this.sendApproveSession({sessionTopic:v,proposal:u,pairingProposalResponse:{relay:{protocol:o??"irn"},responderPublicKey:w},sessionSettleRequest:E,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:rE({correlationId:i},this.getTVFApproveParams(N))}}),y.addTrace(Am)}catch(e){throw this.client.logger.error(e),this.client.session.delete(v,ic("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,Uc(qv)),{topic:v,acknowledged:()=>Promise.resolve(this.client.session.get(v))}})),oE(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:Wv.wc_sessionPropose.reject}),await this.deleteProposal(t)})),oE(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:s,namespaces:n}=e,{done:r,resolve:i,reject:o}=kc(t.cjs.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),a=t.payloadId(),c=t.getBigIntRpcId().toString(),l=this.client.session.get(s).namespaces;return this.events.once(Dc("session_update",a),(({error:e})=>{e?o(e):i()})),await this.client.session.update(s,{namespaces:n}),await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch((e=>{this.client.logger.error(e),this.client.session.update(s,{namespaces:l}),o(e)})),{acknowledged:r}})),oE(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:s}=e,n=t.payloadId(),{done:r,resolve:i,reject:o}=kc(t.cjs.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Dc("session_extend",n),(({error:e})=>{e?o(e):i()})),await this.setExpiry(s,Uc(qv)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch((e=>{o(e)})),{acknowledged:r}})),oE(this,"request",(async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}const{chainId:s,request:n,topic:r,expiry:i=Wv.wc_sessionRequest.req.ttl}=e,o=this.client.session.get(r);o?.transportType===Rg.relay&&await this.confirmOnlineStateOrThrow();const a=t.payloadId(),c=t.getBigIntRpcId().toString(),{done:l,resolve:d,reject:h}=kc(i,"Request expired. Please try again.");this.events.once(Dc("session_request",a),(({error:e,result:t})=>{e?h(e):d(t)}));const u="wc_sessionRequest",p=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);if(p)return await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:r,method:u,params:{request:iE(rE({},n),{expiryTimestamp:Uc(i)}),chainId:s},expiry:i,throwOnFailedPublish:!0,appLink:p}).catch((e=>h(e))),this.client.events.emit("session_request_sent",{topic:r,request:n,chainId:s,id:a}),await l();const f={request:iE(rE({},n),{expiryTimestamp:Uc(i)}),chainId:s};return await Promise.all([new Promise((async e=>{await this.sendRequest({clientRpcId:a,relayRpcId:c,topic:r,method:u,params:f,expiry:i,throwOnFailedPublish:!0,tvf:this.getTVFParams(a,f)}).catch((e=>h(e))),this.client.events.emit("session_request_sent",{topic:r,request:n,chainId:s,id:a}),e()})),new Promise((async e=>{var t;if(null==(t=o.sessionConfig)||!t.disableDeepLink){const e=await async function(e,t){let s="";try{if(vc()&&(s=localStorage.getItem(t),s))return s;s=await e.getItem(t)}catch(e){console.error(e)}return s}(this.client.core.storage,$v);await Bc({id:a,topic:r,wcDeepLink:e})}e()})),l()]).then((e=>e[2]))})),oE(this,"respond",(async e=>{var s,n;this.isInitialized();const r=this.client.core.eventClient.createEvent({properties:{topic:e?.topic||(null==(n=null==(s=e?.response)?void 0:s.id)?void 0:n.toString()),trace:[Sm]}});try{await this.isValidRespond(e)}catch(e){throw r.addTrace(e?.message),r.setError(Um),e}r.addTrace(_m);const{topic:i,response:o}=e,{id:a}=o,c=this.client.session.get(i);c.transportType===Rg.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(c.peer.metadata,c.transportType);try{r.addTrace(Om),t.isJsonRpcResult(o)?await this.sendResult({id:a,topic:i,result:o.result,throwOnFailedPublish:!0,appLink:l}):t.isJsonRpcError(o)&&await this.sendError({id:a,topic:i,error:o.error,appLink:l}),this.cleanupAfterResponse(e)}catch(e){throw r.addTrace(e?.message),r.setError(Lm),e}})),oE(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:s}=e;if(this.client.session.keys.includes(s)){const e=t.payloadId(),n=t.getBigIntRpcId().toString(),{done:r,resolve:i,reject:o}=kc(t.cjs.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Dc("session_ping",e),(({error:e})=>{e?o(e):i()})),await Promise.all([this.sendRequest({topic:s,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:n}),r()])}else this.client.core.pairing.pairings.keys.includes(s)&&(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:s}))})),oE(this,"emit",(async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:s,event:n,chainId:r}=e,i=t.getBigIntRpcId().toString(),o=t.payloadId();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:n,chainId:r},throwOnFailedPublish:!0,relayRpcId:i,clientRpcId:o})})),oE(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:ic("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=rc("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}})),oE(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!!_c(r,n)&&(n.forEach((t=>{const{accounts:n,methods:r,events:o}=e.namespaces[t],a=xf(n),c=s[t];_c(tc(t,c),a)&&_c(c.methods,r)&&_c(c.events,o)||(i=!1)})),i)}(t,e)))))),oE(this,"getPendingSessionRequests",(()=>this.client.pendingRequest.getAll())),oE(this,"authenticate",(async(e,s)=>{var n;this.isInitialized(),this.isValidAuthenticate(e);const r=s&&this.client.core.linkModeSupportedApps.includes(s)&&(null==(n=this.client.metadata.redirect)?void 0:n.linkMode),i=r?Rg.link_mode:Rg.relay;i===Rg.relay&&await this.confirmOnlineStateOrThrow();const{chains:o,statement:a="",uri:c,domain:l,nonce:d,type:h,exp:u,nbf:p,methods:f=[],expiry:g}=e,m=[...e.resources||[]],{topic:y,uri:w}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:i});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:w}});const b=await this.client.core.crypto.generateKeyPair(),v=Gp(b);if(await Promise.all([this.client.auth.authKeys.set(Yv,{responseTopic:v,publicKey:b}),this.client.auth.pairingTopics.set(v,{topic:v,pairingTopic:y})]),await this.client.core.relayer.subscribe(v,{transportType:i}),this.client.logger.info(`sending request to new pairing topic: ${y}`),f.length>0){const{namespace:e}=ec(o[0]);let t=nh(e,"request",f);ah(m)&&(t=rh(t,m.pop())),m.push(t)}const E=g&&g>Wv.wc_sessionAuthenticate.req.ttl?g:Wv.wc_sessionAuthenticate.req.ttl,C={authPayload:{type:h??"caip122",chains:o,statement:a,aud:c,domain:l,version:"1",nonce:d,iat:(new Date).toISOString(),exp:u,nbf:p,resources:m},requester:{publicKey:b,metadata:this.client.metadata},expiryTimestamp:Uc(E)},N={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:o,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:b,metadata:this.client.metadata},expiryTimestamp:Uc(Wv.wc_sessionPropose.req.ttl),id:t.payloadId()},{done:A,resolve:I,reject:S}=kc(E,"Request expired"),_=t.payloadId(),O=Dc("session_connect",N.id),T=Dc("session_request",_),k=async({error:e,session:t})=>{this.events.off(T,x),e?S(e):t&&I({session:t})},x=async e=>{var t,n,r;if(await this.deletePendingAuthRequest(_,{message:"fulfilled",code:0}),e.error){const t=ic("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 Xd({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),S(ic("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:t}=e,s=ah(t.resources),n=[Jd(t.iss)],r=Yd(t.iss);if(s){const e=ih(s),t=oh(s);c.push(...e),n.push(...t)}for(const e of n)l.push(`${e}:${r}`)}const d=await this.client.core.crypto.generateSharedKey(b,a.publicKey);let h;c.length>0&&(h={topic:d,acknowledged:!0,self:{publicKey:b,metadata:this.client.metadata},peer:a,controller:a.publicKey,expiry:Uc(qv),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:Df([...new Set(c)],[...new Set(l)]),transportType:i},await this.client.core.relayer.subscribe(d,{transportType:i}),await this.client.session.set(d,h),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:a.metadata}),h=this.client.session.get(d)),null!=(t=this.client.metadata.redirect)&&t.linkMode&&null!=(n=a.metadata.redirect)&&n.linkMode&&null!=(r=a.metadata.redirect)&&r.universal&&s&&(this.client.core.addLinkModeSupportedApp(a.metadata.redirect.universal),this.client.session.update(d,{transportType:Rg.link_mode})),I({auths:o,session:h})};let P;this.events.once(O,k),this.events.once(T,x);try{if(r){const e=t.formatJsonRpcRequest("wc_sessionAuthenticate",C,_);this.client.core.history.set(y,e);const n=await this.client.core.crypto.encode("",e,{type:qp,encoding:Bp});P=Ef(s,y,n)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:C,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:_}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:N,expiry:Wv.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:N.id})])}catch(e){throw this.events.off(O,k),this.events.off(T,x),e}return await this.setProposal(N.id,N),await this.setAuthRequest(_,{request:iE(rE({},C),{verifyContext:{}}),pairingTopic:y,transportType:i}),{uri:P??w,response:A}})),oE(this,"approveSessionAuthenticate",(async e=>{const{id:t,auths:s}=e,n=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[Dm]}});try{this.isInitialized()}catch(e){throw n.setError(Wm),e}const r=this.getPendingAuthRequest(t);if(!r)throw n.setError(Km),new Error(`Could not find pending auth request with id ${t}`);const i=r.transportType||Rg.relay;i===Rg.relay&&await this.confirmOnlineStateOrThrow();const o=r.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Gp(o),l={type:Fp,receiverPublicKey:o,senderPublicKey:a},d=[],h=[];for(const e of s){if(!await Xd({cacao:e,projectId:this.client.core.projectId})){n.setError(Hm);const e=ic("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:c,error:e,encodeOpts:l}),new Error(e.message)}n.addTrace(Bm);const{p:s}=e,r=ah(s.resources),i=[Jd(s.iss)],o=Yd(s.iss);if(r){const e=ih(r),t=oh(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(Mm),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:Uc(qv),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:Df([...new Set(d)],[...new Set(h)]),transportType:i},n.addTrace($m);try{await this.client.core.relayer.subscribe(u,{transportType:i})}catch(e){throw n.setError(zm),e}n.addTrace(Fm),await this.client.session.set(u,p),n.addTrace(jm),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}n.addTrace(qm);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(Vm),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}})),oE(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===Rg.relay&&await this.confirmOnlineStateOrThrow();const r=n.requester.publicKey,i=await this.client.core.crypto.generateKeyPair(),o=Gp(r),a={type:Fp,receiverPublicKey:r,senderPublicKey:i};await this.sendError({id:t,topic:o,error:s,encodeOpts:a,rpcOpts:Wv.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)})),oE(this,"formatAuthMessage",(e=>{this.isInitialized();const{request:t,iss:s}=e;return Zd(t,s)})),oE(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)})),oE(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)}})),oE(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,ic("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($v).catch((e=>this.client.logger.warn(e))),s===(null==(t=this.sessionRequestQueue.queue[0])?void 0:t.topic)&&(this.sessionRequestQueue.state=zv),await Promise.all(this.getPendingSessionRequests().filter((e=>e.topic===s)).map((e=>this.deletePendingSessionRequest(e.id,ic("USER_DISCONNECTED"))))),r&&this.client.events.emit("session_delete",{id:i,topic:s})})),oE(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(km)}catch{}await Promise.all([this.client.proposal.delete(e,ic("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")})),oE(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=zv,this.client.events.emit("session_request_expire",{id:e}))})),oE(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)])})),oE(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}))})),oE(this,"setProposal",(async(e,t)=>{this.client.core.expirer.set(e,Uc(Wv.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)})),oE(this,"setAuthRequest",(async(e,t)=>{const{request:s,pairingTopic:n,transportType:r=Rg.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})})),oE(this,"setPendingSessionRequest",(async e=>{const{id:t,topic:s,params:n,verifyContext:r}=e,i=n.request.expiryTimestamp||Uc(Wv.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})})),oE(this,"sendRequest",(async e=>{const{topic:s,method:n,params:r,expiry:i,relayRpcId:o,clientRpcId:a,throwOnFailedPublish:c,appLink:l,tvf:d,publishOpts:h={}}=e,u=t.formatJsonRpcRequest(n,r,a);let p;const f=!!l;try{const e=f?Bp:Mp;p=await this.client.core.crypto.encode(s,u,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),e}let g;if(Gv.includes(n)){const e=Jp(JSON.stringify(u)),t=Jp(p);g=await this.client.core.verify.register({id:t,decryptedId:e})}const m=rE(rE({},Wv[n].req),h);if(m.attestation=g,i&&(m.ttl=i),o&&(m.id=o),this.client.core.history.set(s,u),f){const e=Ef(l,s,p);await global.Linking.openURL(e,this.client.name)}else m.tvf=iE(rE({},d),{correlationId:u.id}),c?(m.internal=iE(rE({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,p,m)):this.client.core.relayer.publish(s,p,m).catch((e=>this.client.logger.error(e)));return u.id})),oE(this,"sendProposeSession",(async e=>{const{proposal:s,publishOpts:n}=e,r=t.formatJsonRpcRequest("wc_sessionPropose",s,s.id);this.client.core.history.set(s.pairingTopic,r);const i=await this.client.core.crypto.encode(s.pairingTopic,r,{encoding:Mp}),o=Jp(JSON.stringify(r)),a=Jp(i),c=await this.client.core.verify.register({id:a,decryptedId:o});await this.client.core.relayer.publishCustom({payload:{pairingTopic:s.pairingTopic,sessionProposal:i},opts:iE(rE({},n),{publishMethod:"wc_proposeSession",attestation:c})})})),oE(this,"sendApproveSession",(async e=>{const{sessionTopic:s,pairingProposalResponse:n,proposal:r,sessionSettleRequest:i,publishOpts:o}=e,a=t.formatJsonRpcResult(r.id,n),c=await this.client.core.crypto.encode(r.pairingTopic,a,{encoding:Mp}),l=t.formatJsonRpcRequest("wc_sessionSettle",i,o?.id),d=await this.client.core.crypto.encode(s,l,{encoding:Mp});this.client.core.history.set(s,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:s,pairingTopic:r.pairingTopic,sessionProposalResponse:c,sessionSettlementRequest:d},opts:iE(rE({},o),{publishMethod:"wc_approveSession"})})})),oE(this,"sendResult",(async e=>{const{id:s,topic:n,result:r,throwOnFailedPublish:i,encodeOpts:o,appLink:a}=e,c=t.formatJsonRpcResult(s,r);let l;const d=a&&typeof(null==global?void 0:global.Linking)<"u";try{const e=d?Bp:Mp;l=await this.client.core.crypto.encode(n,c,iE(rE({},o||{}),{encoding:e}))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),e}let h,u;try{h=await this.client.core.history.get(n,s);const e=h.request;try{u=this.getTVFParams(s,e.params,r)}catch(e){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${e?.message}`)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${s}) failed`),e}if(d){const e=Ef(a,n,l);await global.Linking.openURL(e,this.client.name)}else{const e=h.request.method,t=Wv[e].res;t.tvf=iE(rE({},u),{correlationId:s}),i?(t.internal=iE(rE({},t.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,l,t)):this.client.core.relayer.publish(n,l,t).catch((e=>this.client.logger.error(e)))}await this.client.core.history.resolve(c)})),oE(this,"sendError",(async e=>{const{id:s,topic:n,error:r,encodeOpts:i,rpcOpts:o,appLink:a}=e,c=t.formatJsonRpcError(s,r);let l;const d=a&&typeof(null==global?void 0:global.Linking)<"u";try{const e=d?Bp:Mp;l=await this.client.core.crypto.encode(n,c,iE(rE({},i||{}),{encoding:e}))}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),e}let h;try{h=await this.client.core.history.get(n,s)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${n}, ${s}) failed`),e}if(d){const e=Ef(a,n,l);await global.Linking.openURL(e,this.client.name)}else{const e=h.request.method,t=o||Wv[e].res;this.client.core.relayer.publish(n,l,t)}await this.client.core.history.resolve(c)})),oE(this,"cleanup",(async()=>{const e=[],t=[];this.client.session.getAll().forEach((t=>{let s=!1;Lc(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=>{Lc(e.expiryTimestamp)&&t.push(e.id)})),await Promise.all([...e.map((e=>this.deleteSession({topic:e}))),...t.map((e=>this.deleteProposal(e)))])})),oE(this,"onProviderMessageEvent",(async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)})),oE(this,"onRelayEventRequest",(async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()})),oE(this,"processRequestsQueue",(async()=>{if(this.requestQueue.state!==Vv){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Vv;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=zv}else this.client.logger.info("Request queue already active, skipping...")})),oE(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}`)}})),oE(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}`)}})),oE(this,"onRelayEventUnknownPayload",(e=>{const{topic:t}=e,{message:s}=rc("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)})),oE(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)})),oE(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(bm)),this.isValidConnect(rE({},s.params));const a=i.expiryTimestamp||Uc(Wv.wc_sessionPropose.req.ttl),c=rE({id:o,pairingTopic:t,expiryTimestamp:a,attestation:n,encryptedId:r},i);await this.setProposal(o,c);const l=await this.getVerifyContext({attestationId:n,hash:Jp(JSON.stringify(s)),encryptedId:r,metadata:c.proposer.metadata});e?.addTrace(pm),this.client.events.emit("session_proposal",{id:o,params:c,verifyContext:l})}catch(e){await this.sendError({id:o,topic:t,error:e,rpcOpts:Wv.wc_sessionPropose.autoReject}),this.client.logger.error(e)}})),oE(this,"onSessionProposeResponse",(async(e,s,n)=>{const{id:r}=s;if(t.isJsonRpcResult(s)){const{result:t}=s;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:t});const i=this.client.proposal.get(r);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=t.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(r,{sessionTopic:c,pairingTopic:e,proposalId:r,publicKey:o});const l=await this.client.core.relayer.subscribe(c,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:e})}else if(t.isJsonRpcError(s)){await this.deleteProposal(r);const e=Dc("session_connect",r);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:s.error})}})),oE(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=iE(rE(rE(rE({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:Rg.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(Dc("session_connect",h.proposalId),{session:p})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}})),oE(this,"onSessionSettleResponse",(async(e,s)=>{const{id:n}=s;t.isJsonRpcResult(s)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Dc("session_approve",n),{})):t.isJsonRpcError(s)&&(await this.client.session.delete(e,ic("USER_DISCONNECTED")),this.events.emit(Dc("session_approve",n),{error:s.error}))})),oE(this,"onSessionUpdateRequest",(async(e,t)=>{const{params:s,id:n}=t;try{const t=`${e}_session_update`,r=rg.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:ic("INVALID_UPDATE_REQUEST")});this.isValidUpdate(rE({topic:e},s));try{rg.set(t,n),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:e,result:!0})}catch(e){throw rg.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)}})),oE(this,"isRequestOutOfSync",((e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3))),oE(this,"onSessionUpdateResponse",((e,s)=>{const{id:n}=s,r=Dc("session_update",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);t.isJsonRpcResult(s)?this.events.emit(Dc("session_update",n),{}):t.isJsonRpcError(s)&&this.events.emit(Dc("session_update",n),{error:s.error})})),oE(this,"onSessionExtendRequest",(async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Uc(qv)),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)}})),oE(this,"onSessionExtendResponse",((e,s)=>{const{id:n}=s,r=Dc("session_extend",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);t.isJsonRpcResult(s)?this.events.emit(Dc("session_extend",n),{}):t.isJsonRpcError(s)&&this.events.emit(Dc("session_extend",n),{error:s.error})})),oE(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)}})),oE(this,"onSessionPingResponse",((e,s)=>{const{id:n}=s,r=Dc("session_ping",n);setTimeout((()=>{if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners 2176`);t.isJsonRpcResult(s)?this.events.emit(Dc("session_ping",n),{}):t.isJsonRpcError(s)&&this.events.emit(Dc("session_ping",n),{error:s.error})}),500)})),oE(this,"onSessionDeleteRequest",(async(e,t)=>{const{id:s}=t;try{await this.isValidDisconnect({topic:e,reason:t.params}),this.cleanupPendingSentRequestsForTopic({topic:e,error:ic("USER_DISCONNECTED")}),await this.deleteSession({topic:e,id:s})}catch(e){this.client.logger.error(e)}})),oE(this,"onSessionRequest",(async e=>{var s,n,r;const{topic:i,payload:o,attestation:a,encryptedId:c,transportType:l}=e,{id:d,params:h}=o;try{await this.isValidRequest(rE({topic:i},h));const e=this.client.session.get(i),o={id:d,topic:i,params:h,verifyContext:await this.getVerifyContext({attestationId:a,hash:Jp(JSON.stringify(t.formatJsonRpcRequest("wc_sessionRequest",h,d))),encryptedId:c,metadata:e.peer.metadata,transportType:l})};await this.setPendingSessionRequest(o),l===Rg.link_mode&&null!=(s=e.peer.metadata.redirect)&&s.universal&&this.client.core.addLinkModeSupportedApp(null==(n=e.peer.metadata.redirect)?void 0:n.universal),null!=(r=this.client.signConfig)&&r.disableRequestQueue?this.emitSessionRequest(o):(this.addSessionRequestToSessionRequestQueue(o),this.processSessionRequestQueue())}catch(e){await this.sendError({id:d,topic:i,error:e}),this.client.logger.error(e)}})),oE(this,"onSessionRequestResponse",((e,s)=>{const{id:n}=s,r=Dc("session_request",n);if(0===this.events.listenerCount(r))throw new Error(`emitting ${r} without any listeners`);t.isJsonRpcResult(s)?this.events.emit(Dc("session_request",n),{result:s.result}):t.isJsonRpcError(s)&&this.events.emit(Dc("session_request",n),{error:s.error})})),oE(this,"onSessionEventRequest",(async(e,t)=>{const{id:s,params:n}=t;try{const t=`${e}_session_event_${n.event.name}`,r=rg.get(t);if(r&&this.isRequestOutOfSync(r,s))return void this.client.logger.info(`Discarding out of sync request - ${s}`);this.isValidEmit(rE({topic:e},n)),this.client.events.emit("session_event",{id:s,topic:e,params:n}),rg.set(t,s)}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}})),oE(this,"onSessionAuthenticateResponse",((e,s)=>{const{id:n}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:s}),t.isJsonRpcResult(s)?this.events.emit(Dc("session_request",n),{result:s.result}):t.isJsonRpcError(s)&&this.events.emit(Dc("session_request",n),{error:s.error})})),oE(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:Jp(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===Rg.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:Fp,receiverPublicKey:t,senderPublicKey:r};await this.sendError({id:n.id,topic:s,error:e,encodeOpts:a,rpcOpts:Wv.wc_sessionAuthenticate.autoReject,appLink:i})}})),oE(this,"addSessionRequestToSessionRequestQueue",(e=>{this.sessionRequestQueue.queue.push(e)})),oE(this,"cleanupAfterResponse",(e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout((()=>{this.sessionRequestQueue.state=zv,this.processSessionRequestQueue()}),t.cjs.toMiliseconds(this.requestQueueDelay))})),oE(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(Dc("session_request",e.request.id),{error:t})}))})),oE(this,"processSessionRequestQueue",(()=>{if(this.sessionRequestQueue.state===Vv)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.")})),oE(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=Vv,this.emittedSessionRequests.add(e.id),this.client.events.emit("session_request",e))})),oE(this,"onPairingCreated",(e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const s=this.client.proposal.getAll().find((t=>t.pairingTopic===e.topic));s&&this.onSessionProposeRequest({topic:e.topic,payload:t.formatJsonRpcRequest("wc_sessionPropose",iE(rE({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id),attestation:s.attestation,encryptedId:s.encryptedId})})),oE(this,"isValidConnect",(async e=>{if(!Jf(e)){const{message:t}=rc("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(jf(t)||await this.isValidPairingTopic(t),!function(e,t){let s=!1;return t&&!e?s=!0:e&&Mf(e)&&e.length&&e.forEach((e=>{s=Gf(e)})),s}(o,!0)){const{message:e}=rc("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(s&&!jf(s)&&0!==Bf(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&&!jf(n)&&0!==Bf(n)&&this.validateNamespaces(n,"optionalNamespaces"),r&&!jf(r)&&this.validateSessionProps(r,"sessionProperties"),i&&!jf(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)}`)}})),oE(this,"validateNamespaces",((e,t)=>{const s=function(e,t,s){let n=null;if(e&&Bf(e)){const r=Vf(e,t);r&&(n=r);const i=Hf(e,t,s);i&&(n=i)}else n=rc("MISSING_OR_INVALID",`${t}, ${s} should be an object with data`);return n}(e,"connect()",t);if(s)throw new Error(s.message)})),oE(this,"isValidApprove",(async e=>{if(!Jf(e))throw new Error(rc("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=Kf(s,"approve()");if(a)throw new Error(a.message);const c=Qf(o.requiredNamespaces,s,"approve()");if(c)throw new Error(c.message);if(!$f(n,!0)){const{message:e}=rc("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(e)}if(r&&!jf(r)&&this.validateSessionProps(r,"sessionProperties"),i&&!jf(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(", ")}`)}})),oE(this,"isValidReject",(async e=>{if(!Jf(e)){const{message:t}=rc("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&&Ff(e.code,!1)&&e.message&&$f(e.message,!1))}(s)){const{message:e}=rc("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(e)}})),oE(this,"isValidSessionSettleRequest",(e=>{if(!Jf(e)){const{message:t}=rc("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:s,namespaces:n,expiry:r}=e;if(!Gf(t)){const{message:e}=rc("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const i=function(e,t){let s=null;return $f(e?.publicKey,!1)||(s=rc("MISSING_OR_INVALID",`${t} controller public key should be a string`)),s}(s,"onSessionSettleRequest()");if(i)throw new Error(i.message);const o=Kf(n,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(Lc(r)){const{message:e}=rc("EXPIRED","onSessionSettleRequest()");throw new Error(e)}})),oE(this,"isValidUpdate",(async e=>{if(!Jf(e)){const{message:t}=rc("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=Kf(s,"update()");if(r)throw new Error(r.message);const i=Qf(n.requiredNamespaces,s,"update()");if(i)throw new Error(i.message)})),oE(this,"isValidExtend",(async e=>{if(!Jf(e)){const{message:t}=rc("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)})),oE(this,"isValidRequest",(async e=>{if(!Jf(e)){const{message:t}=rc("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(!Yf(i,n)){const{message:e}=rc("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(e)}if(!function(e){return!(jf(e)||!$f(e.method,!1))}(s)){const{message:e}=rc("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(e)}if(!Xf(i,n,s.method)){const{message:e}=rc("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(e)}this.validateRequestExpiry(r)})),oE(this,"isValidRespond",(async e=>{var t;if(!Jf(e)){const{message:t}=rc("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!(jf(e)||jf(e.result)&&jf(e.error)||!Ff(e.id,!1)||!$f(e.jsonrpc,!1))}(n)){const{message:e}=rc("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}=rc("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${r.topic}, received topic: ${s}`);throw new Error(e)}})),oE(this,"isValidPing",(async e=>{if(!Jf(e)){const{message:t}=rc("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)})),oE(this,"isValidEmit",(async e=>{if(!Jf(e)){const{message:t}=rc("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(!Yf(r,n)){const{message:e}=rc("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(e)}if(!function(e){return!(jf(e)||!$f(e.name,!1))}(s)){const{message:e}=rc("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}if(!Zf(r,n,s.name)){const{message:e}=rc("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}})),oE(this,"isValidDisconnect",(async e=>{if(!Jf(e)){const{message:t}=rc("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)})),oE(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(!$f(s,!1))throw new Error("uri is required parameter");if(!$f(n,!1))throw new Error("domain is required parameter");if(!$f(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map((e=>ec(e).namespace)))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:i}=ec(t[0]);if("eip155"!==i)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")})),oE(this,"getVerifyContext",(async e=>{const{attestationId:t,hash:s,encryptedId:n,metadata:r,transportType:i}=e,o={verified:{verifyUrl:r.verifyUrl||tm,validation:"UNKNOWN",origin:r.url||""}};try{if(i===Rg.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})),oE(this,"validateSessionProps",((e,t)=>{Object.values(e).forEach(((s,n)=>{if(null==s){const{message:r}=rc("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${s} for key ${Object.keys(e)[n]}`);throw new Error(r)}}))})),oE(this,"getPendingAuthRequest",(e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0})),oE(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)}}})),oE(this,"checkRecentlyDeleted",(e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=rc("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}})),oE(this,"isLinkModeEnabled",((e,t)=>{var s,n,r,i,o,a,c,l,d;return!(!e||t!==Rg.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")})),oE(this,"getAppLinkIfEnabled",((e,t)=>{var s;return this.isLinkModeEnabled(e,t)?null==(s=e?.redirect)?void 0:s.universal:void 0})),oE(this,"handleLinkModeMessage",(({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=jc(e,"topic")||"",s=decodeURIComponent(jc(e,"wc_ev")||""),n=this.client.session.keys.includes(t);n&&this.client.session.update(t,{transportType:Rg.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:n})})),oE(this,"registerLinkModeListeners",(async()=>{var e;if(Fc()||bc()&&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)}}})),oE(this,"getTVFApproveParams",(e=>{try{const t=Pf(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"),{}}})),oE(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})),oE(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})),oE(this,"extractTxHashesFromResult",((e,t)=>{var s;try{if(!t)return[];const n=e.method,r=Kv[n];if("sui_signTransaction"===n)return[Pd(t.transactionBytes)];if("near_signTransaction"===n)return[Rd(t)];if("near_signTransactions"===n)return t.map((e=>Rd(e)));if("xrpl_signTransactionFor"===n||"xrpl_signTransaction"===n)return[null==(s=t.tx_json)?void 0:s.hash];if("polkadot_signTransaction"===n)return[ag({transaction:e.params.transactionPayload,signature:t.signature})];if("algo_signTxn"===n)return Mf(t)?t.map((e=>Ud(e))):[Ud(t)];if("cosmos_signDirect"===n)return[Dd(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(Mf(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 Va.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}=rc("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Eg,(e=>{this.onProviderMessageEvent(e)}))}async onRelayMessage(e){const{topic:s,message:n,attestation:r,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Yv)?this.client.auth.authKeys.get(Yv):{responseTopic:void 0,publicKey:void 0};try{const e=await this.client.core.crypto.decode(s,n,{receiverPublicKey:o,encoding:i===Rg.link_mode?Bp:Mp});t.isJsonRpcRequest(e)?(this.client.core.history.set(s,e),await this.onRelayEventRequest({topic:s,payload:e,attestation:r,transportType:i,encryptedId:Jp(n)})):t.isJsonRpcResponse(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:s,payload:e,transportType:i}),this.client.core.history.delete(s,e.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(e)}`),await this.onRelayEventUnknownPayload({topic:s,payload:e,transportType:i})),await this.client.core.relayer.messages.ack(s,n)}catch(e){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(e)}}registerExpirerEvents(){this.client.core.expirer.on(Zg,(async e=>{const{topic:t,id:s}=Rc(e.target);return s&&this.client.pendingRequest.keys.includes(s)?await this.deletePendingSessionRequest(s,rc("EXPIRED"),!0):s&&this.client.auth.requests.keys.includes(s)?await this.deletePendingAuthRequest(s,rc("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(qg,(e=>this.onPairingCreated(e))),this.client.core.pairing.events.on(Hg,(e=>{this.addToRecentlyDeleted(e.topic,"pairing")}))}isValidPairingTopic(e){if(!$f(e,!1)){const{message:t}=rc("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}=rc("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Lc(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=rc("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!$f(e,!1)){const{message:t}=rc("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}=rc("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Lc(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=rc("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=rc("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($f(e,!1)){const{message:t}=rc("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=rc("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}=rc("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=rc("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Lc(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=rc("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}validateRequestExpiry(e){if(e&&!function(e,t){return Ff(e,!1)&&e<=t.max&&e>=t.min}(e,Hv)){const{message:t}=rc("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${Hv.min} and ${Hv.max}`);throw new Error(t)}}}class cE extends nv{constructor(e,t){super(e,t,"proposal",Mv),this.core=e,this.logger=t}}class lE extends nv{constructor(e,t){super(e,t,"session",Mv),this.core=e,this.logger=t}}class dE extends nv{constructor(e,t){super(e,t,"request",Mv,(e=>e.id)),this.core=e,this.logger=t}}class hE extends nv{constructor(e,t){super(e,t,"authKeys",Jv,(()=>Yv)),this.core=e,this.logger=t}}class uE extends nv{constructor(e,t){super(e,t,"pairingTopics",Jv),this.core=e,this.logger=t}}class pE extends nv{constructor(e,t){super(e,t,"requests",Jv,(e=>e.id)),this.core=e,this.logger=t}}var fE=Object.defineProperty,gE=(e,t,s)=>((e,t,s)=>t in e?fE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class mE{constructor(e,t){this.core=e,this.logger=t,gE(this,"authKeys"),gE(this,"pairingTopics"),gE(this,"requests"),this.authKeys=new hE(this.core,this.logger),this.pairingTopics=new uE(this.core,this.logger),this.requests=new pE(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var yE=Object.defineProperty,wE=(e,t,s)=>((e,t,s)=>t in e?yE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class bE extends Yn{constructor(t){super(t),wE(this,"protocol","wc"),wE(this,"version",2),wE(this,"name",Bv),wE(this,"metadata"),wE(this,"core"),wE(this,"logger"),wE(this,"events",new e.EventEmitter),wE(this,"engine"),wE(this,"session"),wE(this,"proposal"),wE(this,"pendingRequest"),wE(this,"auth"),wE(this,"signConfig"),wE(this,"on",((e,t)=>this.events.on(e,t))),wE(this,"once",((e,t)=>this.events.once(e,t))),wE(this,"off",((e,t)=>this.events.off(e,t))),wE(this,"removeListener",((e,t)=>this.events.removeListener(e,t))),wE(this,"removeAllListeners",(e=>this.events.removeAllListeners(e))),wE(this,"connect",(async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"pair",(async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"approve",(async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"reject",(async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"update",(async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"extend",(async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"request",(async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"respond",(async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"ping",(async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"emit",(async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"disconnect",(async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"find",(e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"getPendingSessionRequests",(()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}})),wE(this,"authenticate",(async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"formatAuthMessage",(e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"approveSessionAuthenticate",(async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}})),wE(this,"rejectSessionAuthenticate",(async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}})),this.name=t?.name||Bv,this.metadata=Nc(t?.metadata),this.signConfig=t?.signConfig;const s=cg({logger:t?.logger||jv,name:this.name});this.logger=s,this.core=t?.core||new Lv(t),this.session=new lE(this.core,this.logger),this.proposal=new cE(this.core,this.logger),this.pendingRequest=new dE(this.core,this.logger),this.engine=new aE(this),this.auth=new mE(this.core,this.logger)}static async init(e){const t=new bE(e);return await t.initialize(),t}get context(){return kn(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 vE=bE;var EE=Object.defineProperty,CE=Object.defineProperties,NE=Object.getOwnPropertyDescriptors,AE=Object.getOwnPropertySymbols,IE=Object.prototype.hasOwnProperty,SE=Object.prototype.propertyIsEnumerable,_E=(e,t,s)=>t in e?EE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,OE=(e,t)=>{for(var s in t||(t={}))IE.call(t,s)&&_E(e,s,t[s]);if(AE)for(var s of AE(t))SE.call(t,s)&&_E(e,s,t[s]);return e},TE=(e,t)=>CE(e,NE(t));const kE={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"};class xE{constructor(s,n=!1){if(this.url=s,this.disableProviderPing=n,this.events=new e.EventEmitter,this.isAvailable=!1,this.registering=!1,!t.isHttpUrl(s))throw new Error(`Provided URL is not compatible with HTTP connection: ${s}`);this.url=s,this.disableProviderPing=n}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 s=t.safeJsonStringify(e),r=await(await n.o(this.url,TE(OE({},kE),{body:s}))).json();this.onPayload({data:r})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!t.isHttpUrl(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 s=t.safeJsonStringify({id:1,jsonrpc:"2.0",method:"test",params:[]});await n.o(e,TE(OE({},kE),{body:s}))}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 s="string"==typeof e.data?t.safeJsonParse(e.data):e.data;this.events.emit("payload",s)}onError(e,s){const n=this.parseError(s),r=n.message||n.toString(),i=t.formatJsonRpcError(e,r);this.events.emit("payload",i)}parseError(e,s=this.url){return t.parseConnectionError(e,s,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}}function PE(e){return null!=e&&"function"!=typeof e&&function(e){return Number.isSafeInteger(e)&&e>=0}(e.length)}function RE(e){return"__proto__"===e}function UE(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function LE(e){return Object.getOwnPropertySymbols(e).filter((t=>Object.prototype.propertyIsEnumerable.call(e,t)))}function DE(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const ME="[object RegExp]",BE="[object String]",jE="[object Number]",$E="[object Boolean]",FE="[object Arguments]",qE="[object Symbol]",WE="[object Date]",HE="[object Map]",zE="[object Set]",VE="[object Array]",KE="[object ArrayBuffer]",GE="[object Object]",JE="[object DataView]",YE="[object Uint8Array]",XE="[object Uint8ClampedArray]",ZE="[object Uint16Array]",QE="[object Uint32Array]",eC="[object Int8Array]",tC="[object Int16Array]",sC="[object Int32Array]",nC="[object Float32Array]",rC="[object Float64Array]";function iC(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function oC(e,t,s,n=new Map,r=void 0){const i=r?.(e,t,s,n);if(void 0!==i)return i;if(UE(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]=oC(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,oC(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(oC(i,void 0,s,n,r));return t}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(iC(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);n.set(e,t);for(let i=0;i<e.length;i++)t[i]=oC(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),aC(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),aC(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),aC(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,aC(t,e,s,n,r),t}if(e instanceof Boolean){const t=new Boolean(e.valueOf());return n.set(e,t),aC(t,e,s,n,r),t}if(e instanceof Number){const t=new Number(e.valueOf());return n.set(e,t),aC(t,e,s,n,r),t}if(e instanceof String){const t=new String(e.valueOf());return n.set(e,t),aC(t,e,s,n,r),t}if("object"==typeof e&&function(e){switch(DE(e)){case FE:case VE:case KE:case JE:case $E:case WE:case nC:case rC:case eC:case tC:case sC:case HE:case jE:case GE:case ME:case zE:case BE:case qE:case YE:case XE:case ZE:case QE:return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return n.set(e,t),aC(t,e,s,n,r),t}return e}function aC(e,t,s=e,n,r){const i=[...Object.keys(t),...LE(t)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=oC(t[a],a,s,n,r))}}function cC(e,t){return function(e,t){return oC(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(DE(e)===GE&&"function"!=typeof e.constructor){const t={};return i.set(e,t),aC(t,e,r,i),t}switch(Object.prototype.toString.call(e)){case jE:case BE:case $E:{const t=new e.constructor(e?.valueOf());return aC(t,e),t}case FE:{const t={};return aC(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}}))}function lC(e){return cC(e)}function dC(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===DE(e)}function hC(e){return"object"==typeof e&&null!==e}function uC(e){return hC(e)&&PE(e)}function pC(){}function fC(e){return iC(e)}function gC(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 mC(e,t,s,n){if(UE(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(n.has(t))return function(e){if(UE(e))return e;if(Array.isArray(e)||iC(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),...LE(t)];for(let i=0;i<r.length;i++){const o=r[i];if(RE(o))continue;let a=t[o],c=e[o];if(dC(a)&&(a={...a}),dC(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=lC(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(uC(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)||hC(c)&&hC(a)&&(gC(c)||gC(a)||fC(c)||fC(a))?e[o]=mC(c,a,s,n):null==c&&gC(a)?e[o]=mC({},a,s,n):null==c&&fC(a)?e[o]=lC(a):(void 0===c||void 0!==a)&&(e[o]=a)}return e}function yC(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=mC(r,s[e],n,new Map);return r}(e,...t,pC)}const wC="error",bC="universal_provider",vC=`wc@2:${bC}:`,EC="https://rpc.walletconnect.org/v1/",CC="generic",NC=`${EC}bundler`,AC="call_status",IC="default_chain_changed";var SC=Object.defineProperty,_C=Object.defineProperties,OC=Object.getOwnPropertyDescriptors,TC=Object.getOwnPropertySymbols,kC=Object.prototype.hasOwnProperty,xC=Object.prototype.propertyIsEnumerable,PC=(e,t,s)=>t in e?SC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,RC=(e,t)=>{for(var s in t||(t={}))kC.call(t,s)&&PC(e,s,t[s]);if(TC)for(var s of TC(t))xC.call(t,s)&&PC(e,s,t[s]);return e},UC=(e,t)=>_C(e,OC(t));function LC(e,t,s){var n;const r=ec(e);return(null==(n=t.rpcMap)?void 0:n[r.reference])||`${EC}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function DC(e){return e.map((e=>`${e.split(":")[0]}:${e.split(":")[1]}`))}function MC(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 BC(e={},t={}){return yC(MC(jC(e)),MC(jC(t)))}function jC(e){var t,s,n,r,i;const o={};if(!Bf(e))return o;for(const[a,c]of Object.entries(e)){const e=Rf(a)?[a]:c.chains,l=c.methods||[],d=c.events||[],h=c.rpcMap||{},u=Uf(a);o[u]=UC(RC(RC({},o[u]),c),{chains:Mc(e,null==(t=o[u])?void 0:t.chains),methods:Mc(l,null==(s=o[u])?void 0:s.methods),events:Mc(d,null==(n=o[u])?void 0:n.events)}),(Bf(h)||Bf((null==(r=o[u])?void 0:r.rpcMap)||{}))&&(o[u].rpcMap=RC(RC({},h),null==(i=o[u])?void 0:i.rpcMap))}return o}function $C(e){return e.includes(":")?e.split(":")[2]:e}function FC(e){const t={};for(const[s,n]of Object.entries(e)){const e=n.methods||[],r=n.events||[],i=n.accounts||[],o=Rf(s)?[s]:n.chains?n.chains:DC(n.accounts);t[s]={chains:o,methods:e,events:r,accounts:i}}return t}function qC(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 WC={},HC=e=>WC[e],zC=(e,t)=>{WC[e]=t};var VC=Object.defineProperty,KC=Object.getOwnPropertySymbols,GC=Object.prototype.hasOwnProperty,JC=Object.prototype.propertyIsEnumerable,YC=(e,t,s)=>t in e?VC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,XC=(e,t)=>{for(var s in t||(t={}))GC.call(t,s)&&YC(e,s,t[s]);if(KC)for(var s of KC(t))JC.call(t,s)&&YC(e,s,t[s]);return e};const ZC="eip155",QC=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],eN=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,tN=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,sN=e=>Object.keys(e).filter((e=>QC.includes(e))).reduce(((t,s)=>(t[s]=nN(e[s]),t)),{}),nN=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 rN=Object.defineProperty,iN=(e,t,s)=>((e,t,s)=>t in e?rN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let oN;class aN{constructor(e){iN(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 oN||(oN=new aN(e)),oN}}var cN=Object.defineProperty,lN=Object.defineProperties,dN=Object.getOwnPropertyDescriptors,hN=Object.getOwnPropertySymbols,uN=Object.prototype.hasOwnProperty,pN=Object.prototype.propertyIsEnumerable,fN=(e,t,s)=>t in e?cN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;async function gN(e,s){const n=ec(e.result.capabilities.caip345.caip2),r=e.result.capabilities.caip345.transactionHashes,i=await Promise.allSettled(r.map((e=>async function(e,s,n){return await n(parseInt(e)).request(t.formatJsonRpcRequest("eth_getTransactionReceipt",[s]))}(n.reference,e,s)))),o=i.filter((e=>"fulfilled"===e.status)).map((e=>e.value)).filter((e=>e));i.filter((e=>"rejected"===e.status)).forEach((e=>console.warn("Failed to fetch transaction receipt:",e.reason)));const a=!o.length||o.some((e=>!e)),c=o.every((e=>"0x1"===e?.status)),l=o.every((e=>"0x0"===e?.status)),d=o.some((e=>"0x0"===e?.status));let h;return a?h=100:c?h=200:l?h=500:d&&(h=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:o,status:h}}async function mN({sendCalls:e,storage:t}){const s=await t.getItem(AC);await t.setItem(AC,((e,t)=>lN(e,dN(t)))(((e,t)=>{for(var s in t||(t={}))uN.call(t,s)&&fN(e,s,t[s]);if(hN)for(var s of hN(t))pN.call(t,s)&&fN(e,s,t[s]);return e})({},s),{[e.result.id]:{request:e.request,result:e.result,expiry:Uc(86400)}}))}async function yN({resultId:e,storage:t}){const s=await t.getItem(AC),n=s?.[e];if(n&&!Lc(n.expiry))return n;await async function({resultId:e,storage:t}){const s=await t.getItem(AC);if(s){delete s[e],await t.setItem(AC,s);for(const e in s)Lc(s[e].expiry)&&delete s[e];await t.setItem(AC,s)}}({resultId:e,storage:t})}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)),_N=(e,t,s)=>AN(e,"symbol"!=typeof t?t+"":t,s);class ON{constructor(e){_N(this,"name","eip155"),_N(this,"client"),_N(this,"chainId"),_N(this,"namespace"),_N(this,"httpProviders"),_N(this,"events"),_N(this,"storage"),this.namespace=e.namespace,this.events=HC("events"),this.client=HC("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=aN.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(IC,{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||LC(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new lg(new xE(s,HC("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=SN(IN({},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(!Bf(r)&&!Bf(n))return;const o=sN(n);for(const e of s){const s=eN(e);if(!s)continue;i[tN(s)]=o;const n=r?.[`${ZC}:${s}`];if(n){const e=n?.[`${ZC}:${s}:${t}`];i[tN(s)]=XC(XC({},i[tN(s)]),sN(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:SN(IN({},c.sessionProperties||{}),{capabilities:SN(IN({},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 yN({resultId:null==(n=e.request.params)?void 0:n[0],storage:this.storage});if(a)try{return await gN(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,s){var n;const r=new URL(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.formatJsonRpcRequest("eth_getUserOperationReceipt",[null==(n=s.request.params)?void 0:n[0]]))});if(!i.ok)throw new Error(`Failed to fetch user operation receipt - ${i.status}`);return await i.json()}getBundlerUrl(e,t){return`${NC}?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 mN({sendCalls:{request:i,result:r},storage:this.storage}),r}}var TN=Object.defineProperty,kN=(e,t,s)=>((e,t,s)=>t in e?TN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class xN{constructor(e){kN(this,"name",CC),kN(this,"client"),kN(this,"httpProviders"),kN(this,"events"),kN(this,"namespace"),kN(this,"chainId"),this.namespace=e.namespace,this.events=HC("events"),this.client=HC("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(IC,{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 ec(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=ec(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=ec(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||LC(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new lg(new xE(s,HC("disableProviderPing")))}}var PN=Object.defineProperty,RN=Object.defineProperties,UN=Object.getOwnPropertyDescriptors,LN=Object.getOwnPropertySymbols,DN=Object.prototype.hasOwnProperty,MN=Object.prototype.propertyIsEnumerable,BN=(e,t,s)=>t in e?PN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,jN=(e,t)=>{for(var s in t||(t={}))DN.call(t,s)&&BN(e,s,t[s]);if(LN)for(var s of LN(t))MN.call(t,s)&&BN(e,s,t[s]);return e},$N=(e,t)=>RN(e,UN(t)),FN=(e,t,s)=>BN(e,"symbol"!=typeof t?t+"":t,s);class qN{constructor(e){var t,s;FN(this,"client"),FN(this,"namespaces"),FN(this,"optionalNamespaces"),FN(this,"sessionProperties"),FN(this,"scopedProperties"),FN(this,"events",new i.default),FN(this,"rpcProviders",{}),FN(this,"session"),FN(this,"providerOpts"),FN(this,"logger"),FN(this,"uri"),FN(this,"disableProviderPing",!1),FN(this,"connectParams"),this.providerOpts=e,this.logger=cg({logger:null!=(t=e.logger)?t:wC,name:null!=(s=this.providerOpts.name)?s:bC}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new qN(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:jN({},e),chainId:`${n}:${r}`,topic:this.session.topic,expiry:s})}sendAsync(e,s,n,r){const i=(new Date).getTime();this.request(e,n,r).then((e=>s(null,t.formatJsonRpcResult(i,e)))).catch((e=>s(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:ic("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=FC(this.session.namespaces);this.namespaces=BC(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=FC(i.namespaces);return this.namespaces=BC(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(!Mf(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 vE.init({core:this.providerOpts.core,logger:this.providerOpts.logger||wC,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=>Uf(e))))];zC("client",this.client),zC("events",this.events),zC("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=DC(t),n=BC(this.namespaces,this.optionalNamespaces),r=$N(jN({},n[e]),{accounts:t,chains:s});if("eip155"===e)this.rpcProviders[e]=new ON({namespace:r});else this.rpcProviders[e]=new xN({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&&Mf(e)&&this.events.emit("accountsChanged",e.map($C))}else if("chainChanged"===r.name){const e=s.chainId,t=s.event.data,n=Uf(e),r=qC(e)!==qC(t)?`${n}:${qC(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=$N(jN({},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",$N(jN({},ic("USER_DISCONNECTED")),{data:e.topic})))})),this.on(IC,(e=>{this.onChainChanged($N(jN({},e),{internal:!0}))}))}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[CC]}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=BC(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=>Uf(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=Uf(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($C);if(!Mf(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(`${vC}/${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(`${vC}/${e}${s}`)}async deleteFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${vC}/${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(vC)&&await this.client.core.storage.removeItem(e)}catch(e){this.logger.warn(e,"Failed to cleanup storage")}}}const WN=2147483648,HN={convertEVMChainIdToCoinType(e){if(e>=WN)throw new Error("Invalid chainId");return(WN|e)>>>0}},zN=te({suggestions:[],loading:!1}),VN={state:zN,subscribe:e=>se(zN,(()=>e(zN))),subscribeKey:(e,t)=>ie(zN,e,t),async resolveName(e){try{return await Ve.lookupEnsName(e)}catch(e){const t=e;throw new Error(t?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(e){try{return await Ve.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{zN.loading=!0,zN.suggestions=[];const t=await Ve.getEnsNameSuggestions(e);return zN.suggestions=t.suggestions||[],zN.suggestions}catch(e){const t=KN.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{zN.loading=!1}},async getNamesForAddress(e){try{if(!as.state.activeCaipNetwork)return[];const t=ue.getEnsFromCacheForAddress(e);if(t)return t;const s=await Ve.reverseLookupEnsName({address:e});return ue.updateEnsCache({address:e,ens:s,timestamp:Date.now()}),s}catch(e){const t=KN.parseEnsApiError(e,"Error fetching names for address");throw new Error(t)}},async registerName(e){const t=as.state.activeCaipNetwork,s=as.getAccountData(t?.chainNamespace)?.address,n=Ot.getAuthConnector();if(!t)throw new Error("Network not found");if(!s||!n)throw new Error("Address or auth connector not found");zN.loading=!0;try{const n=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});vt.pushTransactionStack({onCancel(){vt.replace("RegisterAccountName")}});const r=await qt.signMessage(n);zN.loading=!1;const i=t.id;if(!i)throw new Error("Network not found");const o=HN.convertEVMChainIdToCoinType(Number(i));await Ve.registerEnsName({coinType:o,address:s,signature:r,message:n}),as.setAccountProp("profileName",e,t.chainNamespace),ue.updateEnsCache({address:s,ens:[{name:e,registered_at:(new Date).toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),vt.replace("RegisterAccountNameSuccess")}catch(t){const s=KN.parseEnsApiError(t,`Error registering name ${e}`);throw vt.replace("RegisterAccountName"),new Error(s)}finally{zN.loading=!1}},validateName:e=>/^[a-zA-Z0-9-]{4,}$/u.test(e),parseEnsApiError(e,t){const s=e;return s?.reasons?.[0]?.description||t}},KN=Qe(VN);function GN(e){try{return new URL(e)}catch{return null}}function JN(e,t){if(t.includes("://")){const s=GN(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=GN(e);return!!i&&(void 0!==n?s===i.hostname&&n===(i.port||void 0):s===i.hostname)}function YN(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 XN={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"]},ZN={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace:e=>XN[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 KN.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===ZN.RPC_ERROR_CODE.USER_REJECTED_METHODS,r=s&&t.code===ZN.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=GN(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(YN(r,e,t))return!0}else if(JN(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=ZN.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}=T.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=>T.parseCaipAddress(e))).filter((({address:e})=>!s.has(e.toLowerCase())&&(s.add(e.toLowerCase()),!0)));return n&&n.length>0?n:[]}},QN=[a.CONNECTOR_ID.AUTH,a.CONNECTOR_ID.WALLET_CONNECT];class eA{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=e=>as.getCaipNetworks(e),this.getConnectorId=e=>Ot.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:a.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:s})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:a.CONNECTOR_ID.AUTH,type:"AUTH",name:a.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){as.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(ZN.isUserRejectedRequestError(e))throw new P(e);throw e}}async switchNetwork(e){const{caipNetwork:t}=e,s=Zt.getProviderId(t.chainNamespace),n=Zt.getProvider(t.chainNamespace);if(!n)throw new Error("Provider not found");if("WALLET_CONNECT"!==s){if("AUTH"===s){const e=Ot.getAuthConnector()?.provider;if(!e)throw new Error("Auth provider not found");const s=xt(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}=pe.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}=pe.getAccount(e);return{address:t}})),caipNetwork:r}))}}onAccountsChanged(e,t,s=!0){if(e.length>0){const{address:s}=pe.getAccount(e[0]),n=this.getConnection({connectorId:t,connections:this.connections,connectors:this.connectors});s&&this.getConnectorId(a.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}=pe.getAccount(e);return{address:t}})),caipNetwork:n?.caipNetwork})}else s&&this.onDisconnect(t)}onDisconnect(e){this.removeProviderListeners(e),this.deleteConnection(e),this.getConnectorId(a.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(a.CHAIN.EVM)?.toLowerCase()===t.toLowerCase()&&this.emit("switchNetwork",{chainId:s})}listenProviderEvents(e,t){if(QN.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 tA=null;const sA={getSIWX:()=>je.state.siwx,async initializeIfEnabled(e=as.getActiveCaipAddress()){const t=je.state.siwx;if(!t||!e)return;const[s,n,r]=e.split(":");if(as.checkIfSupportedNetwork(s,`${s}:${n}`))try{if(je.state.remoteFeatures?.emailCapture){const e=as.getAccountData(s)?.user;return void await ds.open({view:"DataCapture",data:{email:e?.email??void 0}})}tA&&await tA;if((await t.getSessions(`${s}:${n}`,r)).length)return;await ds.open({view:"SIWXSignMessage"})}catch(e){console.error("SIWXUtil:initializeIfEnabled",e),ht.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(e)}),await(qt._getClient()?.disconnect().catch(console.error)),vt.reset("Connect"),qe.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(e=as.getActiveCaipAddress()){if(!je.state.siwx)return!0;if(!e)return!0;const{chainNamespace:t,chainId:s,address:n}=T.parseCaipAddress(e),r=`${t}:${s}`;return(await sA.getSessions({address:n,caipNetworkId:r})).length>0},async requestSignMessage(){const e=je.state.siwx,t=pe.getPlainAddress(as.getActiveCaipAddress()),s=Pt();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{Ot.getConnectorId(s.chainNamespace)===a.CONNECTOR_ID.AUTH&&vt.pushTransactionStack({}),i=await qt.signMessage(r)||""}await e.addSession({data:n,message:r,signature:i}),as.setLastConnectedSIWECaipNetwork(s),ds.close(),ht.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(e){ds.state.open&&"ApproveTransaction"!==vt.state.view||await ds.open({view:"SIWXSignMessage"}),qe.showError("Error signing message"),ht.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=as.getLastConnectedSIWECaipNetwork();if(t){const s=await(e?.getSessions(t?.caipNetworkId,pe.getPlainAddress(as.getActiveCaipAddress())||""));s&&s.length>0?await as.switchActiveNetwork(t):await qt.disconnect()}else await qt.disconnect()}else ds.close();ds.close(),ht.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){const e=this.getSIWX(),t=as.getAllRequestedCaipNetworks(),s=[];return await Promise.all(t.map((async t=>{const n=await(e?.getSessions(t.caipNetworkId,pe.getPlainAddress(as.getActiveCaipAddress())||""));n&&s.push(...n)}))),s},async getSessions(e){const t=je.state.siwx;let s=e?.address;if(!s){const e=as.getActiveCaipAddress();s=pe.getPlainAddress(e)}let n=e?.caipNetworkId;if(!n){const e=as.getActiveCaipNetwork();n=e?.caipNetworkId}return t&&s&&n?t.getSessions(n,s):[]},async isSIWXCloseDisabled(){const e=this.getSIWX();if(e){const t="ApproveTransaction"===vt.state.view,s="SIWXSignMessage"===vt.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=sA.getSIWX(),o=Pt();if(!i||!r.includes(a.CHAIN.EVM)||je.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 c=`${r}:${t}`,l=await i.createMessage({chainId:c,accountAddress:"<<AccountAddress>>"}),d={accountAddress:l.accountAddress,chainId:l.chainId,domain:l.domain,uri:l.uri,version:l.version,nonce:l.nonce,notBefore:l.notBefore,statement:l.statement,resources:l.resources,requestId:l.requestId,issuedAt:l.issuedAt,expirationTime:l.expirationTime,serializedMessage:l.toString()},h=await e.connect({chainId:t,socialUri:s,siwxMessage:d,preferredAccountType:n});if(d.accountAddress=h.address,d.serializedMessage=h.message||"",h.signature&&h.message){const e=sA.addEmbeddedWalletSession(d,h.message,h.signature);await e}return as.setLastConnectedSIWECaipNetwork(o),{address:h.address,chainId:h.chainId,accounts:h.accounts}},async addEmbeddedWalletSession(e,t,s){if(tA)return tA;const n=sA.getSIWX();return n?(tA=n.addSession({data:e,message:t,signature:s}).finally((()=>{tA=null})),tA):Promise.resolve()},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:s}){const n=sA.getSIWX(),r=Pt(),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:Pt()?.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))]});qe.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(as.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&&as.setLastConnectedSIWECaipNetwork(r),ht.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:sA.getSIWXEventProperties()})}catch(t){throw console.error("SIWX:universalProviderAuth - failed to set sessions",t),ht.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:sA.getSIWXEventProperties(t)}),await e.disconnect().catch(console.error),t}finally{qe.hide()}}return!0},getSIWXEventProperties(e){const t=as.state.activeChain;if(!t)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:as.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:xt(t)===be.ACCOUNT_TYPES.SMART_ACCOUNT,message:e?pe.parseError(e):void 0}},async clearSessions(){const e=this.getSIWX();e&&await e.setSessions([])}};class nA{constructor({provider:e,namespace:t}){this.id=a.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=as.getCaipNetworks.bind(as),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=je.state.universalProviderConfigOverride,s=ZN.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 sA.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:rA})}}const rA=["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"],iA=te({message:"",variant:"info",open:!1}),oA=Qe({state:iA,subscribeKey:(e,t)=>ie(iA,e,t),open(e,t){const{debug:s}=je.state,{code:n,displayMessage:r,debugMessage:i}=e;if(r&&s&&(iA.message=r,iA.variant=t,iA.open=!0),i){if(!a.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){iA.open=!0,iA.message=e,iA.variant="warning",t&&console.warn(t,s)},close(){iA.open=!1,iA.message="",iA.variant="info"}}),aA=globalThis,cA=aA.ShadowRoot&&(void 0===aA.ShadyCSS||aA.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,lA=Symbol(),dA=new WeakMap;class hA{constructor(e,t,s){if(this._$cssResult$=!0,s!==lA)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(cA&&void 0===e){const s=void 0!==t&&1===t.length;s&&(e=dA.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),s&&dA.set(t,e))}return e}toString(){return this.cssText}}const uA=e=>new hA("string"==typeof e?e:e+"",void 0,lA),pA=(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 hA(s,e,lA)},fA=cA?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const s of e.cssRules)t+=s.cssText;return uA(t)})(e):e
3
+ /**
4
+ * @license
5
+ * Copyright 2017 Google LLC
6
+ * SPDX-License-Identifier: BSD-3-Clause
7
+ */,{is:gA,defineProperty:mA,getOwnPropertyDescriptor:yA,getOwnPropertyNames:wA,getOwnPropertySymbols:bA,getPrototypeOf:vA}=Object,EA=globalThis,CA=EA.trustedTypes,NA=CA?CA.emptyScript:"",AA=EA.reactiveElementPolyfillSupport,IA=(e,t)=>e,SA={toAttribute(e,t){switch(t){case Boolean:e=e?NA: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}},_A=(e,t)=>!gA(e,t),OA={attribute:!0,type:String,converter:SA,reflect:!1,useDefault:!1,hasChanged:_A};Symbol.metadata??=Symbol("metadata"),EA.litPropertyMetadata??=new WeakMap;class TA 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=OA){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&&mA(this.prototype,e,n)}}static getPropertyDescriptor(e,t,s){const{get:n,set:r}=yA(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)??OA}static _$Ei(){if(this.hasOwnProperty(IA("elementProperties")))return;const e=vA(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(IA("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(IA("properties"))){const e=this.properties,t=[...wA(e),...bA(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(fA(e))}else void 0!==e&&t.push(fA(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(cA)e.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(const s of t){const t=document.createElement("style"),n=aA.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:SA).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:SA;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??_A)(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){}}TA.elementStyles=[],TA.shadowRootOptions={mode:"open"},TA[IA("elementProperties")]=new Map,TA[IA("finalized")]=new Map,AA?.({ReactiveElement:TA}),(EA.reactiveElementVersions??=[]).push("2.1.2");
8
+ /**
9
+ * @license
10
+ * Copyright 2017 Google LLC
11
+ * SPDX-License-Identifier: BSD-3-Clause
12
+ */
13
+ const kA=globalThis,xA=kA.trustedTypes,PA=xA?xA.createPolicy("lit-html",{createHTML:e=>e}):void 0,RA="$lit$",UA=`lit$${Math.random().toFixed(9).slice(2)}$`,LA="?"+UA,DA=`<${LA}>`,MA=document,BA=()=>MA.createComment(""),jA=e=>null===e||"object"!=typeof e&&"function"!=typeof e,$A=Array.isArray,FA="[ \t\n\f\r]",qA=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,WA=/-->/g,HA=/>/g,zA=RegExp(`>|${FA}(?:([^\\s"'>=/]+)(${FA}*=${FA}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),VA=/'/g,KA=/"/g,GA=/^(?:script|style|textarea|title)$/i,JA=e=>(t,...s)=>({_$litType$:e,strings:t,values:s}),YA=JA(1),XA=JA(2),ZA=Symbol.for("lit-noChange"),QA=Symbol.for("lit-nothing"),eI=new WeakMap,tI=MA.createTreeWalker(MA,129);function sI(e,t){if(!$A(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==PA?PA.createHTML(t):t}const nI=(e,t)=>{const s=e.length-1,n=[];let r,i=2===t?"<svg>":3===t?"<math>":"",o=qA;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===qA?"!--"===c[1]?o=WA:void 0!==c[1]?o=HA:void 0!==c[2]?(GA.test(c[2])&&(r=RegExp("</"+c[2],"g")),o=zA):void 0!==c[3]&&(o=zA):o===zA?">"===c[0]?(o=r??qA,l=-1):void 0===c[1]?l=-2:(l=o.lastIndex-c[2].length,a=c[1],o=void 0===c[3]?zA:'"'===c[3]?KA:VA):o===KA||o===VA?o=zA:o===WA||o===HA?o=qA:(o=zA,r=void 0);const h=o===zA&&e[t+1].startsWith("/>")?" ":"";i+=o===qA?s+DA:l>=0?(n.push(a),s.slice(0,l)+RA+s.slice(l)+UA+h):s+UA+(-2===l?t:h)}return[sI(e,i+(e[s]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),n]};class rI{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]=nI(e,t);if(this.el=rI.createElement(c,s),tI.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(n=tI.nextNode())&&a.length<o;){if(1===n.nodeType){if(n.hasAttributes())for(const e of n.getAttributeNames())if(e.endsWith(RA)){const t=l[i++],s=n.getAttribute(e).split(UA),o=/([.?@])?(.*)/.exec(t);a.push({type:1,index:r,name:o[2],strings:s,ctor:"."===o[1]?lI:"?"===o[1]?dI:"@"===o[1]?hI:cI}),n.removeAttribute(e)}else e.startsWith(UA)&&(a.push({type:6,index:r}),n.removeAttribute(e));if(GA.test(n.tagName)){const e=n.textContent.split(UA),t=e.length-1;if(t>0){n.textContent=xA?xA.emptyScript:"";for(let s=0;s<t;s++)n.append(e[s],BA()),tI.nextNode(),a.push({type:2,index:++r});n.append(e[t],BA())}}}else if(8===n.nodeType)if(n.data===LA)a.push({type:2,index:r});else{let e=-1;for(;-1!==(e=n.data.indexOf(UA,e+1));)a.push({type:7,index:r}),e+=UA.length-1}r++}}static createElement(e,t){const s=MA.createElement("template");return s.innerHTML=e,s}}function iI(e,t,s=e,n){if(t===ZA)return t;let r=void 0!==n?s._$Co?.[n]:s._$Cl;const i=jA(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=iI(e,r._$AS(e,t.values),r,n)),t}class oI{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??MA).importNode(t,!0);tI.currentNode=n;let r=tI.nextNode(),i=0,o=0,a=s[0];for(;void 0!==a;){if(i===a.index){let t;2===a.type?t=new aI(r,r.nextSibling,this,e):1===a.type?t=new a.ctor(r,a.name,a.strings,this,e):6===a.type&&(t=new uI(r,this,e)),this._$AV.push(t),a=s[++o]}i!==a?.index&&(r=tI.nextNode(),i++)}return tI.currentNode=MA,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 aI{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,s,n){this.type=2,this._$AH=QA,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=iI(this,e,t),jA(e)?e===QA||null==e||""===e?(this._$AH!==QA&&this._$AR(),this._$AH=QA):e!==this._$AH&&e!==ZA&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>$A(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!==QA&&jA(this._$AH)?this._$AA.nextSibling.data=e:this.T(MA.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=rI.createElement(sI(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new oI(n,this),s=e.u(this.options);e.p(t),this.T(s),this._$AH=e}}_$AC(e){let t=eI.get(e.strings);return void 0===t&&eI.set(e.strings,t=new rI(e)),t}k(e){$A(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 aI(this.O(BA()),this.O(BA()),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 cI{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,s,n,r){this.type=1,this._$AH=QA,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=QA}_$AI(e,t=this,s,n){const r=this.strings;let i=!1;if(void 0===r)e=iI(this,e,t,0),i=!jA(e)||e!==this._$AH&&e!==ZA,i&&(this._$AH=e);else{const n=e;let o,a;for(e=r[0],o=0;o<r.length-1;o++)a=iI(this,n[s+o],t,o),a===ZA&&(a=this._$AH[o]),i||=!jA(a)||a!==this._$AH[o],a===QA?e=QA:e!==QA&&(e+=(a??"")+r[o+1]),this._$AH[o]=a}i&&!n&&this.j(e)}j(e){e===QA?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class lI extends cI{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===QA?void 0:e}}class dI extends cI{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==QA)}}class hI extends cI{constructor(e,t,s,n,r){super(e,t,s,n,r),this.type=5}_$AI(e,t=this){if((e=iI(this,e,t,0)??QA)===ZA)return;const s=this._$AH,n=e===QA&&s!==QA||e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive,r=e!==QA&&(s===QA||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 uI{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){iI(this,e)}}const pI=kA.litHtmlPolyfillSupport;pI?.(rI,aI),(kA.litHtmlVersions??=[]).push("3.3.3");const fI=globalThis;
14
+ /**
15
+ * @license
16
+ * Copyright 2017 Google LLC
17
+ * SPDX-License-Identifier: BSD-3-Clause
18
+ */class gI extends TA{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 aI(t.insertBefore(BA(),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 ZA}}gI._$litElement$=!0,gI.finalized=!0,fI.litElementHydrateSupport?.({LitElement:gI});const mI=fI.litElementPolyfillSupport;mI?.({LitElement:gI}),(fI.litElementVersions??=[]).push("4.2.2");const yI={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"}},wI={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:yI.core,theme:yI.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)"}},bI="--apkt";function vI(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 EI={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]=`${bI}-${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[`${bI}-${t}`]=a)}}(e,t),s},createRootStyles(e,t){const s={...wI,tokens:{...wI.tokens,theme:"light"===e?yI.light:yI.dark}},{cssVariables:n}=EI.createCSSVariables(s),r=EI.assignCSSVariables(n,s),i=EI.generateW3MVariables(t),o=EI.generateW3MOverrides(t),a=EI.generateScaledVariables(t),c=EI.generateBaseVariables(r),l={...r,...c,...i,...o,...a},d=EI.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=vI(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=vI(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=vI(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=vI(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:CI}=EI.createCSSVariables(wI);let NI,AI,II,SI,_I;const OI={"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 TI(e,t="dark"){NI&&document.head.removeChild(NI),NI=document.createElement("style"),NI.textContent=EI.createRootStyles(t,e),document.head.appendChild(NI)}function kI(e="dark"){II&&SI&&NI&&("light"===e?(TI(_I,e),II.removeAttribute("media"),SI.media="enabled"):(TI(_I,e),SI.removeAttribute("media"),II.media="enabled"))}function xI(e){const t=Boolean(e?.["--apkt-font-family"]||e?.["--w3m-font-family"]);return{core:pA`
19
+ ${t?pA``:pA`
20
+ @font-face {
21
+ font-family: 'KHTeka';
22
+ src:
23
+ url(${uA(OI["KHTeka-400-woff2"])}) format('woff2'),
24
+ url(${uA(OI["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(${uA(OI["KHTeka-300-woff2"])}) format('woff2'),
34
+ url(${uA(OI["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(${uA(OI["KHTekaMono-400-woff2"])}) format('woff2'),
43
+ url(${uA(OI["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(${uA(OI["KHTeka-400-woff2"])}) format('woff2'),
52
+ url(${uA(OI["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:pA`
136
+ :root {
137
+ }
138
+ `,light:pA`
139
+ :root {
140
+ }
141
+ `}}const PI=pA`
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
+ `,RI=pA`
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
+ `,UI={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:a.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`},LI={ConnectorExplorerIds:{[a.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[a.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[a.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[a.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[a.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[a.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[UI.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[UI.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[UI.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[UI.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[UI.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[UI.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[UI.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[UI.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[UI.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[UI.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[UI.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[UI.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[UI.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:{[a.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[a.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[a.CONNECTOR_ID.BASE_ACCOUNT]:"bba2c8be-7fd1-463e-42b1-796ecb0ad200",[a.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[a.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[a.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[a.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[a.CONNECTOR_ID.INJECTED]:"Browser Wallet",[a.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[a.CONNECTOR_ID.COINBASE]:"Coinbase",[a.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[a.CONNECTOR_ID.BASE_ACCOUNT]:"Base Account",[a.CONNECTOR_ID.LEDGER]:"Ledger",[a.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[a.CONNECTOR_ID.INJECTED]:"INJECTED",[a.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[a.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[a.CONNECTOR_ID.AUTH]:"AUTH",[UI.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]},DI={getCaipTokens(e){if(!e)return;const t={};return Object.entries(e).forEach((([e,s])=>{t[`${UI.EIP155}:${e}`]=s})),t},isLowerCaseMatch:(e,t)=>e?.toLowerCase()===t?.toLowerCase(),getActiveNamespaceConnectedToAuth(){const e=as.state.activeChain;return a.AUTH_CONNECTOR_SUPPORTED_CHAINS.find((t=>Ot.getConnectorId(t)===a.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 a.CHAIN.EVM;const[t]=e.split(":");return t},getOtherAuthNamespaces(e){if(!e)return[];const t=a.AUTH_CONNECTOR_SUPPORTED_CHAINS.filter((t=>t!==e));return t},getConnectorStorageInfo(e,t){const s=ue.getConnections()[t]??[];return{hasDisconnected:ue.isConnectorDisconnected(e,t),hasConnected:s.some((t=>DI.isLowerCaseMatch(t.connectorId,e)))}}},MI={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 ${D()?window.origin:"unknown"} is not in your allow list. Please update your allowed domains at https://dashboard.reown.com. [PID: ${je.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"}}},BI={TOKEN_ADDRESSES_BY_SYMBOL:{USDC:{8453:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",84532:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"}},getTokenSymbolByAddress(e){if(!e)return;const[t]=Object.entries(BI.TOKEN_ADDRESSES_BY_SYMBOL).find((([t,s])=>Object.values(s).includes(e)))??[];return t}};var jI={exports:{}};function $I(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var FI=function(e,t,s){var n=s&&s.stringify||$I;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 qI=FI;jI.exports=YI;const WI=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||{},HI={mapHttpRequest:sS,mapHttpResponse:sS,wrapRequestSerializer:nS,wrapResponseSerializer:nS,wrapErrorSerializer:nS,req:sS,res:sS,err:eS,errWithCause:eS};function zI(e,t){return"silent"===e?1/0:t.levels.values[e]}const VI=Symbol("pino.logFuncs"),KI=Symbol("pino.hierarchy"),GI={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function JI(e,t){const s={logger:t,parent:e[KI]};t[KI]=s}function YI(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||WI;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=rS),function(e,t,s){const n={};t.forEach((e=>{n[e]=s[e]?s[e]:WI[e]||WI[GI[e]||"log"]||rS})),e[VI]=n}(l,a,s),JI({},l),Object.defineProperty(l,"levelVal",{get:function(){return zI(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,XI(this,d,l,"error"),XI(this,d,l,"fatal"),XI(this,d,l,"warn"),XI(this,d,l,"info"),XI(this,d,l,"debug"),XI(this,d,l,"trace"),o.forEach((e=>{XI(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:tS(e),messageKey:e.messageKey||"msg",onChild:e.onChild||rS};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,ZI([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=QI([].concat(e._logEvent.bindings,i)))}d.prototype=this;const u=new d(this);return JI(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({},YI.levels.values,t),n=Object.assign({},YI.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=rS,l.serializers=n,l._serialize=r,l._stdErrSerialize=i,l.child=function(...e){return h.call(this,d,...e)},t&&(l._logEvent=QI()),l}function XI(e,t,s,n){if(Object.defineProperty(e,n,{value:zI(e.level,s)>zI(n,s)?rS:s[VI][n],writable:!0,enumerable:!0,configurable:!0}),e[n]===rS){if(!t.transmit)return;const r=zI(t.transmit.level||e.level,s);if(zI(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)===WI?WI:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(t.serialize&&(ZI(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?qI(a.shift(),a):void 0}else"string"==typeof c&&(c=qI(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=zI(r,s),c=zI(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||ZI(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=QI(l)}(this,{ts:i,methodLevel:n,methodValue:c,transmitLevel:r,transmitValue:s.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:zI(e._level,s)},o,l)}}}(e[VI][n])}(e,t,s,n);const r=function(e){const t=[];e.bindings&&t.push(e.bindings);let s=e[KI];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 ZI(e,t,s,n){for(const r in e)if(n&&e[r]instanceof Error)e[r]=YI.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 QI(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function eS(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 tS(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?iS:oS}function sS(){return{}}function nS(e){return e}function rS(){}function iS(){return!1}function oS(){return Date.now()}YI.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"}},YI.stdSerializers=HI,YI.stdTimeFunctions=Object.assign({},{nullTime:iS,epochTime:oS,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),jI.exports.default=YI,jI.exports.pino=YI;const aS="info",cS=1024e3;var lS=Object.defineProperty,dS=(e,t,s)=>((e,t,s)=>t in e?lS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class hS{constructor(e){dS(this,"nodeValue"),dS(this,"sizeInBytes"),dS(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 uS{constructor(e){dS(this,"lengthInNodes"),dS(this,"sizeInBytes"),dS(this,"head"),dS(this,"tail"),dS(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new hS(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 pS(e){return"string"==typeof e?e:(e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t)))(e)||""}var fS=Object.defineProperty,gS=(e,t,s)=>((e,t,s)=>t in e?fS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class mS{constructor(e,t=cS){gS(this,"logs"),gS(this,"level"),gS(this,"levelValue"),gS(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=jI.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new uS(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===jI.exports.levels.values.error?console.error(e):t===jI.exports.levels.values.warn?console.warn(e):t===jI.exports.levels.values.debug?console.debug(e):t===jI.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(pS({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 uS(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(pS({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var yS=Object.defineProperty,wS=(e,t,s)=>((e,t,s)=>t in e?yS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class bS{constructor(e,t=cS){wS(this,"baseChunkLogger"),this.baseChunkLogger=new mS(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 vS=Object.defineProperty,ES=(e,t,s)=>((e,t,s)=>t in e?vS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class CS{constructor(e,t=cS){ES(this,"baseChunkLogger"),this.baseChunkLogger=new mS(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 NS=Object.defineProperty,AS=Object.defineProperties,IS=Object.getOwnPropertyDescriptors,SS=Object.getOwnPropertySymbols,_S=Object.prototype.hasOwnProperty,OS=Object.prototype.propertyIsEnumerable,TS=(e,t,s)=>t in e?NS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,kS=(e,t)=>{for(var s in t||(t={}))_S.call(t,s)&&TS(e,s,t[s]);if(SS)for(var s of SS(t))OS.call(t,s)&&TS(e,s,t[s]);return e},xS=(e,t)=>AS(e,IS(t));function PS(e){var t;if(typeof e.loggerOverride<"u"&&"string"!=typeof e.loggerOverride)return{logger:e.loggerOverride,chunkLoggerController:null};const s=xS(kS({},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 bS(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:jI.exports(xS(kS({},e.opts),{level:"trace",browser:xS(kS({},null==(s=e.opts)?void 0:s.browser),{write:e=>n.write(e)})})),chunkLoggerController:n}}(xS(kS({},e),{opts:s})):function(e){var t,s;const n=new CS(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:jI.exports(xS(kS({},e.opts),{level:"trace",browser:xS(kS({},null==(s=e.opts)?void 0:s.browser),{write:e=>n.write(e)})}),n),chunkLoggerController:n}}(xS(kS({},e),{opts:s}))}const RS={createLogger(e,t="error"){const s=function(e){return xS(kS({},e),{level:e?.level||aS})}({level:t}),{logger:n}=PS({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}},US="2.56.3";let LS=({docsBaseUrl:e,docsPath:t="",docsSlug:s})=>t?`${e??"https://viem.sh"}${t}${s?`#${s}`:""}`:void 0,DS=`viem@${US}`;class MS extends Error{constructor(e,t={}){const s=t.cause instanceof MS?t.cause.details:t.cause?.message?t.cause.message:t.details,n=t.cause instanceof MS&&t.cause.docsPath||t.docsPath,r=LS?.({...t,docsPath:n});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...r?[`Docs: ${r}`]:[],...s?[`Details: ${s}`]:[],...DS?[`Version: ${DS}`]:[]].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=US}walk(e){return BS(this,e)}}function BS(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?BS(e.cause,t):t?null:e}class jS 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 $S=(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 FS(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 qS(e){return"object"==typeof e&&null!==e&&"name"in e&&"AbortError"===e.name}const WS=e=>{try{const t=new URL(e);return t.username||t.password?(t.username="",t.password="",t.toString()):e}catch{return e}};class HS extends MS{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: ${WS(i)}`,e&&`Request body: ${$S(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 zS extends MS{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 VS extends MS{constructor({body:e,error:t,url:s}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${WS(s)}`,`Request body: ${$S(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 KS extends MS{constructor({body:e,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${WS(t)}`,`Request body: ${$S(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=t}}class GS extends MS{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 VS?e.code:t??-1}}class JS extends GS{constructor(e,t){super(e,t),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}}class YS extends GS{constructor(e){super(e,{code:YS.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(YS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class XS extends GS{constructor(e){super(e,{code:XS.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(XS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class ZS extends GS{constructor(e,{method:t}={}){super(e,{code:ZS.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}}Object.defineProperty(ZS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class QS extends GS{constructor(e){super(e,{code:QS.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join("\n")})}}Object.defineProperty(QS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class e_ extends GS{constructor(e){super(e,{code:e_.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(e_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class t_ extends GS{constructor(e){super(e,{code:t_.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join("\n")})}}Object.defineProperty(t_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class s_ extends GS{constructor(e){super(e,{code:s_.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(s_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class n_ extends GS{constructor(e){super(e,{code:n_.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(n_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class r_ extends GS{constructor(e){super(e,{code:r_.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(r_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class i_ extends GS{constructor(e,{method:t}={}){super(e,{code:i_.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(i_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class o_ extends GS{constructor(e){super(e,{code:o_.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(o_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class a_ extends GS{constructor(e){super(e,{code:a_.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(a_,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class c_ extends JS{constructor(e){super(e,{code:c_.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(c_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class l_ extends JS{constructor(e){super(e,{code:l_.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(l_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class d_ extends JS{constructor(e,{method:t}={}){super(e,{code:d_.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(d_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class h_ extends JS{constructor(e){super(e,{code:h_.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(h_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class u_ extends JS{constructor(e){super(e,{code:u_.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(u_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class p_ extends JS{constructor(e){super(e,{code:p_.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(p_,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class f_ extends JS{constructor(e){super(e,{code:f_.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(f_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class g_ extends JS{constructor(e){super(e,{code:g_.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(g_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class m_ extends JS{constructor(e){super(e,{code:m_.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(m_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class y_ extends JS{constructor(e){super(e,{code:y_.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(y_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class w_ extends JS{constructor(e){super(e,{code:w_.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(w_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class b_ extends JS{constructor(e){super(e,{code:b_.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(b_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class v_ extends JS{constructor(e){super(e,{code:v_.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(v_,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class E_ extends JS{constructor(e){super(e,{code:E_.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}}Object.defineProperty(E_,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});class C_ extends GS{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}class N_ extends MS{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(N_,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(N_,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});const A_=new Map;function I_({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=()=>A_.delete(t),a=()=>A_.get(t)||[],c=e=>A_.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 S_(e,{signal:t}={}){return new Promise(((s,n)=>{if(t?.aborted)return void n(FS(t));const r=()=>t?.removeEventListener("abort",o),i=setTimeout((()=>{r(),s()}),e),o=()=>{clearTimeout(i),r(),n(FS(t))};t?.addEventListener("abort",o,{once:!0})}))}function __(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(FS(r));try{const t=await e();i(t)}catch(e){if(r?.aborted)return void o(FS(r));if(qS(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 S_(s,{signal:r})}catch(e){return void o(e)}return a({count:c+1})})({error:e});o(e)}};a().catch(o)}))}const O_=256;let T_,k_=O_;const x_=new jS(8192);function P_(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 i_(new Error("method not supported"),{method:d});if(i?.include&&!i.include.includes(d))throw new i_(new Error("method not supported"),{method:d});if(c?.aborted)throw FS(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}.${$S(s)}`):void 0;return function(e,{enabled:t=!0,id:s}){if(!t||!s)return e();if(x_.get(s))return x_.get(s);const n=e().finally((()=>x_.delete(s)));return x_.set(s,n),n}((()=>__((async()=>{try{return await e(s,c?{signal:c}:void 0)}catch(e){if(c?.aborted)throw FS(c);if(qS(e))throw e;const t=e;switch(t.code){case YS.code:throw new YS(t);case XS.code:throw new XS(t);case ZS.code:throw new ZS(t,{method:s.method});case QS.code:throw new QS(t);case e_.code:throw new e_(t);case t_.code:throw new t_(t);case s_.code:throw new s_(t);case n_.code:throw new n_(t);case r_.code:throw new r_(t);case i_.code:throw new i_(t,{method:s.method});case o_.code:throw new o_(t);case a_.code:throw new a_(t);case c_.code:throw new c_(t);case l_.code:throw new l_(t);case d_.code:throw new d_(t);case h_.code:throw new h_(t);case u_.code:throw new u_(t);case p_.code:throw new p_(t);case f_.code:throw new f_(t);case g_.code:throw new g_(t);case m_.code:throw new m_(t);case y_.code:throw new y_(t);case w_.code:throw new w_(t);case b_.code:throw new b_(t);case v_.code:throw new v_(t);case 5e3:throw new c_(t);case E_.code:throw new E_(t);default:if(e instanceof MS)throw e;throw new C_(t)}}}),{delay:({count:e,error:t})=>{if(t&&t instanceof HS){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(qS(e))return!1;if("code"in e&&"number"==typeof e.code)return-1===e.code||(e.code===o_.code||(e.code===e_.code||429===e.code));if(e instanceof HS&&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 R_(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const U_=R_(),L_=10485760;function D_(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??L_,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&&qS(e))return void i(t);i(e)}finally{clearTimeout(o)}})()}))}((async({signal:e})=>{const t={...d,body:Array.isArray(r)?$S(r.map((e=>({jsonrpc:"2.0",id:e.id??U_.take(),...e})))):$S({jsonrpc:"2.0",id:r.id??U_.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 KS({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 zS({maxSize:t,size:e})}if(!e.body){const s=await e.text(),n=(new TextEncoder).encode(s).length;if(n>t)throw new zS({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 zS({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 HS({body:r,details:$S(t.error)||e.statusText,headers:e.headers,status:e.status,url:s})}return t}catch(e){if(p?.aborted)throw FS(p);if(qS(e))throw e;if(e instanceof HS)throw e;if(e instanceof zS)throw e;if(e instanceof KS)throw e;throw new HS({body:r,cause:e,url:s})}}}}function M_({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(!T_||k_+e>2*O_){T_="",k_=0;for(let e=0;e<O_;e++)T_+=(256+256*Math.random()|0).toString(16).substring(1)}return T_.substring(k_,k_+++e)}();return{config:{key:e,methods:t,name:s,request:n,retryCount:r,retryDelay:i,timeout:o,type:a},request:P_(n,{methods:t,retryCount:r,retryDelay:i,uid:l}),value:c}}function B_(e,t={}){const{key:s="fallback",name:n="Fallback",rank:r=!1,shouldThrow:i=j_,retryCount:o,retryDelay:a}=t;return({chain:t,pollingInterval:c=4e3,timeout:l,...d})=>{let h=e,u=()=>{};const p=M_({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 S_(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 j_(e){return!(!("code"in e)||"number"!=typeof e.code||e.code!==r_.code&&e.code!==c_.code&&e.code!==E_.code&&!N_.nodeMessage.test(e.message)&&5e3!==e.code)}class $_ extends MS{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 F_=0;const q_=new WeakMap;function W_(e){if(!e)return"default";const t=q_.get(e);if(void 0!==t)return t;const s=F_++;return q_.set(e,s),s}function H_(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 $_;const E=D_(v,{fetchFn:n,fetchOptions:r,maxResponseBodySize:o,onRequest:l,onResponse:d,timeout:b});return M_({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}=I_({id:`${v}.${W_(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 VS({body:r,error:a,url:v});return c},retryCount:w,retryDelay:h,timeout:b,type:"http"},{fetchOptions:r,url:v})}}function z_(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 V_=["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"],K_={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:a.CHAIN.EVM},getCaipNetworkId(e){return this.isCaipNetwork(e)?e.caipNetworkId:`${a.CHAIN.EVM}:${e.id}`},getDefaultRpcUrl(e,t,s){const n=e.rpcUrls?.default?.http?.[0];return V_.includes(t)?z_(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:LI.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=>K_.extendCaipNetwork(e,{customNetworkImageUrls:t,customRpcUrls:n,projectId:s}))),getViemTransport(e,t,s){const n=[];return s?.forEach((e=>{n.push(H_(e.url,e.config))})),V_.includes(e.caipNetworkId)&&n.push(H_(z_(e.caipNetworkId,t),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),e?.rpcUrls?.default?.http?.forEach((e=>{n.push(H_(e))})),B_(n)},extendWagmiTransports(e,t,s){if(V_.includes(e.caipNetworkId)){return B_([s,H_(this.getDefaultRpcUrl(e,e.caipNetworkId,t))])}return s},getUnsupportedNetwork:e=>({id:e.split(":")[1],caipNetworkId:e,name:a.UNSUPPORTED_NETWORK_NAME,chainNamespace:e.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}),getCaipNetworkFromStorage(e){const t=ue.getActiveCaipNetworkId(),s=as.getAllRequestedCaipNetworks(),n=Array.from(as.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 G_=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 J_(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 Y_="2.56.3";let X_=({docsBaseUrl:e,docsPath:t="",docsSlug:s})=>t?`${e??"https://viem.sh"}${t}${s?`#${s}`:""}`:void 0,Z_=`viem@${Y_}`;class Q_ extends Error{constructor(e,t={}){const s=t.cause instanceof Q_?t.cause.details:t.cause?.message?t.cause.message:t.details,n=t.cause instanceof Q_&&t.cause.docsPath||t.docsPath,r=X_?.({...t,docsPath:n});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...r?[`Docs: ${r}`]:[],...s?[`Details: ${s}`]:[],...Z_?[`Version: ${Z_}`]:[]].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=Y_}walk(e){return eO(this,e)}}function eO(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?eO(e.cause,t):t?null:e}class tO extends Q_{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 sO(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 tO({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 tO({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 nO extends Q_{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 rO extends Q_{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function iO(e,{size:t}){if(J_(e)>t)throw new rO({givenSize:J_(e),maxSize:t})}const oO=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function aO(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 nO({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?sO(a,{size:n}):a}(e,t):"string"==typeof e?function(e,t={}){const s=lO.encode(e);return cO(s,t)}(e,t):"boolean"==typeof e?function(e,t={}){const s=`0x${Number(e)}`;if("number"==typeof t.size)return iO(s,{size:t.size}),sO(s,{size:t.size});return s}(e,t):cO(e,t)}function cO(e,t={}){let s="";for(let t=0;t<e.length;t++)s+=oO[e[t]];const n=`0x${s}`;return"number"==typeof t.size?(iO(n,{size:t.size}),sO(n,{dir:"right",size:t.size})):n}const lO=new TextEncoder;const dO=4902,hO=5e3,uO=32603;class pO extends eA{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new nA({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=>pe.createAccount({caipAddress:t,type:"bip122"===e?"payment":"eoa"})))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&he.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};const t=as.getAccountData();if(t?.balanceLoading&&e.chainId===as.state.activeCaipNetwork?.id)return{balance:t?.balance||"0.00",symbol:t?.balanceSymbol||""};const s=(await as.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(as.state.activeCaipNetwork?.chainNamespace===a.CHAIN.SOLANA){r=(await t.request({method:"solana_signMessage",params:{message:G_.encode((new TextEncoder).encode(s)),pubkey:n}},as.state.activeCaipNetwork?.caipNetworkId)).signature}else r=await t.request({method:"personal_sign",params:[s,n]},as.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===a.CHAIN.EVM)try{await(s.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:aO(t.id)}]}))}catch(e){if(e.code===dO||e.code===uO||e.code===hO||e?.data?.originalError?.code===dO)try{await(s.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:aO(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 fO=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication","headless"],gO={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?he.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?he.DEFAULT_REMOTE_FEATURES.socials:"boolean"==typeof e?!!e&&he.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?he.DEFAULT_REMOTE_FEATURES.swaps:"boolean"==typeof e?!!e&&he.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?he.DEFAULT_REMOTE_FEATURES.onramp:"boolean"==typeof e?!!e&&he.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?he.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?he.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:()=>he.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:()=>he.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:()=>he.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?he.DEFAULT_REMOTE_FEATURES.reownAuthentication:Boolean(e)},headless:{apiFeatureName:"headless",localFeatureName:"headless",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:()=>he.DEFAULT_REMOTE_FEATURES.headless}},mO={localSettingsOverridden:new Set,getApiConfig:(e,t)=>t?.find((t=>t.id===e)),addWarning(e,t){if(void 0!==e){const e=gO[t],s=e.isLegacy?`"features.${e.localFeatureName}" (now "${t}")`:`"features.${t}"`;this.localSettingsOverridden.add(s)}},processFeature(e,t,s,n,r){const i=gO[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)=>gO[e].processApi(t),processFallbackFeature:(e,t)=>gO[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 gt.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?he.DEFAULT_REMOTE_FEATURES:he.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const e of fO){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),he.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.`;oA.open({debugMessage:MI.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(e)},"warning")}return i}};class yO{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(e,t)=>{if(e){const s=as.getCaipNetworks(e)?.find((e=>e.id===t));if(s)return s;const n=as.getNetworkData(e)?.caipNetwork;if(n)return n;const r=as.getRequestedCaipNetworks(e);return r.filter((t=>t.chainNamespace===e))?.[0]}return as.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const e=this.getCaipNetwork();if(e)return e.id},this.getCaipNetworks=e=>as.getCaipNetworks(e),this.getActiveChainNamespace=()=>as.state.activeChain,this.setRequestedCaipNetworks=(e,t)=>{as.setRequestedCaipNetworks(e,t)},this.getApprovedCaipNetworkIds=()=>as.getAllApprovedCaipNetworkIds(),this.getCaipAddress=e=>as.state.activeChain!==e&&e?as.state.chains.get(e)?.accountState?.caipAddress:as.state.activeCaipAddress,this.setClientId=e=>{Ve.setClientId(e)},this.getProvider=e=>Zt.getProvider(e),this.getProviderType=e=>Zt.getProviderId(e),this.getPreferredAccountType=e=>xt(e),this.setCaipAddress=(e,t,s=!1)=>{as.setAccountProp("caipAddress",e,t,s),as.setAccountProp("address",pe.getPlainAddress(e),t,s)},this.setBalance=(e,t,s)=>{as.setAccountProp("balance",e,s),as.setAccountProp("balanceSymbol",t,s)},this.setProfileName=(e,t)=>{as.setAccountProp("profileName",e,t)},this.setProfileImage=(e,t)=>{as.setAccountProp("profileImage",e,t)},this.setUser=(e,t)=>{as.setAccountProp("user",e,t)},this.resetAccount=e=>{as.resetAccount(e)},this.setCaipNetwork=e=>{as.setActiveCaipNetwork(e)},this.setCaipNetworkOfNamespace=(e,t)=>{as.setChainNetworkData(t,{caipNetwork:e})},this.setStatus=(e,t)=>{as.setAccountProp("status",e,t),Ot.isConnected()?ue.setConnectionStatus("connected"):ue.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=e=>as.getAccountData(e)?.address,this.setConnectors=e=>{const t=[...Ot.state.allConnectors,...e];Ot.setConnectors(t)},this.setConnections=(e,t)=>{ue.setConnections(e,t),qt.setConnections(e,t)},this.fetchIdentity=e=>Ve.fetchIdentity(e),this.getReownName=e=>KN.getNamesForAddress(e),this.getConnectors=()=>Ot.getConnectors(),this.getConnectorImage=e=>rt.getConnectorImage(e),this.getConnections=e=>this.remoteFeatures.multiWallet?Rt.getConnectionsData(e).connections:(oA.open(a.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=e=>this.remoteFeatures.multiWallet?Rt.getConnectionsData(e).recentConnections:(oA.open(a.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async e=>{this.remoteFeatures.multiWallet?await qt.switchConnection(e):oA.open(a.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info")},this.deleteConnection=e=>{this.remoteFeatures.multiWallet?(ue.deleteAddressFromConnection(e),qt.syncStorageConnections()):oA.open(a.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info")},this.setConnectedWalletInfo=(e,t)=>{const s=Zt.getProviderId(t),n=e?{...e,type:s}:void 0;as.setAccountProp("connectedWalletInfo",n,t)},this.getIsConnectedState=()=>Boolean(as.state.activeCaipAddress),this.addAddressLabel=(e,t,s)=>{const n=as.getAccountData(s)?.addressLabels||{};as.setAccountProp("addressLabels",{...n,[e]:t},s)},this.removeAddressLabel=(e,t)=>{const s=as.getAccountData(t)?.addressLabels||{};as.setAccountProp("addressLabels",{...s,[e]:void 0},t)},this.getAddress=e=>{const t=e||as.state.activeChain;return as.getAccountData(t)?.address},this.resetNetwork=e=>{as.resetNetwork(e)},this.addConnector=e=>{Ot.addConnector(e)},this.resetWcConnection=()=>{qt.resetWcConnection()},this.setAddressExplorerUrl=(e,t)=>{as.setAccountProp("addressExplorerUrl",e,t)},this.setSmartAccountDeployed=(e,t)=>{as.setAccountProp("smartAccountDeployed",e,t)},this.setPreferredAccountType=(e,t)=>{as.setAccountProp("preferredAccountType",e,t)},this.setEIP6963Enabled=e=>{je.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&&!yt.hasInjectedConnectors()&&gt.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1,fetchRecommendedWallets:!0}),je.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),e.basic||e.manualWCControl||(this.remoteFeatures=await mO.fetchRemoteFeatures(e)),await gt.fetchUsage(),je.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&fs.setOnrampProviders(this.remoteFeatures.onramp),(je.state.remoteFeatures?.email||Array.isArray(je.state.remoteFeatures?.socials)&&je.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins(),je.state.features?.reownAuthentication||je.state.remoteFeatures?.reownAuthentication){const{ReownAuthentication:e}=await Promise.resolve().then((function(){return require("./features-fa5c5622.cjs")})),t=je.state.siwx;t instanceof e||(t&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),je.setSIWX(new e))}}async openSend(e){const t=e.namespace||as.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=as.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=BI.getTokenSymbolByAddress(e.assetAddress);t&&await gt.fetchTokenImages([t])}catch{}return await ds.open({view:"WalletSend",data:{send:e}}),new Promise(((e,t)=>{const s=ss.subscribeKey("hash",(t=>{t&&(r(),e({hash:t}))})),n=ds.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 gt.fetchAllowedOrigins();if(!pe.isClient())return;const t=window.location.origin;ZN.isOriginAllowed(t,e,a.DEFAULT_ALLOWED_ANCESTORS)||oA.open(MI.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":oA.open(MI.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const t=e.cause instanceof Error?e.cause:e;oA.open({displayMessage:MI.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:MI.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,ht.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(){Jt.initialize(this.chainAdapters)}initializeThemeController(e){e.themeMode&&Nt.setThemeMode(e.themeMode),e.themeVariables&&Nt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");as.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const t=this.getDefaultNetwork();t&&as.setActiveCaipNetwork(t)}initializeConnectionController(e){qt.initialize(e.adapters??[]),qt.setWcBasic(e.basic??!1)}initializeConnectorController(){Ot.initialize(this.chainNamespaces)}initializeProjectSettings(e){je.setProjectId(e.projectId),je.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){je.setDebug(!1!==e.debug),je.setEnableWalletGuide(!1!==e.enableWalletGuide),je.setEnableWallets(!1!==e.enableWallets),je.setEIP6963Enabled(!1!==e.enableEIP6963),je.setEnableCoinbase(!1!==e.enableCoinbase),je.setEnableNetworkSwitch(!1!==e.enableNetworkSwitch),je.setEnableReconnect(!1!==e.enableReconnect),je.setEnableMobileFullScreen(!0===e.enableMobileFullScreen),je.setCoinbasePreference(e.coinbasePreference),je.setEnableAuthLogger(!1!==e.enableAuthLogger),je.setCustomRpcUrls(e.customRpcUrls),je.setEnableEmbedded(e.enableEmbedded),je.setAllWallets(e.allWallets),je.setIncludeWalletIds(e.includeWalletIds),je.setExcludeWalletIds(e.excludeWalletIds),je.setFeaturedWalletIds(e.featuredWalletIds),je.setTokens(e.tokens),je.setTermsConditionsUrl(e.termsConditionsUrl),je.setPrivacyPolicyUrl(e.privacyPolicyUrl),je.setCustomWallets(e.customWallets),je.setFeatures(e.features),je.setAllowUnsupportedChain(e.allowUnsupportedChain),je.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),je.setPreferUniversalLinks(e.experimental_preferUniversalLinks),je.setDefaultAccountTypes(e.defaultAccountTypes);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),je.setMetadata(e.metadata),je.setDisableAppend(e.disableAppend),je.setEnableEmbedded(e.enableEmbedded),je.setSIWX(e.siwx),this.features=je.state.features??{},!e.projectId)return void oA.open(MI.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");const s=e.adapters?.find((e=>e.namespace===a.CHAIN.EVM));if(s&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");je.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return pe.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=K_.getUnsupportedNetwork(`${t}:${e}`);as.setActiveCaipNetwork(s)}}getDefaultNetwork(){return K_.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return K_.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return K_.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?K_.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=as.state.chains.get(e)?.accountState?.caipAddress;return!r&&je.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=as.state.activeChain,t=this.getAdapter(e),s=this.getCaipNetwork(e)?.id,n=qt.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),ue.setConnectedNamespaces([...as.state.chains.keys()]),await this.syncWalletConnectAccount(),await sA.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=as.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})),ue.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||as.state.activeChain,i=Ot.getConnectorId(r),o=t===a.CONNECTOR_ID.AUTH||i===a.CONNECTOR_ID.AUTH,c=t===a.CONNECTOR_ID.WALLET_CONNECT||i===a.CONNECTOR_ID.WALLET_CONNECT;try{const e=Array.from(as.state.chains.keys());let r=s?[s]:e;(c||o)&&(r=e);const i=r.map((async e=>{const s=Ot.getConnectorId(e),r=t||s,i=await this.disconnectConnector(e,r);i&&(o&&ue.deleteConnectedSocialProvider(),i.connections.forEach((t=>{ue.addDisconnectedConnectorId(t.connectorId,e)}))),n&&this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})})),a=await Promise.allSettled(i);ss.resetSend(),qt.resetWcConnection(),sA.getSIWX()?.signOutOnDisconnect&&await sA.clearSessions(),Ot.setFilterByNamespace(void 0),qt.syncStorageConnections();const l=a.filter((e=>"rejected"===e.status));if(l.length>0)throw new Error(l.map((e=>e.reason.message)).join(", "));ht.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=as.state.activeChain,s=this.getAdapter(as.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:Zt.getProvider(t)}));return r?.signature||""},sendTransaction:async e=>{const t=e.chainNamespace;if(!t)throw new Error("sendTransaction: namespace not found");if(he.SEND_SUPPORTED_NAMESPACES.includes(t)){const s=this.getAdapter(t);if(!s)throw new Error("sendTransaction: adapter not found");const n=Zt.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===a.CHAIN.EVM){const s=this.getAdapter(t);if(!s)throw new Error("estimateGas: adapter is required but got undefined");const n=Zt.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=as.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=as.getAccountData();return s?.profileImage||!1},getEnsAddress:async e=>await ZN.resolveReownName(e),writeContract:async e=>{const t=as.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=Zt.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=as.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=Zt.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(as.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(as.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(as.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(as.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(as.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(as.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)}},qt.setClient(this.connectionControllerClient)}async onConnectExternal(e){const t=as.state.activeChain,s=e.chain||t,n=this.getAdapter(s);let r=!0;if(e.type===UI.CONNECTOR_TYPE_AUTH){const s=a.AUTH_CONNECTOR_SUPPORTED_CHAINS.some((e=>Ot.getConnectorId(e)===a.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,c=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(c)return ue.addConnectedNamespace(s),this.syncProvider({...c,chainNamespace:s}),this.setStatus("connected",s),this.syncConnectedWalletInfo(s),ue.removeDisconnectedConnectorId(e.id,s),{address:c.address,connectedCaipNetwork:o}}async connectInactiveNamespaces(e,t){const s=e.type===UI.CONNECTOR_TYPE_AUTH,n=DI.getOtherAuthNamespaces(t?.connectedCaipNetwork?.chainNamespace),r=as.state.activeCaipNetwork,i=this.getAdapter(r?.chainNamespace);s&&(await Promise.all(n.map((async t=>{try{const s=Zt.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]}))&&(ue.addConnectedNamespace(t),ue.removeDisconnectedConnectorId(e.id,t),this.setStatus("connected",t),this.syncConnectedWalletInfo(t))}catch(e){oA.warn(MI.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,MI.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(t,e instanceof Error?e.message:void 0),MI.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}}))),r&&await(i?.switchNetwork({caipNetwork:r})))}getApprovedCaipNetworksData(){if(Zt.getProviderId(as.state.activeChain)===UI.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=Zt.getProviderId(t);if(e.chainNamespace===as.state.activeChain){const s=this.getAdapter(t);await(s?.switchNetwork({caipNetwork:e}))}else if(this.setCaipNetwork(e),s===UI.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}=T.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 pO({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=ue.getConnectionStatus();!1===je.state.enableReconnect?this.setStatus("disconnected",e):"connected"===s?this.setStatus("connecting",e):"disconnected"===s?(ue.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=as.state.activeChain===e,i=as.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(qt.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=as.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=as.state.activeChain===e;n?.provider&&(this.syncProvider({id:n.id,type:n.type,provider:n?.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const i=as.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),ue.addConnectedNamespace(e)}))}async handlePreviousConnectorConnection(e){const t=e?.chain,s=e?.id,n=Ot.getConnectorId(t),r=je.state.remoteFeatures?.multiWallet,i=t&&s&&n&&n!==s&&!r;try{i&&await qt.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=>qt.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()||ue.deleteRecentWallet();const t=ue.getRecentWallet();ht.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:pe.isMobile()?"mobile":"qrcode",name:t?.name||"Unknown",reconnect:!0,view:vt.state.view,walletRank:t?.order}})}async syncNamespaceConnection(e){try{e===a.CHAIN.EVM&&pe.isSafeApp()&&Ot.setConnectorId(a.CONNECTOR_ID.SAFE,e);const t=Ot.getConnectorId(e);switch(this.setStatus("connecting",e),t){case a.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case a.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||{};as.resetAccount(t),as.resetNetwork(t),ue.removeConnectedNamespace(t);const n=Array.from(as.state.chains.keys());(t?[t]:n).forEach((e=>ue.addDisconnectedConnectorId(Ot.getConnectorId(e)||"",e))),Ot.removeConnectorId(t),Zt.resetChain(t),this.setUser(null,t),this.setStatus("disconnected",t),this.setConnectedWalletInfo(null,t),!1!==s&&ds.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=Ot.getConnectorId(e),r=Ot.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),ht.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:n.address,properties:{method:"browser",name:r.info?.name||r.name||"Unknown",reconnect:!0,view:vt.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=as.state.activeCaipNetwork?.id,i=n.find((e=>{const{chainId:t}=T.parseCaipAddress(e);return t===r?.toString()}))||n[0];if(i){const e=T.validateCaipAddress(i),{chainId:n,address:r}=T.parseCaipAddress(e);if(Zt.setProviderId(t,UI.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&as.state.activeCaipNetwork&&s.namespace!==a.CHAIN.EVM){const e=s.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:as.state.activeCaipNetwork});Zt.setProvider(t,e)}else Zt.setProvider(t,this.universalProvider);Ot.setConnectorId(a.CONNECTOR_ID.WALLET_CONNECT,t),ue.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),as.setApprovedCaipNetworksData(t,{approvedCaipNetworkIds:o.approvedCaipNetworkIds,supportsAllNetworks:o.supportsAllNetworks})}));await Promise.all(t)}syncProvider({type:e,provider:t,id:s,chainNamespace:n}){Zt.setProviderId(n,e),Zt.setProvider(n,t),Ot.setConnectorId(s,n)}async syncAccount(e){const t=e.chainNamespace===as.state.activeChain,s=as.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:n,chainId:r,chainNamespace:i}=e,{chainId:o}=ue.getActiveNetworkProps(),c=s?.id||o,l=as.state.activeCaipNetwork?.name===a.UNSUPPORTED_NETWORK_NAME,d=as.getNetworkProp("supportsAllNetworks",i);if(this.setStatus("connected",i),(!l||d)&&c){let e=this.getCaipNetworks().find((e=>e.id.toString()===c.toString())),o=this.getCaipNetworks().find((e=>e.chainNamespace===i));if(!d&&!e&&!o){const t=this.getApprovedCaipNetworkIds()||[],s=t.find((e=>T.parseCaipNetworkId(e)?.chainId===c.toString())),n=t.find((e=>T.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 l=e||o;l?.chainNamespace===as.state.activeChain?je.state.enableNetworkSwitch&&!je.state.allowUnsupportedChain&&as.state.activeCaipNetwork?.name===a.UNSUPPORTED_NETWORK_NAME?as.showUnsupportedChainUI():this.setCaipNetwork(l):t||s&&this.setCaipNetworkOfNamespace(s,i),this.syncConnectedWalletInfo(i);const h=this.getAddress(i);DI.isLowerCaseMatch(n,h)||this.syncAccountInfo(n,l?.id,i),t?await this.syncBalance({address:n,chainId:l?.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=Ot.getConnectorId(e),s=Zt.getProviderId(e);if(s===UI.CONNECTOR_TYPE_ANNOUNCED||s===UI.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===UI.CONNECTOR_TYPE_WALLET_CONNECT){const t=Zt.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===a.CONNECTOR_ID.COINBASE_SDK||t===a.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=c.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=as.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=RS.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};je.setManualWCControl(Boolean(this.options?.manualWCControl)),this.universalProvider=this.options.universalProvider??await qN.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===je.state.enableReconnect&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach((e=>{ZN.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:e=>{qt.setUri(e)},onConnect:e=>{const{address:t}=pe.getAccount(e[0]);for(const e of this.chainNamespaces)ue.removeDisconnectedConnectorId(a.CONNECTOR_ID.WALLET_CONNECT,e);qt.finalizeWcConnection(t)},onDisconnect:()=>{as.state.noAdapters&&this.resetAccount(e),qt.resetWcConnection()},onChainChanged:t=>{const s=as.state.activeChain,n=s&&Ot.state.activeConnectorIds[s]===a.CONNECTOR_ID.WALLET_CONNECT;if(s===e&&(as.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=as.state.activeChain,n=s&&Ot.state.activeConnectorIds[s]===a.CONNECTOR_ID.WALLET_CONNECT;if(s===e&&(as.state.noAdapters||n)){const e=t?.[0];e&&this.syncAccount({address:e.address,chainId:e.chainId,chainNamespace:e.chainNamespace})}}})}))}createUniversalProvider(){return!this.universalProviderInitPromise&&pe.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){ht.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=as.getAllApprovedCaipNetworkIds(),t=as.getAllRequestedCaipNetworks();return pe.sortRequestedNetworks(e,t).filter((e=>as.isCaipNetworkDisabled(e)))}handleAlertError(e){const t=Object.entries(MI.UniversalProviderErrors).find((([,{message:t}])=>e.message.includes(t))),[s,n]=t??[],{message:r,alertErrorKey:i}=n??{};if(s&&r&&!this.reportedAlertErrors[s]){const e=MI.ALERT_ERRORS[i];e&&(oA.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&&qt.setUri(e.uri);const{isSwap:t,isSend:s}=this.toModalOptions();return t(e)?ds.open({...e,data:{swap:e.arguments}}):s(e)&&e.arguments?this.openSend(e.arguments):ds.open(e)}async close(){await this.injectModalUi(),ds.close()}setLoading(e,t){ds.setLoading(e,t)}async disconnect(e){await qt.disconnect({namespace:e})}getSIWX(){return je.state.siwx}getError(){return""}getChainId(){return as.state.activeCaipNetwork?.id}async switchNetwork(e,{throwOnFailure:t=!1}={}){const s=this.getCaipNetworks().find((t=>t.id===e.id));s?await as.switchActiveNetwork(s,{throwOnFailure:t}):oA.open(MI.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error")}getWalletProvider(){return as.state.activeChain?Zt.state.providers[as.state.activeChain]:null}getWalletProviderType(){return Zt.getProviderId(as.state.activeChain)}subscribeProviders(e){return Zt.subscribeProviders(e)}getThemeMode(){return Nt.state.themeMode}getThemeVariables(){return Nt.state.themeVariables}setThemeMode(e){Nt.setThemeMode(e),kI(Nt.state.themeMode)}setTermsConditionsUrl(e){je.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){je.setPrivacyPolicyUrl(e)}setThemeVariables(e){Nt.setThemeVariables(e),function(e){if(_I=e,AI&&II&&SI){AI.textContent=xI(e).core.cssText,II.textContent=xI(e).dark.cssText,SI.textContent=xI(e).light.cssText;const t=e?.["--apkt-font-family"]||e?.["--w3m-font-family"];t&&(AI.textContent=AI.textContent?.replace("font-family: KHTeka",`font-family: ${t}`),II.textContent=II.textContent?.replace("font-family: KHTeka",`font-family: ${t}`),SI.textContent=SI.textContent?.replace("font-family: KHTeka",`font-family: ${t}`))}NI&&TI(e,"enabled"===SI?.media?"light":"dark")}(Nt.state.themeVariables)}subscribeTheme(e){return Nt.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?qt.subscribe(e):(oA.open(a.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){if(e)return as.state.chains.get(e)?.accountState?.connectedWalletInfo;const t=as.getAccountData();return t?.connectedWalletInfo}getAccount(e){const t=e||as.state.activeChain,s=Ot.getAuthConnector(t),n=as.getAccountData(t),r=ue.getConnectedConnectorId(as.state.activeChain),i=qt.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})=>pe.createAccount({caipAddress:`${t.caipNetworkId}:${e}`,type:s||"eoa",publicKey:n}))):[]}));if(n)return{allAccounts:o,caipAddress:n.caipAddress,address:pe.getPlainAddress(n.caipAddress),isConnected:Boolean(n.caipAddress),status:n.status,embeddedWalletInfo:s&&r===a.CONNECTOR_ID.AUTH?{user:n.user?{...n.user,username:ue.getConnectedSocialUsername()}:void 0,authProvider:n.socialProvider||"email",accountType:xt(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=as.subscribeChainProp("accountState",n,t);s.push(e)}else{const e=as.subscribe(n);s.push(e)}const r=Ot.subscribe(n);return s.push(r),()=>{s.forEach((e=>e()))}}subscribeNetwork(e){return as.subscribe((({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t?.id,caipNetworkId:t?.caipNetworkId})}))}subscribeWalletInfo(e,t){return t?as.subscribeChainProp("accountState",(t=>e(t?.connectedWalletInfo)),t):as.subscribeChainProp("accountState",(t=>e(t?.connectedWalletInfo)))}subscribeShouldUpdateToAddress(e){return as.subscribeChainProp("accountState",(t=>e(t?.shouldUpdateToAddress)))}subscribeCaipNetworkChange(e){return as.subscribeKey("activeCaipNetwork",e)}getState(){return Lt.state}getRemoteFeatures(){return je.state.remoteFeatures}subscribeState(e){return Lt.subscribe(e)}subscribeRemoteFeatures(e){return je.subscribeKey("remoteFeatures",e)}showErrorMessage(e){qe.showError(e)}showSuccessMessage(e){qe.showSuccess(e)}getEvent(){return{...ht.state}}subscribeEvents(e){return ht.subscribe(e)}replace(e){vt.replace(e)}redirect(e){vt.push(e)}popTransactionStack(e){vt.popTransactionStack(e)}isOpen(){return ds.state.open}isTransactionStackEmpty(){return 0===vt.state.transactionStack.length}static getInstance(){return this.instance}updateFeatures(e){je.setFeatures(e)}updateRemoteFeatures(e){je.setRemoteFeatures(e)}updateOptions(e){const t={...je.state||{},...e};je.setOptions(t)}setConnectMethodsOrder(e){je.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){je.setWalletFeaturesOrder(e)}setCollapseWallets(e){je.setCollapseWallets(e)}setSocialsOrder(e){je.setSocialsOrder(e)}getConnectMethodsOrder(){return mt.getConnectOrderMethod(je.state.features,Ot.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))||as.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&&as.removeNetwork(e,t)}}let wO=!1;class bO extends yO{async open(e){Ot.isConnected()||await super.open(e)}async close(){if(await super.close(),this.options.manualWCControl){const e=as.getAccountData(this.activeChainNamespace)?.address;qt.finalizeWcConnection(e)}}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!wO&&pe.isClient()){await Promise.resolve().then((function(){return require("./basic-b777d2b1.cjs")})),await Promise.resolve().then((function(){return require("./w3m-modal-70bcf6d8.cjs")}));if(!document.querySelector("w3m-modal")){const e=document.createElement("w3m-modal");je.state.disableAppend||je.state.enableEmbedded||document.body.insertAdjacentElement("beforeend",e)}wO=!0}}}var vO=Object.freeze({__proto__:null,createAppKit:function(e){return new bO({...e,basic:!0,sdkVersion:"html-core-1.8.19"})},AppKit:bO});exports.A=QA,exports.AdapterController=Jt,exports.AlertController=oA,exports.ApiController=gt,exports.AppKitError=Xe,exports.AssetController=tt,exports.AssetUtil=rt,exports.BalanceUtil=Kt,exports.BlockchainApiController=Ve,exports.CaipNetworksUtil=K_,exports.ChainController=as,exports.ConnectionController=qt,exports.ConnectionControllerUtil=Rt,exports.ConnectorController=Ot,exports.ConnectorUtil=yt,exports.ConstantsUtil=a,exports.ConstantsUtil$1=he,exports.ContractUtil=_,exports.CoreHelperUtil=pe,exports.E=ZA,exports.ErrorUtil=k,exports.EventsController=ht,exports.FetchUtil=De,exports.HelpersUtil=DI,exports.MobileWalletUtil=ot,exports.ModalController=ds,exports.NetworkUtil=c,exports.NumberUtil=N,exports.OptionsController=je,exports.ParseUtil=T,exports.ProviderController=Zt,exports.RouterController=vt,exports.SIWXUtil=sA,exports.SafeLocalStorage=L,exports.SafeLocalStorageKeys=R,exports.SnackController=qe,exports.StorageUtil=ue,exports.SwapApiUtil=Qt,exports.ThemeController=Nt,exports.W3mFrameRpcConstants=be,exports.WalletUtil=mt,exports.addressResolverAbi=[{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"}]}],exports.b=YA,exports.batchGatewayAbi=[{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"}]}],exports.core=vO,exports.css=function(e,...t){return pA(e,...t.map((e=>uA("function"==typeof e?e(CI):e))))},exports.elementStyles=RI,exports.erc1155Abi=[{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"}],exports.erc1271Abi=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],exports.erc20Abi=Re,exports.erc20Abi_bytes32=[{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"}]}],exports.erc4626Abi=[{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"}],exports.erc6492SignatureValidatorAbi=[{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"}],exports.erc721Abi=[{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:[]}],exports.f=_A,exports.formatEther=function(e,t="wei"){return Se(e,Ie.ether-Ie[t])},exports.formatGwei=function(e,t="wei"){return Se(e,Ie.gwei-Ie[t])},exports.formatUnits=Ue,exports.from=_e,exports.fromEther=function(e,t="wei"){return _e(e,Ie.ether-Ie[t])},exports.fromGwei=function(e,t="wei"){return _e(e,Ie.gwei-Ie[t])},exports.getActiveCaipNetwork=Pt,exports.getActiveNetworkTokenAddress=kt,exports.getNativeTokenAddress=function(e){return he.NATIVE_TOKEN_ADDRESS[e]},exports.getPreferredAccountType=xt,exports.i=gI,exports.i$1=pA,exports.initializeTheming=function(e,t="dark"){if(_I=e,AI=document.createElement("style"),II=document.createElement("style"),SI=document.createElement("style"),AI.textContent=xI(e).core.cssText,II.textContent=xI(e).dark.cssText,SI.textContent=xI(e).light.cssText,document.head.appendChild(AI),document.head.appendChild(II),document.head.appendChild(SI),TI(e,t),kI(t),!(e?.["--apkt-font-family"]||e?.["--w3m-font-family"]))for(const[e,t]of Object.entries(OI)){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)}kI(t)},exports.multicall3Abi=[{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"}],exports.proxy=te,exports.resetStyles=PI,exports.subscribe=se,exports.subscribeKey=ie,exports.textResolverAbi=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],exports.u=SA,exports.universalResolverResolveAbi=xe,exports.universalResolverReverseAbi=Pe,exports.vars=CI,exports.w=XA,exports.withErrorBoundary=Qe;