@reown/appkit-cdn 1.6.7-basic-test.8.0 → 1.6.7-core-2.0

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 (254) hide show
  1. package/dist/{add-Bo7hlhOK.js → add-DE6xsvo_.js} +2 -2
  2. package/dist/{add-Bo7hlhOK.js.map → add-DE6xsvo_.js.map} +1 -1
  3. package/dist/{all-wallets-DiYxd6h8.js → all-wallets-CaSXZUWF.js} +2 -2
  4. package/dist/{all-wallets-DiYxd6h8.js.map → all-wallets-CaSXZUWF.js.map} +1 -1
  5. package/dist/{app-store-BwOymb6f.js → app-store-CrDyy3Wa.js} +2 -2
  6. package/dist/{app-store-BwOymb6f.js.map → app-store-CrDyy3Wa.js.map} +1 -1
  7. package/dist/{appkit-7F54kjKy.js → appkit-Cly9g1o7.js} +49893 -55110
  8. package/dist/appkit-Cly9g1o7.js.map +1 -0
  9. package/dist/appkit.js +8 -8
  10. package/dist/{apple-2YTcD6RU.js → apple-BbOPLgIX.js} +2 -2
  11. package/dist/{apple-2YTcD6RU.js.map → apple-BbOPLgIX.js.map} +1 -1
  12. package/dist/{arrow-bottom-circle-W1sxGKIm.js → arrow-bottom-circle-BFTWJbEj.js} +2 -2
  13. package/dist/{arrow-bottom-circle-W1sxGKIm.js.map → arrow-bottom-circle-BFTWJbEj.js.map} +1 -1
  14. package/dist/{arrow-bottom-ZLYjQRVF.js → arrow-bottom-nxwCJBf2.js} +2 -2
  15. package/dist/{arrow-bottom-ZLYjQRVF.js.map → arrow-bottom-nxwCJBf2.js.map} +1 -1
  16. package/dist/{arrow-left-DLgnPVzk.js → arrow-left-BWlJ2qlC.js} +2 -2
  17. package/dist/{arrow-left-DLgnPVzk.js.map → arrow-left-BWlJ2qlC.js.map} +1 -1
  18. package/dist/{arrow-right-C5iPaK1O.js → arrow-right-BGkJBSWL.js} +2 -2
  19. package/dist/{arrow-right-C5iPaK1O.js.map → arrow-right-BGkJBSWL.js.map} +1 -1
  20. package/dist/{arrow-top-CKGwVtz2.js → arrow-top-CW2jDEe4.js} +2 -2
  21. package/dist/{arrow-top-CKGwVtz2.js.map → arrow-top-CW2jDEe4.js.map} +1 -1
  22. package/dist/{bank-DeTywVwC.js → bank-1GOPral2.js} +2 -2
  23. package/dist/{bank-DeTywVwC.js.map → bank-1GOPral2.js.map} +1 -1
  24. package/dist/{browser-ZHBOTr6m.js → browser-CNMKyt_S.js} +2 -2
  25. package/dist/{browser-ZHBOTr6m.js.map → browser-CNMKyt_S.js.map} +1 -1
  26. package/dist/{browser-B8BCrASu.js → browser-CRwbyiDn.js} +2 -2
  27. package/dist/{browser-B8BCrASu.js.map → browser-CRwbyiDn.js.map} +1 -1
  28. package/dist/{card-WYAxW4AU.js → card-BobtkMhO.js} +2 -2
  29. package/dist/{card-WYAxW4AU.js.map → card-BobtkMhO.js.map} +1 -1
  30. package/dist/{checkmark-D6gNkqXD.js → checkmark-9IgRwflL.js} +2 -2
  31. package/dist/{checkmark-D6gNkqXD.js.map → checkmark-9IgRwflL.js.map} +1 -1
  32. package/dist/{checkmark-bold-CVLxIhp1.js → checkmark-bold-BCsyR4P6.js} +2 -2
  33. package/dist/{checkmark-bold-CVLxIhp1.js.map → checkmark-bold-BCsyR4P6.js.map} +1 -1
  34. package/dist/{chevron-bottom-BnZrP8ng.js → chevron-bottom-hQ1dLD8u.js} +2 -2
  35. package/dist/{chevron-bottom-BnZrP8ng.js.map → chevron-bottom-hQ1dLD8u.js.map} +1 -1
  36. package/dist/{chevron-left-PQlhhfpK.js → chevron-left-B11Abfnf.js} +2 -2
  37. package/dist/{chevron-left-PQlhhfpK.js.map → chevron-left-B11Abfnf.js.map} +1 -1
  38. package/dist/{chevron-right-BHxp4jkW.js → chevron-right-Bf32y1EN.js} +2 -2
  39. package/dist/{chevron-right-BHxp4jkW.js.map → chevron-right-Bf32y1EN.js.map} +1 -1
  40. package/dist/{chevron-top-BbJGkGfR.js → chevron-top-BO8SByAy.js} +2 -2
  41. package/dist/{chevron-top-BbJGkGfR.js.map → chevron-top-BO8SByAy.js.map} +1 -1
  42. package/dist/{chrome-store-Cie71Qem.js → chrome-store-9vnZcqNu.js} +2 -2
  43. package/dist/{chrome-store-Cie71Qem.js.map → chrome-store-9vnZcqNu.js.map} +1 -1
  44. package/dist/{clock-IQBTFXEw.js → clock-riZdPcFM.js} +2 -2
  45. package/dist/{clock-IQBTFXEw.js.map → clock-riZdPcFM.js.map} +1 -1
  46. package/dist/{close-DxKbHQ06.js → close-DNxPKWKb.js} +2 -2
  47. package/dist/{close-DxKbHQ06.js.map → close-DNxPKWKb.js.map} +1 -1
  48. package/dist/{coinPlaceholder-CoskC0O6.js → coinPlaceholder-vaT6n0Dq.js} +2 -2
  49. package/dist/{coinPlaceholder-CoskC0O6.js.map → coinPlaceholder-vaT6n0Dq.js.map} +1 -1
  50. package/dist/{compass-IfPXB2uJ.js → compass-BXTAYDkL.js} +2 -2
  51. package/dist/{compass-IfPXB2uJ.js.map → compass-BXTAYDkL.js.map} +1 -1
  52. package/dist/{copy-Bjw7HZdA.js → copy-CBRaHGDQ.js} +2 -2
  53. package/dist/{copy-Bjw7HZdA.js.map → copy-CBRaHGDQ.js.map} +1 -1
  54. package/dist/{cursor-BEjLiAyG.js → cursor-d-bR9lqy.js} +2 -2
  55. package/dist/{cursor-BEjLiAyG.js.map → cursor-d-bR9lqy.js.map} +1 -1
  56. package/dist/{cursor-transparent-B4swj4oX.js → cursor-transparent-DanHbb8L.js} +2 -2
  57. package/dist/{cursor-transparent-B4swj4oX.js.map → cursor-transparent-DanHbb8L.js.map} +1 -1
  58. package/dist/{desktop-DWDJAE0j.js → desktop-Ea_pcyLe.js} +2 -2
  59. package/dist/{desktop-DWDJAE0j.js.map → desktop-Ea_pcyLe.js.map} +1 -1
  60. package/dist/{disconnect-DyBVvUlm.js → disconnect-CjRyCdF-.js} +2 -2
  61. package/dist/{disconnect-DyBVvUlm.js.map → disconnect-CjRyCdF-.js.map} +1 -1
  62. package/dist/{discord-Dy6b3RRH.js → discord-85Fgrjua.js} +2 -2
  63. package/dist/{discord-Dy6b3RRH.js.map → discord-85Fgrjua.js.map} +1 -1
  64. package/dist/{email-DghZZFyu.js → email-C29KqpqU.js} +8 -8
  65. package/dist/{email-DghZZFyu.js.map → email-C29KqpqU.js.map} +1 -1
  66. package/dist/{embedded-wallet-CGjM19AV.js → embedded-wallet-ChtJ9d8m.js} +10 -10
  67. package/dist/{embedded-wallet-CGjM19AV.js.map → embedded-wallet-ChtJ9d8m.js.map} +1 -1
  68. package/dist/{etherscan-CJk7TO4R.js → etherscan-DTm7ibk5.js} +2 -2
  69. package/dist/{etherscan-CJk7TO4R.js.map → etherscan-DTm7ibk5.js.map} +1 -1
  70. package/dist/{exclamation-triangle-DiOWokAx.js → exclamation-triangle-DGIy7zhV.js} +2 -2
  71. package/dist/{exclamation-triangle-DiOWokAx.js.map → exclamation-triangle-DGIy7zhV.js.map} +1 -1
  72. package/dist/{extension-AzZ-VQ5S.js → extension-BG9HdMPD.js} +2 -2
  73. package/dist/{extension-AzZ-VQ5S.js.map → extension-BG9HdMPD.js.map} +1 -1
  74. package/dist/{external-link-Bg6o90yA.js → external-link-Di43C1pf.js} +2 -2
  75. package/dist/{external-link-Bg6o90yA.js.map → external-link-Di43C1pf.js.map} +1 -1
  76. package/dist/{facebook-BvIKAWg3.js → facebook-CMAKZiZB.js} +2 -2
  77. package/dist/{facebook-BvIKAWg3.js.map → facebook-CMAKZiZB.js.map} +1 -1
  78. package/dist/{farcaster-CMMxDX39.js → farcaster-Dpf9c4MK.js} +2 -2
  79. package/dist/{farcaster-CMMxDX39.js.map → farcaster-Dpf9c4MK.js.map} +1 -1
  80. package/dist/{filters-CFLl0iBs.js → filters-CMFnX3RL.js} +2 -2
  81. package/dist/{filters-CFLl0iBs.js.map → filters-CMFnX3RL.js.map} +1 -1
  82. package/dist/{github-CmYncmzL.js → github-Bjk1_5qL.js} +2 -2
  83. package/dist/{github-CmYncmzL.js.map → github-Bjk1_5qL.js.map} +1 -1
  84. package/dist/{google-Ckse0W4Z.js → google-62muXda9.js} +2 -2
  85. package/dist/{google-Ckse0W4Z.js.map → google-62muXda9.js.map} +1 -1
  86. package/dist/{help-circle-BijMy4ht.js → help-circle-CTpQUk-o.js} +2 -2
  87. package/dist/{help-circle-BijMy4ht.js.map → help-circle-CTpQUk-o.js.map} +1 -1
  88. package/dist/{id-gO3BEzSg.js → id-Dp8nTGU2.js} +2 -2
  89. package/dist/{id-gO3BEzSg.js.map → id-Dp8nTGU2.js.map} +1 -1
  90. package/dist/{if-defined-BUCsuh9s.js → if-defined-DeBuBv8C.js} +78 -78
  91. package/dist/{if-defined-BUCsuh9s.js.map → if-defined-DeBuBv8C.js.map} +1 -1
  92. package/dist/{image-DxhE6Fnm.js → image-Dn9sVFNH.js} +2 -2
  93. package/dist/{image-DxhE6Fnm.js.map → image-Dn9sVFNH.js.map} +1 -1
  94. package/dist/{index-DPDvs1Rr.js → index-3AIUbrUU.js} +4 -4
  95. package/dist/{index-DPDvs1Rr.js.map → index-3AIUbrUU.js.map} +1 -1
  96. package/dist/{index-OJaV5piL.js → index-APZGoFS4.js} +3 -3
  97. package/dist/{index-OJaV5piL.js.map → index-APZGoFS4.js.map} +1 -1
  98. package/dist/{index-C9D8IpSa.js → index-B4ozkdcL.js} +3 -3
  99. package/dist/{index-C9D8IpSa.js.map → index-B4ozkdcL.js.map} +1 -1
  100. package/dist/{index-CQfiGCux.js → index-BBqt8FI3.js} +3 -3
  101. package/dist/{index-CQfiGCux.js.map → index-BBqt8FI3.js.map} +1 -1
  102. package/dist/{index-h2uWrDWR.js → index-BF2zsxDq.js} +4 -4
  103. package/dist/{index-h2uWrDWR.js.map → index-BF2zsxDq.js.map} +1 -1
  104. package/dist/{index-DnuurRsQ.js → index-BInOwLdY.js} +7 -7
  105. package/dist/{index-DnuurRsQ.js.map → index-BInOwLdY.js.map} +1 -1
  106. package/dist/{index-BL1Vtc1i.js → index-BOUiZbXW.js} +4 -4
  107. package/dist/{index-BL1Vtc1i.js.map → index-BOUiZbXW.js.map} +1 -1
  108. package/dist/{index-Bdgknjoz.js → index-BOt3v16B.js} +4 -4
  109. package/dist/{index-Bdgknjoz.js.map → index-BOt3v16B.js.map} +1 -1
  110. package/dist/{index-CGcPcD7s.js → index-BV_wsLUs.js} +3 -3
  111. package/dist/{index-CGcPcD7s.js.map → index-BV_wsLUs.js.map} +1 -1
  112. package/dist/{index-C0zB454j.js → index-BjEXOY6K.js} +3 -3
  113. package/dist/{index-C0zB454j.js.map → index-BjEXOY6K.js.map} +1 -1
  114. package/dist/{index-Clt4Gamg.js → index-BjjSQnZ5.js} +3 -3
  115. package/dist/{index-Clt4Gamg.js.map → index-BjjSQnZ5.js.map} +1 -1
  116. package/dist/{index-Bf_CKPQ4.js → index-BkE0sZOy.js} +4 -4
  117. package/dist/{index-Bf_CKPQ4.js.map → index-BkE0sZOy.js.map} +1 -1
  118. package/dist/{index-C_NCBpBW.js → index-BoR_58tP.js} +3 -3
  119. package/dist/{index-C_NCBpBW.js.map → index-BoR_58tP.js.map} +1 -1
  120. package/dist/{index-BuYXv-te.js → index-BpUy6ELp.js} +4 -4
  121. package/dist/{index-BuYXv-te.js.map → index-BpUy6ELp.js.map} +1 -1
  122. package/dist/{index-uQiw5aDt.js → index-BxTB1jb6.js} +4 -4
  123. package/dist/{index-uQiw5aDt.js.map → index-BxTB1jb6.js.map} +1 -1
  124. package/dist/{index-0sQOBosT.js → index-C3dCbvuU.js} +3 -3
  125. package/dist/{index-0sQOBosT.js.map → index-C3dCbvuU.js.map} +1 -1
  126. package/dist/{index-B3US0ze7.js → index-CIWdN6s7.js} +81 -29
  127. package/dist/index-CIWdN6s7.js.map +1 -0
  128. package/dist/{index-BtP6BgXy.js → index-CMFU2wOq.js} +3 -3
  129. package/dist/{index-BtP6BgXy.js.map → index-CMFU2wOq.js.map} +1 -1
  130. package/dist/index-CRQSbrdZ.js +3348 -0
  131. package/dist/index-CRQSbrdZ.js.map +1 -0
  132. package/dist/{index-D4uZajOt.js → index-CiZ2wBs3.js} +3 -3
  133. package/dist/{index-D4uZajOt.js.map → index-CiZ2wBs3.js.map} +1 -1
  134. package/dist/{index-DfXsC6Vx.js → index-Cjc4qIdP.js} +3 -3
  135. package/dist/{index-DfXsC6Vx.js.map → index-Cjc4qIdP.js.map} +1 -1
  136. package/dist/{index-D1vsBg_X.js → index-CmoL773p.js} +3 -3
  137. package/dist/{index-D1vsBg_X.js.map → index-CmoL773p.js.map} +1 -1
  138. package/dist/{index-_DqHUChI.js → index-CoPIlial.js} +4 -4
  139. package/dist/{index-_DqHUChI.js.map → index-CoPIlial.js.map} +1 -1
  140. package/dist/{index-DQibQFkr.js → index-D9nmWywB.js} +4 -4
  141. package/dist/{index-DQibQFkr.js.map → index-D9nmWywB.js.map} +1 -1
  142. package/dist/{index-5stOlOiL.js → index-DPRQcYF5.js} +4 -4
  143. package/dist/{index-5stOlOiL.js.map → index-DPRQcYF5.js.map} +1 -1
  144. package/dist/{index--8fCrTMB.js → index-DThB6yHY.js} +4 -4
  145. package/dist/{index--8fCrTMB.js.map → index-DThB6yHY.js.map} +1 -1
  146. package/dist/{index-BNLFpx_o.js → index-Dew3mRSJ.js} +2 -2
  147. package/dist/{index-BNLFpx_o.js.map → index-Dew3mRSJ.js.map} +1 -1
  148. package/dist/{index-Dj8pFty_.js → index-DvMegG3P.js} +3 -505
  149. package/dist/index-DvMegG3P.js.map +1 -0
  150. package/dist/{index-B7_8EBSn.js → index-Ee9KL65X.js} +7 -6
  151. package/dist/{index-B7_8EBSn.js.map → index-Ee9KL65X.js.map} +1 -1
  152. package/dist/{index-D5X2HlH8.js → index-EipIP3kf.js} +6 -6
  153. package/dist/{index-D5X2HlH8.js.map → index-EipIP3kf.js.map} +1 -1
  154. package/dist/{index-cjkE7IEF.js → index-KXOAAHza.js} +5 -5
  155. package/dist/{index-cjkE7IEF.js.map → index-KXOAAHza.js.map} +1 -1
  156. package/dist/{index-BiZ2sPMP.js → index-huLhd52f.js} +3 -3
  157. package/dist/{index-BiZ2sPMP.js.map → index-huLhd52f.js.map} +1 -1
  158. package/dist/{index.es-DWq-VIEl.js → index.es-E9oLZaOC.js} +3 -3
  159. package/dist/{index.es-DWq-VIEl.js.map → index.es-E9oLZaOC.js.map} +1 -1
  160. package/dist/{info-CSgVmziu.js → info-DQT-QmV7.js} +2 -2
  161. package/dist/{info-CSgVmziu.js.map → info-DQT-QmV7.js.map} +1 -1
  162. package/dist/{info-circle-Bzkbp00x.js → info-circle-p3wAzkW0.js} +2 -2
  163. package/dist/{info-circle-Bzkbp00x.js.map → info-circle-p3wAzkW0.js.map} +1 -1
  164. package/dist/{lightbulb-C-bkgBIb.js → lightbulb-Bnnje34R.js} +2 -2
  165. package/dist/{lightbulb-C-bkgBIb.js.map → lightbulb-Bnnje34R.js.map} +1 -1
  166. package/dist/{mail-CGmFg6fK.js → mail-5PSXCI0v.js} +2 -2
  167. package/dist/{mail-CGmFg6fK.js.map → mail-5PSXCI0v.js.map} +1 -1
  168. package/dist/{metamask-sdk-BakScGM0.js → metamask-sdk-8ZnQEZHu.js} +576 -584
  169. package/dist/metamask-sdk-8ZnQEZHu.js.map +1 -0
  170. package/dist/{mobile-DtRyE0jl.js → mobile-6mHtv3de.js} +2 -2
  171. package/dist/{mobile-DtRyE0jl.js.map → mobile-6mHtv3de.js.map} +1 -1
  172. package/dist/{more-KeHkLrDL.js → more-Dlt5sBR_.js} +2 -2
  173. package/dist/{more-KeHkLrDL.js.map → more-Dlt5sBR_.js.map} +1 -1
  174. package/dist/{native-Bp8NmofE.js → native-BhQYFetC.js} +2 -2
  175. package/dist/{native-Bp8NmofE.js.map → native-BhQYFetC.js.map} +1 -1
  176. package/dist/{network-placeholder-DOqs4Acw.js → network-placeholder-ZwUth56L.js} +2 -2
  177. package/dist/{network-placeholder-DOqs4Acw.js.map → network-placeholder-ZwUth56L.js.map} +1 -1
  178. package/dist/{nftPlaceholder-CqCnpGWd.js → nftPlaceholder-BZbdxsVy.js} +2 -2
  179. package/dist/{nftPlaceholder-CqCnpGWd.js.map → nftPlaceholder-BZbdxsVy.js.map} +1 -1
  180. package/dist/{off-BjQ1lWwI.js → off-DMjVDy9F.js} +2 -2
  181. package/dist/{off-BjQ1lWwI.js.map → off-DMjVDy9F.js.map} +1 -1
  182. package/dist/{onramp-YQOJXd7V.js → onramp-Bcn6fi9Y.js} +12 -12
  183. package/dist/{onramp-YQOJXd7V.js.map → onramp-Bcn6fi9Y.js.map} +1 -1
  184. package/dist/{play-store-gd3X2PE-.js → play-store-BB8PxYq4.js} +2 -2
  185. package/dist/{play-store-gd3X2PE-.js.map → play-store-BB8PxYq4.js.map} +1 -1
  186. package/dist/{plus-BjhhVCpY.js → plus-BQCGi8aA.js} +2 -2
  187. package/dist/{plus-BjhhVCpY.js.map → plus-BQCGi8aA.js.map} +1 -1
  188. package/dist/{qr-code-qjafSsS2.js → qr-code-CkWYDLbl.js} +2 -2
  189. package/dist/{qr-code-qjafSsS2.js.map → qr-code-CkWYDLbl.js.map} +1 -1
  190. package/dist/{receive-DkS03GRp.js → receive-BliYuS9o.js} +6 -6
  191. package/dist/{receive-DkS03GRp.js.map → receive-BliYuS9o.js.map} +1 -1
  192. package/dist/{recycle-horizontal-Chbf-42q.js → recycle-horizontal-BuvzEP2Z.js} +2 -2
  193. package/dist/{recycle-horizontal-Chbf-42q.js.map → recycle-horizontal-BuvzEP2Z.js.map} +1 -1
  194. package/dist/{refresh-B_fq24BN.js → refresh-2H3scIjP.js} +2 -2
  195. package/dist/{refresh-B_fq24BN.js.map → refresh-2H3scIjP.js.map} +1 -1
  196. package/dist/{search-CMyddrMM.js → search-C6kAa6cT.js} +2 -2
  197. package/dist/{search-CMyddrMM.js.map → search-C6kAa6cT.js.map} +1 -1
  198. package/dist/{send-DLwfVu3X.js → send-CUKUapsP.js} +2 -2
  199. package/dist/{send-DLwfVu3X.js.map → send-CUKUapsP.js.map} +1 -1
  200. package/dist/{send-5jN_SWT6.js → send-Dzhh-U1d.js} +10 -10
  201. package/dist/{send-5jN_SWT6.js.map → send-Dzhh-U1d.js.map} +1 -1
  202. package/dist/sha3-_pthIdIu.js +507 -0
  203. package/dist/sha3-_pthIdIu.js.map +1 -0
  204. package/dist/{socials-BskU39sA.js → socials-DfRR4eSa.js} +11 -11
  205. package/dist/socials-DfRR4eSa.js.map +1 -0
  206. package/dist/{swapHorizontal-CkK6Uemb.js → swapHorizontal-Comnyn0B.js} +2 -2
  207. package/dist/{swapHorizontal-CkK6Uemb.js.map → swapHorizontal-Comnyn0B.js.map} +1 -1
  208. package/dist/{swapHorizontalBold-EjmeRq01.js → swapHorizontalBold-sfM6wFJK.js} +2 -2
  209. package/dist/{swapHorizontalBold-EjmeRq01.js.map → swapHorizontalBold-sfM6wFJK.js.map} +1 -1
  210. package/dist/{swapHorizontalMedium-Dta28Hsi.js → swapHorizontalMedium-DHYNeIT9.js} +2 -2
  211. package/dist/{swapHorizontalMedium-Dta28Hsi.js.map → swapHorizontalMedium-DHYNeIT9.js.map} +1 -1
  212. package/dist/{swapHorizontalRoundedBold-c2wfDzBF.js → swapHorizontalRoundedBold-bjbYmfWO.js} +2 -2
  213. package/dist/{swapHorizontalRoundedBold-c2wfDzBF.js.map → swapHorizontalRoundedBold-bjbYmfWO.js.map} +1 -1
  214. package/dist/{swapVertical-BWZAOaFe.js → swapVertical-BxaU27nG.js} +2 -2
  215. package/dist/{swapVertical-BWZAOaFe.js.map → swapVertical-BxaU27nG.js.map} +1 -1
  216. package/dist/{swaps-CpwnRcad.js → swaps-BzTiyZmt.js} +10 -10
  217. package/dist/{swaps-CpwnRcad.js.map → swaps-BzTiyZmt.js.map} +1 -1
  218. package/dist/{telegram-DQpS1hOx.js → telegram-CiKi0tAK.js} +2 -2
  219. package/dist/{telegram-DQpS1hOx.js.map → telegram-CiKi0tAK.js.map} +1 -1
  220. package/dist/{three-dots-BIyLH-r_.js → three-dots-BJQoQYgU.js} +2 -2
  221. package/dist/{three-dots-BIyLH-r_.js.map → three-dots-BJQoQYgU.js.map} +1 -1
  222. package/dist/{transactions-ClbAR3b3.js → transactions-Bv-oGunp.js} +4 -4
  223. package/dist/{transactions-ClbAR3b3.js.map → transactions-Bv-oGunp.js.map} +1 -1
  224. package/dist/{twitch-w1fW9GUX.js → twitch-COTSMXJA.js} +2 -2
  225. package/dist/{twitch-w1fW9GUX.js.map → twitch-COTSMXJA.js.map} +1 -1
  226. package/dist/{twitterIcon-NV4rOXLM.js → twitterIcon-D_003_ON.js} +2 -2
  227. package/dist/{twitterIcon-NV4rOXLM.js.map → twitterIcon-D_003_ON.js.map} +1 -1
  228. package/dist/{verify-M1n52Kbs.js → verify-CwN_7Z4z.js} +2 -2
  229. package/dist/{verify-M1n52Kbs.js.map → verify-CwN_7Z4z.js.map} +1 -1
  230. package/dist/{verify-filled-CaH-d-6a.js → verify-filled-CMaOXVVk.js} +2 -2
  231. package/dist/{verify-filled-CaH-d-6a.js.map → verify-filled-CMaOXVVk.js.map} +1 -1
  232. package/dist/{w3m-modal-DuL53Gbm.js → w3m-modal-C3DATvc6.js} +13 -10
  233. package/dist/w3m-modal-C3DATvc6.js.map +1 -0
  234. package/dist/{wallet-Dshhbo-h.js → wallet-D84gVoa4.js} +2 -2
  235. package/dist/{wallet-Dshhbo-h.js.map → wallet-D84gVoa4.js.map} +1 -1
  236. package/dist/{wallet-placeholder-CjvKtwBY.js → wallet-placeholder-14A7hM7b.js} +2 -2
  237. package/dist/{wallet-placeholder-CjvKtwBY.js.map → wallet-placeholder-14A7hM7b.js.map} +1 -1
  238. package/dist/{walletconnect-iX57ADQX.js → walletconnect-8JXyBf8j.js} +2 -2
  239. package/dist/{walletconnect-iX57ADQX.js.map → walletconnect-8JXyBf8j.js.map} +1 -1
  240. package/dist/{warning-circle-8Hc0Cz7j.js → warning-circle-B2uvv-rW.js} +2 -2
  241. package/dist/{warning-circle-8Hc0Cz7j.js.map → warning-circle-B2uvv-rW.js.map} +1 -1
  242. package/dist/{x-CynCso4V.js → x-w1gCvlpq.js} +2 -2
  243. package/dist/{x-CynCso4V.js.map → x-w1gCvlpq.js.map} +1 -1
  244. package/package.json +11 -11
  245. package/dist/appkit-7F54kjKy.js.map +0 -1
  246. package/dist/ccip-DElUUMQ2.js +0 -160
  247. package/dist/ccip-DElUUMQ2.js.map +0 -1
  248. package/dist/index-B3US0ze7.js.map +0 -1
  249. package/dist/index-Dj8pFty_.js.map +0 -1
  250. package/dist/metamask-sdk-BakScGM0.js.map +0 -1
  251. package/dist/secp256k1-BSI-MLM-.js +0 -1705
  252. package/dist/secp256k1-BSI-MLM-.js.map +0 -1
  253. package/dist/socials-BskU39sA.js.map +0 -1
  254. package/dist/w3m-modal-DuL53Gbm.js.map +0 -1
@@ -0,0 +1,3348 @@
1
+ import { a6 as Buffer, $ as getDefaultExportFromCjs, a7 as bytesToHex, a8 as sha256, a9 as EventEmitter } from "./appkit-Cly9g1o7.js";
2
+ import { s as sha3 } from "./sha3-_pthIdIu.js";
3
+ import { D, g, c as clsx, h, y } from "./hooks.module-B8FgZbnF.js";
4
+ class ScopedLocalStorage {
5
+ constructor(scope, module) {
6
+ this.scope = scope;
7
+ this.module = module;
8
+ }
9
+ storeObject(key, item) {
10
+ this.setItem(key, JSON.stringify(item));
11
+ }
12
+ loadObject(key) {
13
+ const item = this.getItem(key);
14
+ return item ? JSON.parse(item) : void 0;
15
+ }
16
+ setItem(key, value) {
17
+ localStorage.setItem(this.scopedKey(key), value);
18
+ }
19
+ getItem(key) {
20
+ return localStorage.getItem(this.scopedKey(key));
21
+ }
22
+ removeItem(key) {
23
+ localStorage.removeItem(this.scopedKey(key));
24
+ }
25
+ clear() {
26
+ const prefix = this.scopedKey("");
27
+ const keysToRemove = [];
28
+ for (let i = 0; i < localStorage.length; i++) {
29
+ const key = localStorage.key(i);
30
+ if (typeof key === "string" && key.startsWith(prefix)) {
31
+ keysToRemove.push(key);
32
+ }
33
+ }
34
+ keysToRemove.forEach((key) => localStorage.removeItem(key));
35
+ }
36
+ scopedKey(key) {
37
+ return `-${this.scope}${this.module ? `:${this.module}` : ""}:${key}`;
38
+ }
39
+ static clearAll() {
40
+ new ScopedLocalStorage("CBWSDK").clear();
41
+ new ScopedLocalStorage("walletlink").clear();
42
+ }
43
+ }
44
+ const standardErrorCodes = {
45
+ rpc: {
46
+ invalidInput: -32e3,
47
+ resourceNotFound: -32001,
48
+ resourceUnavailable: -32002,
49
+ transactionRejected: -32003,
50
+ methodNotSupported: -32004,
51
+ limitExceeded: -32005,
52
+ parse: -32700,
53
+ invalidRequest: -32600,
54
+ methodNotFound: -32601,
55
+ invalidParams: -32602,
56
+ internal: -32603
57
+ },
58
+ provider: {
59
+ userRejectedRequest: 4001,
60
+ unauthorized: 4100,
61
+ unsupportedMethod: 4200,
62
+ disconnected: 4900,
63
+ chainDisconnected: 4901,
64
+ unsupportedChain: 4902
65
+ }
66
+ };
67
+ const errorValues = {
68
+ "-32700": {
69
+ standard: "JSON RPC 2.0",
70
+ message: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
71
+ },
72
+ "-32600": {
73
+ standard: "JSON RPC 2.0",
74
+ message: "The JSON sent is not a valid Request object."
75
+ },
76
+ "-32601": {
77
+ standard: "JSON RPC 2.0",
78
+ message: "The method does not exist / is not available."
79
+ },
80
+ "-32602": {
81
+ standard: "JSON RPC 2.0",
82
+ message: "Invalid method parameter(s)."
83
+ },
84
+ "-32603": {
85
+ standard: "JSON RPC 2.0",
86
+ message: "Internal JSON-RPC error."
87
+ },
88
+ "-32000": {
89
+ standard: "EIP-1474",
90
+ message: "Invalid input."
91
+ },
92
+ "-32001": {
93
+ standard: "EIP-1474",
94
+ message: "Resource not found."
95
+ },
96
+ "-32002": {
97
+ standard: "EIP-1474",
98
+ message: "Resource unavailable."
99
+ },
100
+ "-32003": {
101
+ standard: "EIP-1474",
102
+ message: "Transaction rejected."
103
+ },
104
+ "-32004": {
105
+ standard: "EIP-1474",
106
+ message: "Method not supported."
107
+ },
108
+ "-32005": {
109
+ standard: "EIP-1474",
110
+ message: "Request limit exceeded."
111
+ },
112
+ "4001": {
113
+ standard: "EIP-1193",
114
+ message: "User rejected the request."
115
+ },
116
+ "4100": {
117
+ standard: "EIP-1193",
118
+ message: "The requested account and/or method has not been authorized by the user."
119
+ },
120
+ "4200": {
121
+ standard: "EIP-1193",
122
+ message: "The requested method is not supported by this Ethereum provider."
123
+ },
124
+ "4900": {
125
+ standard: "EIP-1193",
126
+ message: "The provider is disconnected from all chains."
127
+ },
128
+ "4901": {
129
+ standard: "EIP-1193",
130
+ message: "The provider is disconnected from the specified chain."
131
+ },
132
+ "4902": {
133
+ standard: "EIP-3085",
134
+ message: "Unrecognized chain ID."
135
+ }
136
+ };
137
+ const FALLBACK_MESSAGE = "Unspecified error message.";
138
+ const JSON_RPC_SERVER_ERROR_MESSAGE = "Unspecified server error.";
139
+ function getMessageFromCode(code, fallbackMessage = FALLBACK_MESSAGE) {
140
+ if (code && Number.isInteger(code)) {
141
+ const codeString = code.toString();
142
+ if (hasKey(errorValues, codeString)) {
143
+ return errorValues[codeString].message;
144
+ }
145
+ if (isJsonRpcServerError(code)) {
146
+ return JSON_RPC_SERVER_ERROR_MESSAGE;
147
+ }
148
+ }
149
+ return fallbackMessage;
150
+ }
151
+ function isValidCode(code) {
152
+ if (!Number.isInteger(code)) {
153
+ return false;
154
+ }
155
+ const codeString = code.toString();
156
+ if (errorValues[codeString]) {
157
+ return true;
158
+ }
159
+ if (isJsonRpcServerError(code)) {
160
+ return true;
161
+ }
162
+ return false;
163
+ }
164
+ function serialize(error, { shouldIncludeStack = false } = {}) {
165
+ const serialized = {};
166
+ if (error && typeof error === "object" && !Array.isArray(error) && hasKey(error, "code") && isValidCode(error.code)) {
167
+ const _error = error;
168
+ serialized.code = _error.code;
169
+ if (_error.message && typeof _error.message === "string") {
170
+ serialized.message = _error.message;
171
+ if (hasKey(_error, "data")) {
172
+ serialized.data = _error.data;
173
+ }
174
+ } else {
175
+ serialized.message = getMessageFromCode(serialized.code);
176
+ serialized.data = { originalError: assignOriginalError(error) };
177
+ }
178
+ } else {
179
+ serialized.code = standardErrorCodes.rpc.internal;
180
+ serialized.message = hasStringProperty(error, "message") ? error.message : FALLBACK_MESSAGE;
181
+ serialized.data = { originalError: assignOriginalError(error) };
182
+ }
183
+ if (shouldIncludeStack) {
184
+ serialized.stack = hasStringProperty(error, "stack") ? error.stack : void 0;
185
+ }
186
+ return serialized;
187
+ }
188
+ function isJsonRpcServerError(code) {
189
+ return code >= -32099 && code <= -32e3;
190
+ }
191
+ function assignOriginalError(error) {
192
+ if (error && typeof error === "object" && !Array.isArray(error)) {
193
+ return Object.assign({}, error);
194
+ }
195
+ return error;
196
+ }
197
+ function hasKey(obj, key) {
198
+ return Object.prototype.hasOwnProperty.call(obj, key);
199
+ }
200
+ function hasStringProperty(obj, prop) {
201
+ return typeof obj === "object" && obj !== null && prop in obj && typeof obj[prop] === "string";
202
+ }
203
+ const standardErrors = {
204
+ rpc: {
205
+ parse: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.parse, arg),
206
+ invalidRequest: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidRequest, arg),
207
+ invalidParams: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidParams, arg),
208
+ methodNotFound: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.methodNotFound, arg),
209
+ internal: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.internal, arg),
210
+ server: (opts) => {
211
+ if (!opts || typeof opts !== "object" || Array.isArray(opts)) {
212
+ throw new Error("Ethereum RPC Server errors must provide single object argument.");
213
+ }
214
+ const { code } = opts;
215
+ if (!Number.isInteger(code) || code > -32005 || code < -32099) {
216
+ throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');
217
+ }
218
+ return getEthJsonRpcError(code, opts);
219
+ },
220
+ invalidInput: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidInput, arg),
221
+ resourceNotFound: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.resourceNotFound, arg),
222
+ resourceUnavailable: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.resourceUnavailable, arg),
223
+ transactionRejected: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.transactionRejected, arg),
224
+ methodNotSupported: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.methodNotSupported, arg),
225
+ limitExceeded: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.limitExceeded, arg)
226
+ },
227
+ provider: {
228
+ userRejectedRequest: (arg) => {
229
+ return getEthProviderError(standardErrorCodes.provider.userRejectedRequest, arg);
230
+ },
231
+ unauthorized: (arg) => {
232
+ return getEthProviderError(standardErrorCodes.provider.unauthorized, arg);
233
+ },
234
+ unsupportedMethod: (arg) => {
235
+ return getEthProviderError(standardErrorCodes.provider.unsupportedMethod, arg);
236
+ },
237
+ disconnected: (arg) => {
238
+ return getEthProviderError(standardErrorCodes.provider.disconnected, arg);
239
+ },
240
+ chainDisconnected: (arg) => {
241
+ return getEthProviderError(standardErrorCodes.provider.chainDisconnected, arg);
242
+ },
243
+ unsupportedChain: (arg) => {
244
+ return getEthProviderError(standardErrorCodes.provider.unsupportedChain, arg);
245
+ },
246
+ custom: (opts) => {
247
+ if (!opts || typeof opts !== "object" || Array.isArray(opts)) {
248
+ throw new Error("Ethereum Provider custom errors must provide single object argument.");
249
+ }
250
+ const { code, message, data } = opts;
251
+ if (!message || typeof message !== "string") {
252
+ throw new Error('"message" must be a nonempty string');
253
+ }
254
+ return new EthereumProviderError(code, message, data);
255
+ }
256
+ }
257
+ };
258
+ function getEthJsonRpcError(code, arg) {
259
+ const [message, data] = parseOpts(arg);
260
+ return new EthereumRpcError(code, message || getMessageFromCode(code), data);
261
+ }
262
+ function getEthProviderError(code, arg) {
263
+ const [message, data] = parseOpts(arg);
264
+ return new EthereumProviderError(code, message || getMessageFromCode(code), data);
265
+ }
266
+ function parseOpts(arg) {
267
+ if (arg) {
268
+ if (typeof arg === "string") {
269
+ return [arg];
270
+ } else if (typeof arg === "object" && !Array.isArray(arg)) {
271
+ const { message, data } = arg;
272
+ if (message && typeof message !== "string") {
273
+ throw new Error("Must specify string message.");
274
+ }
275
+ return [message || void 0, data];
276
+ }
277
+ }
278
+ return [];
279
+ }
280
+ class EthereumRpcError extends Error {
281
+ constructor(code, message, data) {
282
+ if (!Number.isInteger(code)) {
283
+ throw new Error('"code" must be an integer.');
284
+ }
285
+ if (!message || typeof message !== "string") {
286
+ throw new Error('"message" must be a nonempty string.');
287
+ }
288
+ super(message);
289
+ this.code = code;
290
+ if (data !== void 0) {
291
+ this.data = data;
292
+ }
293
+ }
294
+ }
295
+ class EthereumProviderError extends EthereumRpcError {
296
+ /**
297
+ * Create an Ethereum Provider JSON-RPC error.
298
+ * `code` must be an integer in the 1000 <= 4999 range.
299
+ */
300
+ constructor(code, message, data) {
301
+ if (!isValidEthProviderCode(code)) {
302
+ throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');
303
+ }
304
+ super(code, message, data);
305
+ }
306
+ }
307
+ function isValidEthProviderCode(code) {
308
+ return Number.isInteger(code) && code >= 1e3 && code <= 4999;
309
+ }
310
+ function OpaqueType() {
311
+ return (value) => value;
312
+ }
313
+ const HexString = OpaqueType();
314
+ const AddressString = OpaqueType();
315
+ const BigIntString = OpaqueType();
316
+ function IntNumber(num) {
317
+ return Math.floor(num);
318
+ }
319
+ const INT_STRING_REGEX = /^[0-9]*$/;
320
+ const HEXADECIMAL_STRING_REGEX = /^[a-f0-9]*$/;
321
+ function randomBytesHex(length) {
322
+ return uint8ArrayToHex(crypto.getRandomValues(new Uint8Array(length)));
323
+ }
324
+ function uint8ArrayToHex(value) {
325
+ return [...value].map((b) => b.toString(16).padStart(2, "0")).join("");
326
+ }
327
+ function hexStringToUint8Array(hexString) {
328
+ return new Uint8Array(hexString.match(/.{1,2}/g).map((byte) => Number.parseInt(byte, 16)));
329
+ }
330
+ function hexStringFromBuffer(buf, includePrefix = false) {
331
+ const hex = buf.toString("hex");
332
+ return HexString(includePrefix ? `0x${hex}` : hex);
333
+ }
334
+ function encodeToHexString(str) {
335
+ return hexStringFromBuffer(ensureBuffer(str), true);
336
+ }
337
+ function bigIntStringFromBigInt(bi) {
338
+ return BigIntString(bi.toString(10));
339
+ }
340
+ function hexStringFromNumber(num) {
341
+ return HexString(`0x${BigInt(num).toString(16)}`);
342
+ }
343
+ function has0xPrefix(str) {
344
+ return str.startsWith("0x") || str.startsWith("0X");
345
+ }
346
+ function strip0x(hex) {
347
+ if (has0xPrefix(hex)) {
348
+ return hex.slice(2);
349
+ }
350
+ return hex;
351
+ }
352
+ function prepend0x(hex) {
353
+ if (has0xPrefix(hex)) {
354
+ return `0x${hex.slice(2)}`;
355
+ }
356
+ return `0x${hex}`;
357
+ }
358
+ function isHexString$1(hex) {
359
+ if (typeof hex !== "string") {
360
+ return false;
361
+ }
362
+ const s = strip0x(hex).toLowerCase();
363
+ return HEXADECIMAL_STRING_REGEX.test(s);
364
+ }
365
+ function ensureHexString(hex, includePrefix = false) {
366
+ if (typeof hex === "string") {
367
+ const s = strip0x(hex).toLowerCase();
368
+ if (HEXADECIMAL_STRING_REGEX.test(s)) {
369
+ return HexString(includePrefix ? `0x${s}` : s);
370
+ }
371
+ }
372
+ throw standardErrors.rpc.invalidParams(`"${String(hex)}" is not a hexadecimal string`);
373
+ }
374
+ function ensureEvenLengthHexString(hex, includePrefix = false) {
375
+ let h2 = ensureHexString(hex, false);
376
+ if (h2.length % 2 === 1) {
377
+ h2 = HexString(`0${h2}`);
378
+ }
379
+ return includePrefix ? HexString(`0x${h2}`) : h2;
380
+ }
381
+ function ensureAddressString(str) {
382
+ if (typeof str === "string") {
383
+ const s = strip0x(str).toLowerCase();
384
+ if (isHexString$1(s) && s.length === 40) {
385
+ return AddressString(prepend0x(s));
386
+ }
387
+ }
388
+ throw standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(str)}`);
389
+ }
390
+ function ensureBuffer(str) {
391
+ if (Buffer.isBuffer(str)) {
392
+ return str;
393
+ }
394
+ if (typeof str === "string") {
395
+ if (isHexString$1(str)) {
396
+ const s = ensureEvenLengthHexString(str, false);
397
+ return Buffer.from(s, "hex");
398
+ }
399
+ return Buffer.from(str, "utf8");
400
+ }
401
+ throw standardErrors.rpc.invalidParams(`Not binary data: ${String(str)}`);
402
+ }
403
+ function ensureIntNumber(num) {
404
+ if (typeof num === "number" && Number.isInteger(num)) {
405
+ return IntNumber(num);
406
+ }
407
+ if (typeof num === "string") {
408
+ if (INT_STRING_REGEX.test(num)) {
409
+ return IntNumber(Number(num));
410
+ }
411
+ if (isHexString$1(num)) {
412
+ return IntNumber(Number(BigInt(ensureEvenLengthHexString(num, true))));
413
+ }
414
+ }
415
+ throw standardErrors.rpc.invalidParams(`Not an integer: ${String(num)}`);
416
+ }
417
+ function ensureBigInt(val) {
418
+ if (val !== null && (typeof val === "bigint" || isBigNumber(val))) {
419
+ return BigInt(val.toString(10));
420
+ }
421
+ if (typeof val === "number") {
422
+ return BigInt(ensureIntNumber(val));
423
+ }
424
+ if (typeof val === "string") {
425
+ if (INT_STRING_REGEX.test(val)) {
426
+ return BigInt(val);
427
+ }
428
+ if (isHexString$1(val)) {
429
+ return BigInt(ensureEvenLengthHexString(val, true));
430
+ }
431
+ }
432
+ throw standardErrors.rpc.invalidParams(`Not an integer: ${String(val)}`);
433
+ }
434
+ function ensureParsedJSONObject(val) {
435
+ if (typeof val === "string") {
436
+ return JSON.parse(val);
437
+ }
438
+ if (typeof val === "object") {
439
+ return val;
440
+ }
441
+ throw standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(val)}`);
442
+ }
443
+ function isBigNumber(val) {
444
+ if (val == null || typeof val.constructor !== "function") {
445
+ return false;
446
+ }
447
+ const { constructor } = val;
448
+ return typeof constructor.config === "function" && typeof constructor.EUCLID === "number";
449
+ }
450
+ async function generateKeyPair() {
451
+ return crypto.subtle.generateKey({
452
+ name: "ECDH",
453
+ namedCurve: "P-256"
454
+ }, true, ["deriveKey"]);
455
+ }
456
+ async function deriveSharedSecret(ownPrivateKey, peerPublicKey) {
457
+ return crypto.subtle.deriveKey({
458
+ name: "ECDH",
459
+ public: peerPublicKey
460
+ }, ownPrivateKey, {
461
+ name: "AES-GCM",
462
+ length: 256
463
+ }, false, ["encrypt", "decrypt"]);
464
+ }
465
+ async function encrypt(sharedSecret, plainText) {
466
+ const iv = crypto.getRandomValues(new Uint8Array(12));
467
+ const cipherText = await crypto.subtle.encrypt({
468
+ name: "AES-GCM",
469
+ iv
470
+ }, sharedSecret, new TextEncoder().encode(plainText));
471
+ return { iv, cipherText };
472
+ }
473
+ async function decrypt(sharedSecret, { iv, cipherText }) {
474
+ const plainText = await crypto.subtle.decrypt({
475
+ name: "AES-GCM",
476
+ iv
477
+ }, sharedSecret, cipherText);
478
+ return new TextDecoder().decode(plainText);
479
+ }
480
+ function getFormat(keyType) {
481
+ switch (keyType) {
482
+ case "public":
483
+ return "spki";
484
+ case "private":
485
+ return "pkcs8";
486
+ }
487
+ }
488
+ async function exportKeyToHexString(type, key) {
489
+ const format = getFormat(type);
490
+ const exported = await crypto.subtle.exportKey(format, key);
491
+ return uint8ArrayToHex(new Uint8Array(exported));
492
+ }
493
+ async function importKeyFromHexString(type, hexString) {
494
+ const format = getFormat(type);
495
+ const arrayBuffer = hexStringToUint8Array(hexString).buffer;
496
+ return await crypto.subtle.importKey(format, new Uint8Array(arrayBuffer), {
497
+ name: "ECDH",
498
+ namedCurve: "P-256"
499
+ }, true, type === "private" ? ["deriveKey"] : []);
500
+ }
501
+ async function encryptContent(content, sharedSecret) {
502
+ const serialized = JSON.stringify(content, (_, value) => {
503
+ if (!(value instanceof Error))
504
+ return value;
505
+ const error = value;
506
+ return Object.assign(Object.assign({}, error.code ? { code: error.code } : {}), { message: error.message });
507
+ });
508
+ return encrypt(sharedSecret, serialized);
509
+ }
510
+ async function decryptContent(encryptedData, sharedSecret) {
511
+ return JSON.parse(await decrypt(sharedSecret, encryptedData));
512
+ }
513
+ const OWN_PRIVATE_KEY = {
514
+ storageKey: "ownPrivateKey",
515
+ keyType: "private"
516
+ };
517
+ const OWN_PUBLIC_KEY = {
518
+ storageKey: "ownPublicKey",
519
+ keyType: "public"
520
+ };
521
+ const PEER_PUBLIC_KEY = {
522
+ storageKey: "peerPublicKey",
523
+ keyType: "public"
524
+ };
525
+ class SCWKeyManager {
526
+ constructor() {
527
+ this.storage = new ScopedLocalStorage("CBWSDK", "SCWKeyManager");
528
+ this.ownPrivateKey = null;
529
+ this.ownPublicKey = null;
530
+ this.peerPublicKey = null;
531
+ this.sharedSecret = null;
532
+ }
533
+ async getOwnPublicKey() {
534
+ await this.loadKeysIfNeeded();
535
+ return this.ownPublicKey;
536
+ }
537
+ // returns null if the shared secret is not yet derived
538
+ async getSharedSecret() {
539
+ await this.loadKeysIfNeeded();
540
+ return this.sharedSecret;
541
+ }
542
+ async setPeerPublicKey(key) {
543
+ this.sharedSecret = null;
544
+ this.peerPublicKey = key;
545
+ await this.storeKey(PEER_PUBLIC_KEY, key);
546
+ await this.loadKeysIfNeeded();
547
+ }
548
+ async clear() {
549
+ this.ownPrivateKey = null;
550
+ this.ownPublicKey = null;
551
+ this.peerPublicKey = null;
552
+ this.sharedSecret = null;
553
+ this.storage.removeItem(OWN_PUBLIC_KEY.storageKey);
554
+ this.storage.removeItem(OWN_PRIVATE_KEY.storageKey);
555
+ this.storage.removeItem(PEER_PUBLIC_KEY.storageKey);
556
+ }
557
+ async generateKeyPair() {
558
+ const newKeyPair = await generateKeyPair();
559
+ this.ownPrivateKey = newKeyPair.privateKey;
560
+ this.ownPublicKey = newKeyPair.publicKey;
561
+ await this.storeKey(OWN_PRIVATE_KEY, newKeyPair.privateKey);
562
+ await this.storeKey(OWN_PUBLIC_KEY, newKeyPair.publicKey);
563
+ }
564
+ async loadKeysIfNeeded() {
565
+ if (this.ownPrivateKey === null) {
566
+ this.ownPrivateKey = await this.loadKey(OWN_PRIVATE_KEY);
567
+ }
568
+ if (this.ownPublicKey === null) {
569
+ this.ownPublicKey = await this.loadKey(OWN_PUBLIC_KEY);
570
+ }
571
+ if (this.ownPrivateKey === null || this.ownPublicKey === null) {
572
+ await this.generateKeyPair();
573
+ }
574
+ if (this.peerPublicKey === null) {
575
+ this.peerPublicKey = await this.loadKey(PEER_PUBLIC_KEY);
576
+ }
577
+ if (this.sharedSecret === null) {
578
+ if (this.ownPrivateKey === null || this.peerPublicKey === null)
579
+ return;
580
+ this.sharedSecret = await deriveSharedSecret(this.ownPrivateKey, this.peerPublicKey);
581
+ }
582
+ }
583
+ // storage methods
584
+ async loadKey(item) {
585
+ const key = this.storage.getItem(item.storageKey);
586
+ if (!key)
587
+ return null;
588
+ return importKeyFromHexString(item.keyType, key);
589
+ }
590
+ async storeKey(item, key) {
591
+ const hexString = await exportKeyToHexString(item.keyType, key);
592
+ this.storage.setItem(item.storageKey, hexString);
593
+ }
594
+ }
595
+ const VERSION = "4.3.0";
596
+ const NAME = "@coinbase/wallet-sdk";
597
+ async function fetchRPCRequest(request, rpcUrl) {
598
+ const requestBody = Object.assign(Object.assign({}, request), { jsonrpc: "2.0", id: crypto.randomUUID() });
599
+ const res = await window.fetch(rpcUrl, {
600
+ method: "POST",
601
+ body: JSON.stringify(requestBody),
602
+ mode: "cors",
603
+ headers: {
604
+ "Content-Type": "application/json",
605
+ "X-Cbw-Sdk-Version": VERSION,
606
+ "X-Cbw-Sdk-Platform": NAME
607
+ }
608
+ });
609
+ const { result, error } = await res.json();
610
+ if (error)
611
+ throw error;
612
+ return result;
613
+ }
614
+ function getCoinbaseInjectedLegacyProvider() {
615
+ const window2 = globalThis;
616
+ return window2.coinbaseWalletExtension;
617
+ }
618
+ function getInjectedEthereum() {
619
+ var _a, _b;
620
+ try {
621
+ const window2 = globalThis;
622
+ return (_a = window2.ethereum) !== null && _a !== void 0 ? _a : (_b = window2.top) === null || _b === void 0 ? void 0 : _b.ethereum;
623
+ } catch (_c) {
624
+ return void 0;
625
+ }
626
+ }
627
+ function getCoinbaseInjectedProvider({ metadata, preference }) {
628
+ var _a, _b;
629
+ const { appName, appLogoUrl, appChainIds } = metadata;
630
+ if (preference.options !== "smartWalletOnly") {
631
+ const extension = getCoinbaseInjectedLegacyProvider();
632
+ if (extension) {
633
+ (_a = extension.setAppInfo) === null || _a === void 0 ? void 0 : _a.call(extension, appName, appLogoUrl, appChainIds, preference);
634
+ return extension;
635
+ }
636
+ }
637
+ const ethereum = getInjectedEthereum();
638
+ if (ethereum === null || ethereum === void 0 ? void 0 : ethereum.isCoinbaseBrowser) {
639
+ (_b = ethereum.setAppInfo) === null || _b === void 0 ? void 0 : _b.call(ethereum, appName, appLogoUrl, appChainIds, preference);
640
+ return ethereum;
641
+ }
642
+ return void 0;
643
+ }
644
+ function checkErrorForInvalidRequestArgs(args) {
645
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
646
+ throw standardErrors.rpc.invalidParams({
647
+ message: "Expected a single, non-array, object argument.",
648
+ data: args
649
+ });
650
+ }
651
+ const { method, params } = args;
652
+ if (typeof method !== "string" || method.length === 0) {
653
+ throw standardErrors.rpc.invalidParams({
654
+ message: "'args.method' must be a non-empty string.",
655
+ data: args
656
+ });
657
+ }
658
+ if (params !== void 0 && !Array.isArray(params) && (typeof params !== "object" || params === null)) {
659
+ throw standardErrors.rpc.invalidParams({
660
+ message: "'args.params' must be an object or array if provided.",
661
+ data: args
662
+ });
663
+ }
664
+ switch (method) {
665
+ case "eth_sign":
666
+ case "eth_signTypedData_v2":
667
+ case "eth_subscribe":
668
+ case "eth_unsubscribe":
669
+ throw standardErrors.provider.unsupportedMethod();
670
+ }
671
+ }
672
+ const ACCOUNTS_KEY = "accounts";
673
+ const ACTIVE_CHAIN_STORAGE_KEY = "activeChain";
674
+ const AVAILABLE_CHAINS_STORAGE_KEY = "availableChains";
675
+ const WALLET_CAPABILITIES_STORAGE_KEY = "walletCapabilities";
676
+ class SCWSigner {
677
+ constructor(params) {
678
+ var _a, _b, _c;
679
+ this.metadata = params.metadata;
680
+ this.communicator = params.communicator;
681
+ this.callback = params.callback;
682
+ this.keyManager = new SCWKeyManager();
683
+ this.storage = new ScopedLocalStorage("CBWSDK", "SCWStateManager");
684
+ this.accounts = (_a = this.storage.loadObject(ACCOUNTS_KEY)) !== null && _a !== void 0 ? _a : [];
685
+ this.chain = this.storage.loadObject(ACTIVE_CHAIN_STORAGE_KEY) || {
686
+ id: (_c = (_b = params.metadata.appChainIds) === null || _b === void 0 ? void 0 : _b[0]) !== null && _c !== void 0 ? _c : 1
687
+ };
688
+ this.handshake = this.handshake.bind(this);
689
+ this.request = this.request.bind(this);
690
+ this.createRequestMessage = this.createRequestMessage.bind(this);
691
+ this.decryptResponseMessage = this.decryptResponseMessage.bind(this);
692
+ }
693
+ async handshake(args) {
694
+ var _a, _b, _c, _d;
695
+ await ((_b = (_a = this.communicator).waitForPopupLoaded) === null || _b === void 0 ? void 0 : _b.call(_a));
696
+ const handshakeMessage = await this.createRequestMessage({
697
+ handshake: {
698
+ method: args.method,
699
+ params: Object.assign({}, this.metadata, (_c = args.params) !== null && _c !== void 0 ? _c : {})
700
+ }
701
+ });
702
+ const response = await this.communicator.postRequestAndWaitForResponse(handshakeMessage);
703
+ if ("failure" in response.content)
704
+ throw response.content.failure;
705
+ const peerPublicKey = await importKeyFromHexString("public", response.sender);
706
+ await this.keyManager.setPeerPublicKey(peerPublicKey);
707
+ const decrypted = await this.decryptResponseMessage(response);
708
+ const result = decrypted.result;
709
+ if ("error" in result)
710
+ throw result.error;
711
+ switch (args.method) {
712
+ case "eth_requestAccounts": {
713
+ const accounts = result.value;
714
+ this.accounts = accounts;
715
+ this.storage.storeObject(ACCOUNTS_KEY, accounts);
716
+ (_d = this.callback) === null || _d === void 0 ? void 0 : _d.call(this, "accountsChanged", accounts);
717
+ break;
718
+ }
719
+ }
720
+ }
721
+ async request(request) {
722
+ var _a;
723
+ if (this.accounts.length === 0) {
724
+ switch (request.method) {
725
+ case "wallet_sendCalls":
726
+ return this.sendRequestToPopup(request);
727
+ default:
728
+ throw standardErrors.provider.unauthorized();
729
+ }
730
+ }
731
+ switch (request.method) {
732
+ case "eth_requestAccounts":
733
+ (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, "connect", { chainId: hexStringFromNumber(this.chain.id) });
734
+ return this.accounts;
735
+ case "eth_accounts":
736
+ return this.accounts;
737
+ case "eth_coinbase":
738
+ return this.accounts[0];
739
+ case "net_version":
740
+ return this.chain.id;
741
+ case "eth_chainId":
742
+ return hexStringFromNumber(this.chain.id);
743
+ case "wallet_getCapabilities":
744
+ return this.storage.loadObject(WALLET_CAPABILITIES_STORAGE_KEY);
745
+ case "wallet_switchEthereumChain":
746
+ return this.handleSwitchChainRequest(request);
747
+ case "eth_ecRecover":
748
+ case "personal_sign":
749
+ case "wallet_sign":
750
+ case "personal_ecRecover":
751
+ case "eth_signTransaction":
752
+ case "eth_sendTransaction":
753
+ case "eth_signTypedData_v1":
754
+ case "eth_signTypedData_v3":
755
+ case "eth_signTypedData_v4":
756
+ case "eth_signTypedData":
757
+ case "wallet_addEthereumChain":
758
+ case "wallet_watchAsset":
759
+ case "wallet_sendCalls":
760
+ case "wallet_showCallsStatus":
761
+ case "wallet_grantPermissions":
762
+ return this.sendRequestToPopup(request);
763
+ default:
764
+ if (!this.chain.rpcUrl)
765
+ throw standardErrors.rpc.internal("No RPC URL set for chain");
766
+ return fetchRPCRequest(request, this.chain.rpcUrl);
767
+ }
768
+ }
769
+ async sendRequestToPopup(request) {
770
+ var _a, _b;
771
+ await ((_b = (_a = this.communicator).waitForPopupLoaded) === null || _b === void 0 ? void 0 : _b.call(_a));
772
+ const response = await this.sendEncryptedRequest(request);
773
+ const decrypted = await this.decryptResponseMessage(response);
774
+ const result = decrypted.result;
775
+ if ("error" in result)
776
+ throw result.error;
777
+ return result.value;
778
+ }
779
+ async cleanup() {
780
+ var _a, _b;
781
+ this.storage.clear();
782
+ await this.keyManager.clear();
783
+ this.accounts = [];
784
+ this.chain = {
785
+ id: (_b = (_a = this.metadata.appChainIds) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : 1
786
+ };
787
+ }
788
+ /**
789
+ * @returns `null` if the request was successful.
790
+ * https://eips.ethereum.org/EIPS/eip-3326#wallet_switchethereumchain
791
+ */
792
+ async handleSwitchChainRequest(request) {
793
+ var _a;
794
+ const params = request.params;
795
+ if (!params || !((_a = params[0]) === null || _a === void 0 ? void 0 : _a.chainId)) {
796
+ throw standardErrors.rpc.invalidParams();
797
+ }
798
+ const chainId = ensureIntNumber(params[0].chainId);
799
+ const localResult = this.updateChain(chainId);
800
+ if (localResult)
801
+ return null;
802
+ const popupResult = await this.sendRequestToPopup(request);
803
+ if (popupResult === null) {
804
+ this.updateChain(chainId);
805
+ }
806
+ return popupResult;
807
+ }
808
+ async sendEncryptedRequest(request) {
809
+ const sharedSecret = await this.keyManager.getSharedSecret();
810
+ if (!sharedSecret) {
811
+ throw standardErrors.provider.unauthorized("No valid session found, try requestAccounts before other methods");
812
+ }
813
+ const encrypted = await encryptContent({
814
+ action: request,
815
+ chainId: this.chain.id
816
+ }, sharedSecret);
817
+ const message = await this.createRequestMessage({ encrypted });
818
+ return this.communicator.postRequestAndWaitForResponse(message);
819
+ }
820
+ async createRequestMessage(content) {
821
+ const publicKey = await exportKeyToHexString("public", await this.keyManager.getOwnPublicKey());
822
+ return {
823
+ id: crypto.randomUUID(),
824
+ sender: publicKey,
825
+ content,
826
+ timestamp: /* @__PURE__ */ new Date()
827
+ };
828
+ }
829
+ async decryptResponseMessage(message) {
830
+ var _a, _b;
831
+ const content = message.content;
832
+ if ("failure" in content) {
833
+ throw content.failure;
834
+ }
835
+ const sharedSecret = await this.keyManager.getSharedSecret();
836
+ if (!sharedSecret) {
837
+ throw standardErrors.provider.unauthorized("Invalid session");
838
+ }
839
+ const response = await decryptContent(content.encrypted, sharedSecret);
840
+ const availableChains = (_a = response.data) === null || _a === void 0 ? void 0 : _a.chains;
841
+ if (availableChains) {
842
+ const chains = Object.entries(availableChains).map(([id, rpcUrl]) => ({
843
+ id: Number(id),
844
+ rpcUrl
845
+ }));
846
+ this.storage.storeObject(AVAILABLE_CHAINS_STORAGE_KEY, chains);
847
+ this.updateChain(this.chain.id, chains);
848
+ }
849
+ const walletCapabilities = (_b = response.data) === null || _b === void 0 ? void 0 : _b.capabilities;
850
+ if (walletCapabilities) {
851
+ this.storage.storeObject(WALLET_CAPABILITIES_STORAGE_KEY, walletCapabilities);
852
+ }
853
+ return response;
854
+ }
855
+ updateChain(chainId, newAvailableChains) {
856
+ var _a;
857
+ const chains = newAvailableChains !== null && newAvailableChains !== void 0 ? newAvailableChains : this.storage.loadObject(AVAILABLE_CHAINS_STORAGE_KEY);
858
+ const chain = chains === null || chains === void 0 ? void 0 : chains.find((chain2) => chain2.id === chainId);
859
+ if (!chain)
860
+ return false;
861
+ if (chain !== this.chain) {
862
+ this.chain = chain;
863
+ this.storage.storeObject(ACTIVE_CHAIN_STORAGE_KEY, chain);
864
+ (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, "chainChanged", hexStringFromNumber(chain.id));
865
+ }
866
+ return true;
867
+ }
868
+ }
869
+ const { keccak_256 } = sha3;
870
+ function zeros(bytes) {
871
+ return Buffer.allocUnsafe(bytes).fill(0);
872
+ }
873
+ function bitLengthFromBigInt(num) {
874
+ return num.toString(2).length;
875
+ }
876
+ function bufferBEFromBigInt(num, length) {
877
+ let hex = num.toString(16);
878
+ if (hex.length % 2 !== 0) hex = "0" + hex;
879
+ const byteArray = hex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16));
880
+ while (byteArray.length < length) {
881
+ byteArray.unshift(0);
882
+ }
883
+ return Buffer.from(byteArray);
884
+ }
885
+ function twosFromBigInt(value, width) {
886
+ const isNegative = value < 0n;
887
+ let result;
888
+ if (isNegative) {
889
+ const mask = (1n << BigInt(width)) - 1n;
890
+ result = (~value & mask) + 1n;
891
+ } else {
892
+ result = value;
893
+ }
894
+ result &= (1n << BigInt(width)) - 1n;
895
+ return result;
896
+ }
897
+ function setLength(msg, length, right) {
898
+ const buf = zeros(length);
899
+ msg = toBuffer(msg);
900
+ if (right) {
901
+ if (msg.length < length) {
902
+ msg.copy(buf);
903
+ return buf;
904
+ }
905
+ return msg.slice(0, length);
906
+ } else {
907
+ if (msg.length < length) {
908
+ msg.copy(buf, length - msg.length);
909
+ return buf;
910
+ }
911
+ return msg.slice(-length);
912
+ }
913
+ }
914
+ function setLengthRight(msg, length) {
915
+ return setLength(msg, length, true);
916
+ }
917
+ function toBuffer(v) {
918
+ if (!Buffer.isBuffer(v)) {
919
+ if (Array.isArray(v)) {
920
+ v = Buffer.from(v);
921
+ } else if (typeof v === "string") {
922
+ if (isHexString(v)) {
923
+ v = Buffer.from(padToEven(stripHexPrefix(v)), "hex");
924
+ } else {
925
+ v = Buffer.from(v);
926
+ }
927
+ } else if (typeof v === "number") {
928
+ v = intToBuffer(v);
929
+ } else if (v === null || v === void 0) {
930
+ v = Buffer.allocUnsafe(0);
931
+ } else if (typeof v === "bigint") {
932
+ v = bufferBEFromBigInt(v);
933
+ } else if (v.toArray) {
934
+ v = Buffer.from(v.toArray());
935
+ } else {
936
+ throw new Error("invalid type");
937
+ }
938
+ }
939
+ return v;
940
+ }
941
+ function bufferToHex(buf) {
942
+ buf = toBuffer(buf);
943
+ return "0x" + buf.toString("hex");
944
+ }
945
+ function keccak(a, bits) {
946
+ a = toBuffer(a);
947
+ if (!bits) bits = 256;
948
+ if (bits !== 256) {
949
+ throw new Error("unsupported");
950
+ }
951
+ return Buffer.from(keccak_256(new Uint8Array(a)));
952
+ }
953
+ function padToEven(str) {
954
+ return str.length % 2 ? "0" + str : str;
955
+ }
956
+ function isHexString(str) {
957
+ return typeof str === "string" && str.match(/^0x[0-9A-Fa-f]*$/);
958
+ }
959
+ function stripHexPrefix(str) {
960
+ if (typeof str === "string" && str.startsWith("0x")) {
961
+ return str.slice(2);
962
+ }
963
+ return str;
964
+ }
965
+ var util$2 = {
966
+ zeros,
967
+ setLength,
968
+ setLengthRight,
969
+ isHexString,
970
+ stripHexPrefix,
971
+ toBuffer,
972
+ bufferToHex,
973
+ keccak,
974
+ bitLengthFromBigInt,
975
+ bufferBEFromBigInt,
976
+ twosFromBigInt
977
+ };
978
+ const util$1 = util$2;
979
+ function elementaryName(name) {
980
+ if (name.startsWith("int[")) {
981
+ return "int256" + name.slice(3);
982
+ } else if (name === "int") {
983
+ return "int256";
984
+ } else if (name.startsWith("uint[")) {
985
+ return "uint256" + name.slice(4);
986
+ } else if (name === "uint") {
987
+ return "uint256";
988
+ } else if (name.startsWith("fixed[")) {
989
+ return "fixed128x128" + name.slice(5);
990
+ } else if (name === "fixed") {
991
+ return "fixed128x128";
992
+ } else if (name.startsWith("ufixed[")) {
993
+ return "ufixed128x128" + name.slice(6);
994
+ } else if (name === "ufixed") {
995
+ return "ufixed128x128";
996
+ }
997
+ return name;
998
+ }
999
+ function parseTypeN(type) {
1000
+ return Number.parseInt(/^\D+(\d+)$/.exec(type)[1], 10);
1001
+ }
1002
+ function parseTypeNxM(type) {
1003
+ var tmp = /^\D+(\d+)x(\d+)$/.exec(type);
1004
+ return [Number.parseInt(tmp[1], 10), Number.parseInt(tmp[2], 10)];
1005
+ }
1006
+ function parseTypeArray(type) {
1007
+ var tmp = type.match(/(.*)\[(.*?)\]$/);
1008
+ if (tmp) {
1009
+ return tmp[2] === "" ? "dynamic" : Number.parseInt(tmp[2], 10);
1010
+ }
1011
+ return null;
1012
+ }
1013
+ function parseNumber(arg) {
1014
+ var type = typeof arg;
1015
+ if (type === "string" || type === "number") {
1016
+ return BigInt(arg);
1017
+ } else if (type === "bigint") {
1018
+ return arg;
1019
+ } else {
1020
+ throw new Error("Argument is not a number");
1021
+ }
1022
+ }
1023
+ function encodeSingle(type, arg) {
1024
+ var size, num, ret, i;
1025
+ if (type === "address") {
1026
+ return encodeSingle("uint160", parseNumber(arg));
1027
+ } else if (type === "bool") {
1028
+ return encodeSingle("uint8", arg ? 1 : 0);
1029
+ } else if (type === "string") {
1030
+ return encodeSingle("bytes", new Buffer(arg, "utf8"));
1031
+ } else if (isArray(type)) {
1032
+ if (typeof arg.length === "undefined") {
1033
+ throw new Error("Not an array?");
1034
+ }
1035
+ size = parseTypeArray(type);
1036
+ if (size !== "dynamic" && size !== 0 && arg.length > size) {
1037
+ throw new Error("Elements exceed array size: " + size);
1038
+ }
1039
+ ret = [];
1040
+ type = type.slice(0, type.lastIndexOf("["));
1041
+ if (typeof arg === "string") {
1042
+ arg = JSON.parse(arg);
1043
+ }
1044
+ for (i in arg) {
1045
+ ret.push(encodeSingle(type, arg[i]));
1046
+ }
1047
+ if (size === "dynamic") {
1048
+ var length = encodeSingle("uint256", arg.length);
1049
+ ret.unshift(length);
1050
+ }
1051
+ return Buffer.concat(ret);
1052
+ } else if (type === "bytes") {
1053
+ arg = new Buffer(arg);
1054
+ ret = Buffer.concat([encodeSingle("uint256", arg.length), arg]);
1055
+ if (arg.length % 32 !== 0) {
1056
+ ret = Buffer.concat([ret, util$1.zeros(32 - arg.length % 32)]);
1057
+ }
1058
+ return ret;
1059
+ } else if (type.startsWith("bytes")) {
1060
+ size = parseTypeN(type);
1061
+ if (size < 1 || size > 32) {
1062
+ throw new Error("Invalid bytes<N> width: " + size);
1063
+ }
1064
+ return util$1.setLengthRight(arg, 32);
1065
+ } else if (type.startsWith("uint")) {
1066
+ size = parseTypeN(type);
1067
+ if (size % 8 || size < 8 || size > 256) {
1068
+ throw new Error("Invalid uint<N> width: " + size);
1069
+ }
1070
+ num = parseNumber(arg);
1071
+ const bitLength = util$1.bitLengthFromBigInt(num);
1072
+ if (bitLength > size) {
1073
+ throw new Error("Supplied uint exceeds width: " + size + " vs " + bitLength);
1074
+ }
1075
+ if (num < 0) {
1076
+ throw new Error("Supplied uint is negative");
1077
+ }
1078
+ return util$1.bufferBEFromBigInt(num, 32);
1079
+ } else if (type.startsWith("int")) {
1080
+ size = parseTypeN(type);
1081
+ if (size % 8 || size < 8 || size > 256) {
1082
+ throw new Error("Invalid int<N> width: " + size);
1083
+ }
1084
+ num = parseNumber(arg);
1085
+ const bitLength = util$1.bitLengthFromBigInt(num);
1086
+ if (bitLength > size) {
1087
+ throw new Error("Supplied int exceeds width: " + size + " vs " + bitLength);
1088
+ }
1089
+ const twos = util$1.twosFromBigInt(num, 256);
1090
+ return util$1.bufferBEFromBigInt(twos, 32);
1091
+ } else if (type.startsWith("ufixed")) {
1092
+ size = parseTypeNxM(type);
1093
+ num = parseNumber(arg);
1094
+ if (num < 0) {
1095
+ throw new Error("Supplied ufixed is negative");
1096
+ }
1097
+ return encodeSingle("uint256", num * BigInt(2) ** BigInt(size[1]));
1098
+ } else if (type.startsWith("fixed")) {
1099
+ size = parseTypeNxM(type);
1100
+ return encodeSingle("int256", parseNumber(arg) * BigInt(2) ** BigInt(size[1]));
1101
+ }
1102
+ throw new Error("Unsupported or invalid type: " + type);
1103
+ }
1104
+ function isDynamic(type) {
1105
+ return type === "string" || type === "bytes" || parseTypeArray(type) === "dynamic";
1106
+ }
1107
+ function isArray(type) {
1108
+ return type.lastIndexOf("]") === type.length - 1;
1109
+ }
1110
+ function rawEncode(types, values) {
1111
+ var output = [];
1112
+ var data = [];
1113
+ var headLength = 32 * types.length;
1114
+ for (var i in types) {
1115
+ var type = elementaryName(types[i]);
1116
+ var value = values[i];
1117
+ var cur = encodeSingle(type, value);
1118
+ if (isDynamic(type)) {
1119
+ output.push(encodeSingle("uint256", headLength));
1120
+ data.push(cur);
1121
+ headLength += cur.length;
1122
+ } else {
1123
+ output.push(cur);
1124
+ }
1125
+ }
1126
+ return Buffer.concat(output.concat(data));
1127
+ }
1128
+ function solidityPack(types, values) {
1129
+ if (types.length !== values.length) {
1130
+ throw new Error("Number of types are not matching the values");
1131
+ }
1132
+ var size, num;
1133
+ var ret = [];
1134
+ for (var i = 0; i < types.length; i++) {
1135
+ var type = elementaryName(types[i]);
1136
+ var value = values[i];
1137
+ if (type === "bytes") {
1138
+ ret.push(value);
1139
+ } else if (type === "string") {
1140
+ ret.push(new Buffer(value, "utf8"));
1141
+ } else if (type === "bool") {
1142
+ ret.push(new Buffer(value ? "01" : "00", "hex"));
1143
+ } else if (type === "address") {
1144
+ ret.push(util$1.setLength(value, 20));
1145
+ } else if (type.startsWith("bytes")) {
1146
+ size = parseTypeN(type);
1147
+ if (size < 1 || size > 32) {
1148
+ throw new Error("Invalid bytes<N> width: " + size);
1149
+ }
1150
+ ret.push(util$1.setLengthRight(value, size));
1151
+ } else if (type.startsWith("uint")) {
1152
+ size = parseTypeN(type);
1153
+ if (size % 8 || size < 8 || size > 256) {
1154
+ throw new Error("Invalid uint<N> width: " + size);
1155
+ }
1156
+ num = parseNumber(value);
1157
+ const bitLength = util$1.bitLengthFromBigInt(num);
1158
+ if (bitLength > size) {
1159
+ throw new Error("Supplied uint exceeds width: " + size + " vs " + bitLength);
1160
+ }
1161
+ ret.push(util$1.bufferBEFromBigInt(num, size / 8));
1162
+ } else if (type.startsWith("int")) {
1163
+ size = parseTypeN(type);
1164
+ if (size % 8 || size < 8 || size > 256) {
1165
+ throw new Error("Invalid int<N> width: " + size);
1166
+ }
1167
+ num = parseNumber(value);
1168
+ const bitLength = util$1.bitLengthFromBigInt(num);
1169
+ if (bitLength > size) {
1170
+ throw new Error("Supplied int exceeds width: " + size + " vs " + bitLength);
1171
+ }
1172
+ const twos = util$1.twosFromBigInt(num, size);
1173
+ ret.push(util$1.bufferBEFromBigInt(twos, size / 8));
1174
+ } else {
1175
+ throw new Error("Unsupported or invalid type: " + type);
1176
+ }
1177
+ }
1178
+ return Buffer.concat(ret);
1179
+ }
1180
+ function soliditySHA3(types, values) {
1181
+ return util$1.keccak(solidityPack(types, values));
1182
+ }
1183
+ var abi$1 = {
1184
+ rawEncode,
1185
+ solidityPack,
1186
+ soliditySHA3
1187
+ };
1188
+ const util = util$2;
1189
+ const abi = abi$1;
1190
+ const TYPED_MESSAGE_SCHEMA = {
1191
+ type: "object",
1192
+ properties: {
1193
+ types: {
1194
+ type: "object",
1195
+ additionalProperties: {
1196
+ type: "array",
1197
+ items: {
1198
+ type: "object",
1199
+ properties: {
1200
+ name: { type: "string" },
1201
+ type: { type: "string" }
1202
+ },
1203
+ required: ["name", "type"]
1204
+ }
1205
+ }
1206
+ },
1207
+ primaryType: { type: "string" },
1208
+ domain: { type: "object" },
1209
+ message: { type: "object" }
1210
+ },
1211
+ required: ["types", "primaryType", "domain", "message"]
1212
+ };
1213
+ const TypedDataUtils = {
1214
+ /**
1215
+ * Encodes an object by encoding and concatenating each of its members
1216
+ *
1217
+ * @param {string} primaryType - Root type
1218
+ * @param {Object} data - Object to encode
1219
+ * @param {Object} types - Type definitions
1220
+ * @returns {string} - Encoded representation of an object
1221
+ */
1222
+ encodeData(primaryType, data, types, useV4 = true) {
1223
+ const encodedTypes = ["bytes32"];
1224
+ const encodedValues = [this.hashType(primaryType, types)];
1225
+ if (useV4) {
1226
+ const encodeField = (name, type, value) => {
1227
+ if (types[type] !== void 0) {
1228
+ return ["bytes32", value == null ? "0x0000000000000000000000000000000000000000000000000000000000000000" : util.keccak(this.encodeData(type, value, types, useV4))];
1229
+ }
1230
+ if (value === void 0)
1231
+ throw new Error(`missing value for field ${name} of type ${type}`);
1232
+ if (type === "bytes") {
1233
+ return ["bytes32", util.keccak(value)];
1234
+ }
1235
+ if (type === "string") {
1236
+ if (typeof value === "string") {
1237
+ value = Buffer.from(value, "utf8");
1238
+ }
1239
+ return ["bytes32", util.keccak(value)];
1240
+ }
1241
+ if (type.lastIndexOf("]") === type.length - 1) {
1242
+ const parsedType = type.slice(0, type.lastIndexOf("["));
1243
+ const typeValuePairs = value.map((item) => encodeField(name, parsedType, item));
1244
+ return ["bytes32", util.keccak(abi.rawEncode(
1245
+ typeValuePairs.map(([type2]) => type2),
1246
+ typeValuePairs.map(([, value2]) => value2)
1247
+ ))];
1248
+ }
1249
+ return [type, value];
1250
+ };
1251
+ for (const field of types[primaryType]) {
1252
+ const [type, value] = encodeField(field.name, field.type, data[field.name]);
1253
+ encodedTypes.push(type);
1254
+ encodedValues.push(value);
1255
+ }
1256
+ } else {
1257
+ for (const field of types[primaryType]) {
1258
+ let value = data[field.name];
1259
+ if (value !== void 0) {
1260
+ if (field.type === "bytes") {
1261
+ encodedTypes.push("bytes32");
1262
+ value = util.keccak(value);
1263
+ encodedValues.push(value);
1264
+ } else if (field.type === "string") {
1265
+ encodedTypes.push("bytes32");
1266
+ if (typeof value === "string") {
1267
+ value = Buffer.from(value, "utf8");
1268
+ }
1269
+ value = util.keccak(value);
1270
+ encodedValues.push(value);
1271
+ } else if (types[field.type] !== void 0) {
1272
+ encodedTypes.push("bytes32");
1273
+ value = util.keccak(this.encodeData(field.type, value, types, useV4));
1274
+ encodedValues.push(value);
1275
+ } else if (field.type.lastIndexOf("]") === field.type.length - 1) {
1276
+ throw new Error("Arrays currently unimplemented in encodeData");
1277
+ } else {
1278
+ encodedTypes.push(field.type);
1279
+ encodedValues.push(value);
1280
+ }
1281
+ }
1282
+ }
1283
+ }
1284
+ return abi.rawEncode(encodedTypes, encodedValues);
1285
+ },
1286
+ /**
1287
+ * Encodes the type of an object by encoding a comma delimited list of its members
1288
+ *
1289
+ * @param {string} primaryType - Root type to encode
1290
+ * @param {Object} types - Type definitions
1291
+ * @returns {string} - Encoded representation of the type of an object
1292
+ */
1293
+ encodeType(primaryType, types) {
1294
+ let result = "";
1295
+ let deps = this.findTypeDependencies(primaryType, types).filter((dep) => dep !== primaryType);
1296
+ deps = [primaryType].concat(deps.sort());
1297
+ for (const type of deps) {
1298
+ const children = types[type];
1299
+ if (!children) {
1300
+ throw new Error("No type definition specified: " + type);
1301
+ }
1302
+ result += type + "(" + types[type].map(({ name, type: type2 }) => type2 + " " + name).join(",") + ")";
1303
+ }
1304
+ return result;
1305
+ },
1306
+ /**
1307
+ * Finds all types within a type definition object
1308
+ *
1309
+ * @param {string} primaryType - Root type
1310
+ * @param {Object} types - Type definitions
1311
+ * @param {Array} results - current set of accumulated types
1312
+ * @returns {Array} - Set of all types found in the type definition
1313
+ */
1314
+ findTypeDependencies(primaryType, types, results = []) {
1315
+ primaryType = primaryType.match(/^\w*/)[0];
1316
+ if (results.includes(primaryType) || types[primaryType] === void 0) {
1317
+ return results;
1318
+ }
1319
+ results.push(primaryType);
1320
+ for (const field of types[primaryType]) {
1321
+ for (const dep of this.findTypeDependencies(field.type, types, results)) {
1322
+ !results.includes(dep) && results.push(dep);
1323
+ }
1324
+ }
1325
+ return results;
1326
+ },
1327
+ /**
1328
+ * Hashes an object
1329
+ *
1330
+ * @param {string} primaryType - Root type
1331
+ * @param {Object} data - Object to hash
1332
+ * @param {Object} types - Type definitions
1333
+ * @returns {Buffer} - Hash of an object
1334
+ */
1335
+ hashStruct(primaryType, data, types, useV4 = true) {
1336
+ return util.keccak(this.encodeData(primaryType, data, types, useV4));
1337
+ },
1338
+ /**
1339
+ * Hashes the type of an object
1340
+ *
1341
+ * @param {string} primaryType - Root type to hash
1342
+ * @param {Object} types - Type definitions
1343
+ * @returns {string} - Hash of an object
1344
+ */
1345
+ hashType(primaryType, types) {
1346
+ return util.keccak(this.encodeType(primaryType, types));
1347
+ },
1348
+ /**
1349
+ * Removes properties from a message object that are not defined per EIP-712
1350
+ *
1351
+ * @param {Object} data - typed message object
1352
+ * @returns {Object} - typed message object with only allowed fields
1353
+ */
1354
+ sanitizeData(data) {
1355
+ const sanitizedData = {};
1356
+ for (const key in TYPED_MESSAGE_SCHEMA.properties) {
1357
+ data[key] && (sanitizedData[key] = data[key]);
1358
+ }
1359
+ if (sanitizedData.types) {
1360
+ sanitizedData.types = Object.assign({ EIP712Domain: [] }, sanitizedData.types);
1361
+ }
1362
+ return sanitizedData;
1363
+ },
1364
+ /**
1365
+ * Returns the hash of a typed message as per EIP-712 for signing
1366
+ *
1367
+ * @param {Object} typedData - Types message data to sign
1368
+ * @returns {string} - sha3 hash for signing
1369
+ */
1370
+ hash(typedData, useV4 = true) {
1371
+ const sanitizedData = this.sanitizeData(typedData);
1372
+ const parts = [Buffer.from("1901", "hex")];
1373
+ parts.push(this.hashStruct("EIP712Domain", sanitizedData.domain, sanitizedData.types, useV4));
1374
+ if (sanitizedData.primaryType !== "EIP712Domain") {
1375
+ parts.push(this.hashStruct(sanitizedData.primaryType, sanitizedData.message, sanitizedData.types, useV4));
1376
+ }
1377
+ return util.keccak(Buffer.concat(parts));
1378
+ }
1379
+ };
1380
+ var ethEip712Util = {
1381
+ TYPED_MESSAGE_SCHEMA,
1382
+ TypedDataUtils,
1383
+ hashForSignTypedDataLegacy: function(msgParams) {
1384
+ return typedSignatureHashLegacy(msgParams.data);
1385
+ },
1386
+ hashForSignTypedData_v3: function(msgParams) {
1387
+ return TypedDataUtils.hash(msgParams.data, false);
1388
+ },
1389
+ hashForSignTypedData_v4: function(msgParams) {
1390
+ return TypedDataUtils.hash(msgParams.data);
1391
+ }
1392
+ };
1393
+ function typedSignatureHashLegacy(typedData) {
1394
+ const error = new Error("Expect argument to be non-empty array");
1395
+ if (typeof typedData !== "object" || !typedData.length) throw error;
1396
+ const data = typedData.map(function(e) {
1397
+ return e.type === "bytes" ? util.toBuffer(e.value) : e.value;
1398
+ });
1399
+ const types = typedData.map(function(e) {
1400
+ return e.type;
1401
+ });
1402
+ const schema = typedData.map(function(e) {
1403
+ if (!e.name) throw error;
1404
+ return e.type + " " + e.name;
1405
+ });
1406
+ return abi.soliditySHA3(
1407
+ ["bytes32", "bytes32"],
1408
+ [
1409
+ abi.soliditySHA3(new Array(typedData.length).fill("string"), schema),
1410
+ abi.soliditySHA3(types, data)
1411
+ ]
1412
+ );
1413
+ }
1414
+ const eip712 = /* @__PURE__ */ getDefaultExportFromCjs(ethEip712Util);
1415
+ const WALLET_USER_NAME_KEY = "walletUsername";
1416
+ const LOCAL_STORAGE_ADDRESSES_KEY = "Addresses";
1417
+ const APP_VERSION_KEY = "AppVersion";
1418
+ function isErrorResponse(response) {
1419
+ return response.errorMessage !== void 0;
1420
+ }
1421
+ class WalletLinkCipher {
1422
+ // @param secret hex representation of 32-byte secret
1423
+ constructor(secret) {
1424
+ this.secret = secret;
1425
+ }
1426
+ /**
1427
+ *
1428
+ * @param plainText string to be encrypted
1429
+ * returns hex string representation of bytes in the order: initialization vector (iv),
1430
+ * auth tag, encrypted plaintext. IV is 12 bytes. Auth tag is 16 bytes. Remaining bytes are the
1431
+ * encrypted plainText.
1432
+ */
1433
+ async encrypt(plainText) {
1434
+ const secret = this.secret;
1435
+ if (secret.length !== 64)
1436
+ throw Error(`secret must be 256 bits`);
1437
+ const ivBytes = crypto.getRandomValues(new Uint8Array(12));
1438
+ const secretKey = await crypto.subtle.importKey("raw", hexStringToUint8Array(secret), { name: "aes-gcm" }, false, ["encrypt", "decrypt"]);
1439
+ const enc = new TextEncoder();
1440
+ const encryptedResult = await window.crypto.subtle.encrypt({
1441
+ name: "AES-GCM",
1442
+ iv: ivBytes
1443
+ }, secretKey, enc.encode(plainText));
1444
+ const tagLength = 16;
1445
+ const authTag = encryptedResult.slice(encryptedResult.byteLength - tagLength);
1446
+ const encryptedPlaintext = encryptedResult.slice(0, encryptedResult.byteLength - tagLength);
1447
+ const authTagBytes = new Uint8Array(authTag);
1448
+ const encryptedPlaintextBytes = new Uint8Array(encryptedPlaintext);
1449
+ const concatted = new Uint8Array([...ivBytes, ...authTagBytes, ...encryptedPlaintextBytes]);
1450
+ return uint8ArrayToHex(concatted);
1451
+ }
1452
+ /**
1453
+ *
1454
+ * @param cipherText hex string representation of bytes in the order: initialization vector (iv),
1455
+ * auth tag, encrypted plaintext. IV is 12 bytes. Auth tag is 16 bytes.
1456
+ */
1457
+ async decrypt(cipherText) {
1458
+ const secret = this.secret;
1459
+ if (secret.length !== 64)
1460
+ throw Error(`secret must be 256 bits`);
1461
+ return new Promise((resolve, reject) => {
1462
+ void async function() {
1463
+ const secretKey = await crypto.subtle.importKey("raw", hexStringToUint8Array(secret), { name: "aes-gcm" }, false, ["encrypt", "decrypt"]);
1464
+ const encrypted = hexStringToUint8Array(cipherText);
1465
+ const ivBytes = encrypted.slice(0, 12);
1466
+ const authTagBytes = encrypted.slice(12, 28);
1467
+ const encryptedPlaintextBytes = encrypted.slice(28);
1468
+ const concattedBytes = new Uint8Array([...encryptedPlaintextBytes, ...authTagBytes]);
1469
+ const algo = {
1470
+ name: "AES-GCM",
1471
+ iv: new Uint8Array(ivBytes)
1472
+ };
1473
+ try {
1474
+ const decrypted = await window.crypto.subtle.decrypt(algo, secretKey, concattedBytes);
1475
+ const decoder = new TextDecoder();
1476
+ resolve(decoder.decode(decrypted));
1477
+ } catch (err) {
1478
+ reject(err);
1479
+ }
1480
+ }();
1481
+ });
1482
+ }
1483
+ }
1484
+ class WalletLinkHTTP {
1485
+ constructor(linkAPIUrl, sessionId, sessionKey) {
1486
+ this.linkAPIUrl = linkAPIUrl;
1487
+ this.sessionId = sessionId;
1488
+ const credentials = `${sessionId}:${sessionKey}`;
1489
+ this.auth = `Basic ${btoa(credentials)}`;
1490
+ }
1491
+ // mark unseen events as seen
1492
+ async markUnseenEventsAsSeen(events) {
1493
+ return Promise.all(events.map((e) => fetch(`${this.linkAPIUrl}/events/${e.eventId}/seen`, {
1494
+ method: "POST",
1495
+ headers: {
1496
+ Authorization: this.auth
1497
+ }
1498
+ }))).catch((error) => console.error("Unabled to mark event as failed:", error));
1499
+ }
1500
+ async fetchUnseenEvents() {
1501
+ var _a;
1502
+ const response = await fetch(`${this.linkAPIUrl}/events?unseen=true`, {
1503
+ headers: {
1504
+ Authorization: this.auth
1505
+ }
1506
+ });
1507
+ if (response.ok) {
1508
+ const { events, error } = await response.json();
1509
+ if (error) {
1510
+ throw new Error(`Check unseen events failed: ${error}`);
1511
+ }
1512
+ const responseEvents = (_a = events === null || events === void 0 ? void 0 : events.filter((e) => e.event === "Web3Response").map((e) => ({
1513
+ type: "Event",
1514
+ sessionId: this.sessionId,
1515
+ eventId: e.id,
1516
+ event: e.event,
1517
+ data: e.data
1518
+ }))) !== null && _a !== void 0 ? _a : [];
1519
+ this.markUnseenEventsAsSeen(responseEvents);
1520
+ return responseEvents;
1521
+ }
1522
+ throw new Error(`Check unseen events failed: ${response.status}`);
1523
+ }
1524
+ }
1525
+ var ConnectionState;
1526
+ (function(ConnectionState2) {
1527
+ ConnectionState2[ConnectionState2["DISCONNECTED"] = 0] = "DISCONNECTED";
1528
+ ConnectionState2[ConnectionState2["CONNECTING"] = 1] = "CONNECTING";
1529
+ ConnectionState2[ConnectionState2["CONNECTED"] = 2] = "CONNECTED";
1530
+ })(ConnectionState || (ConnectionState = {}));
1531
+ class WalletLinkWebSocket {
1532
+ setConnectionStateListener(listener) {
1533
+ this.connectionStateListener = listener;
1534
+ }
1535
+ setIncomingDataListener(listener) {
1536
+ this.incomingDataListener = listener;
1537
+ }
1538
+ /**
1539
+ * Constructor
1540
+ * @param url WebSocket server URL
1541
+ * @param [WebSocketClass] Custom WebSocket implementation
1542
+ */
1543
+ constructor(url, WebSocketClass = WebSocket) {
1544
+ this.WebSocketClass = WebSocketClass;
1545
+ this.webSocket = null;
1546
+ this.pendingData = [];
1547
+ this.url = url.replace(/^http/, "ws");
1548
+ }
1549
+ /**
1550
+ * Make a websocket connection
1551
+ * @returns a Promise that resolves when connected
1552
+ */
1553
+ async connect() {
1554
+ if (this.webSocket) {
1555
+ throw new Error("webSocket object is not null");
1556
+ }
1557
+ return new Promise((resolve, reject) => {
1558
+ var _a;
1559
+ let webSocket;
1560
+ try {
1561
+ this.webSocket = webSocket = new this.WebSocketClass(this.url);
1562
+ } catch (err) {
1563
+ reject(err);
1564
+ return;
1565
+ }
1566
+ (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.CONNECTING);
1567
+ webSocket.onclose = (evt) => {
1568
+ var _a2;
1569
+ this.clearWebSocket();
1570
+ reject(new Error(`websocket error ${evt.code}: ${evt.reason}`));
1571
+ (_a2 = this.connectionStateListener) === null || _a2 === void 0 ? void 0 : _a2.call(this, ConnectionState.DISCONNECTED);
1572
+ };
1573
+ webSocket.onopen = (_) => {
1574
+ var _a2;
1575
+ resolve();
1576
+ (_a2 = this.connectionStateListener) === null || _a2 === void 0 ? void 0 : _a2.call(this, ConnectionState.CONNECTED);
1577
+ if (this.pendingData.length > 0) {
1578
+ const pending = [...this.pendingData];
1579
+ pending.forEach((data) => this.sendData(data));
1580
+ this.pendingData = [];
1581
+ }
1582
+ };
1583
+ webSocket.onmessage = (evt) => {
1584
+ var _a2, _b;
1585
+ if (evt.data === "h") {
1586
+ (_a2 = this.incomingDataListener) === null || _a2 === void 0 ? void 0 : _a2.call(this, {
1587
+ type: "Heartbeat"
1588
+ });
1589
+ } else {
1590
+ try {
1591
+ const message = JSON.parse(evt.data);
1592
+ (_b = this.incomingDataListener) === null || _b === void 0 ? void 0 : _b.call(this, message);
1593
+ } catch (_c) {
1594
+ }
1595
+ }
1596
+ };
1597
+ });
1598
+ }
1599
+ /**
1600
+ * Disconnect from server
1601
+ */
1602
+ disconnect() {
1603
+ var _a;
1604
+ const { webSocket } = this;
1605
+ if (!webSocket) {
1606
+ return;
1607
+ }
1608
+ this.clearWebSocket();
1609
+ (_a = this.connectionStateListener) === null || _a === void 0 ? void 0 : _a.call(this, ConnectionState.DISCONNECTED);
1610
+ this.connectionStateListener = void 0;
1611
+ this.incomingDataListener = void 0;
1612
+ try {
1613
+ webSocket.close();
1614
+ } catch (_b) {
1615
+ }
1616
+ }
1617
+ /**
1618
+ * Send data to server
1619
+ * @param data text to send
1620
+ */
1621
+ sendData(data) {
1622
+ const { webSocket } = this;
1623
+ if (!webSocket) {
1624
+ this.pendingData.push(data);
1625
+ this.connect();
1626
+ return;
1627
+ }
1628
+ webSocket.send(data);
1629
+ }
1630
+ clearWebSocket() {
1631
+ const { webSocket } = this;
1632
+ if (!webSocket) {
1633
+ return;
1634
+ }
1635
+ this.webSocket = null;
1636
+ webSocket.onclose = null;
1637
+ webSocket.onerror = null;
1638
+ webSocket.onmessage = null;
1639
+ webSocket.onopen = null;
1640
+ }
1641
+ }
1642
+ const HEARTBEAT_INTERVAL = 1e4;
1643
+ const REQUEST_TIMEOUT = 6e4;
1644
+ class WalletLinkConnection {
1645
+ /**
1646
+ * Constructor
1647
+ * @param session Session
1648
+ * @param linkAPIUrl Coinbase Wallet link server URL
1649
+ * @param listener WalletLinkConnectionUpdateListener
1650
+ * @param [WebSocketClass] Custom WebSocket implementation
1651
+ */
1652
+ constructor({ session, linkAPIUrl, listener }) {
1653
+ this.destroyed = false;
1654
+ this.lastHeartbeatResponse = 0;
1655
+ this.nextReqId = IntNumber(1);
1656
+ this._connected = false;
1657
+ this._linked = false;
1658
+ this.shouldFetchUnseenEventsOnConnect = false;
1659
+ this.requestResolutions = /* @__PURE__ */ new Map();
1660
+ this.handleSessionMetadataUpdated = (metadata) => {
1661
+ if (!metadata)
1662
+ return;
1663
+ const handlers = /* @__PURE__ */ new Map([
1664
+ ["__destroyed", this.handleDestroyed],
1665
+ ["EthereumAddress", this.handleAccountUpdated],
1666
+ ["WalletUsername", this.handleWalletUsernameUpdated],
1667
+ ["AppVersion", this.handleAppVersionUpdated],
1668
+ [
1669
+ "ChainId",
1670
+ // ChainId and JsonRpcUrl are always updated together
1671
+ (v) => metadata.JsonRpcUrl && this.handleChainUpdated(v, metadata.JsonRpcUrl)
1672
+ ]
1673
+ ]);
1674
+ handlers.forEach((handler, key) => {
1675
+ const value = metadata[key];
1676
+ if (value === void 0)
1677
+ return;
1678
+ handler(value);
1679
+ });
1680
+ };
1681
+ this.handleDestroyed = (__destroyed) => {
1682
+ var _a;
1683
+ if (__destroyed !== "1")
1684
+ return;
1685
+ (_a = this.listener) === null || _a === void 0 ? void 0 : _a.resetAndReload();
1686
+ };
1687
+ this.handleAccountUpdated = async (encryptedEthereumAddress) => {
1688
+ var _a;
1689
+ const address = await this.cipher.decrypt(encryptedEthereumAddress);
1690
+ (_a = this.listener) === null || _a === void 0 ? void 0 : _a.accountUpdated(address);
1691
+ };
1692
+ this.handleMetadataUpdated = async (key, encryptedMetadataValue) => {
1693
+ var _a;
1694
+ const decryptedValue = await this.cipher.decrypt(encryptedMetadataValue);
1695
+ (_a = this.listener) === null || _a === void 0 ? void 0 : _a.metadataUpdated(key, decryptedValue);
1696
+ };
1697
+ this.handleWalletUsernameUpdated = async (walletUsername) => {
1698
+ this.handleMetadataUpdated(WALLET_USER_NAME_KEY, walletUsername);
1699
+ };
1700
+ this.handleAppVersionUpdated = async (appVersion) => {
1701
+ this.handleMetadataUpdated(APP_VERSION_KEY, appVersion);
1702
+ };
1703
+ this.handleChainUpdated = async (encryptedChainId, encryptedJsonRpcUrl) => {
1704
+ var _a;
1705
+ const chainId = await this.cipher.decrypt(encryptedChainId);
1706
+ const jsonRpcUrl = await this.cipher.decrypt(encryptedJsonRpcUrl);
1707
+ (_a = this.listener) === null || _a === void 0 ? void 0 : _a.chainUpdated(chainId, jsonRpcUrl);
1708
+ };
1709
+ this.session = session;
1710
+ this.cipher = new WalletLinkCipher(session.secret);
1711
+ this.listener = listener;
1712
+ const ws = new WalletLinkWebSocket(`${linkAPIUrl}/rpc`, WebSocket);
1713
+ ws.setConnectionStateListener(async (state) => {
1714
+ let connected = false;
1715
+ switch (state) {
1716
+ case ConnectionState.DISCONNECTED:
1717
+ if (!this.destroyed) {
1718
+ const connect = async () => {
1719
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
1720
+ if (!this.destroyed) {
1721
+ ws.connect().catch(() => {
1722
+ connect();
1723
+ });
1724
+ }
1725
+ };
1726
+ connect();
1727
+ }
1728
+ break;
1729
+ case ConnectionState.CONNECTED:
1730
+ connected = await this.handleConnected();
1731
+ this.updateLastHeartbeat();
1732
+ setInterval(() => {
1733
+ this.heartbeat();
1734
+ }, HEARTBEAT_INTERVAL);
1735
+ if (this.shouldFetchUnseenEventsOnConnect) {
1736
+ this.fetchUnseenEventsAPI();
1737
+ }
1738
+ break;
1739
+ case ConnectionState.CONNECTING:
1740
+ break;
1741
+ }
1742
+ if (this.connected !== connected) {
1743
+ this.connected = connected;
1744
+ }
1745
+ });
1746
+ ws.setIncomingDataListener((m) => {
1747
+ var _a;
1748
+ switch (m.type) {
1749
+ case "Heartbeat":
1750
+ this.updateLastHeartbeat();
1751
+ return;
1752
+ case "IsLinkedOK":
1753
+ case "Linked": {
1754
+ const linked = m.type === "IsLinkedOK" ? m.linked : void 0;
1755
+ this.linked = linked || m.onlineGuests > 0;
1756
+ break;
1757
+ }
1758
+ case "GetSessionConfigOK":
1759
+ case "SessionConfigUpdated": {
1760
+ this.handleSessionMetadataUpdated(m.metadata);
1761
+ break;
1762
+ }
1763
+ case "Event": {
1764
+ this.handleIncomingEvent(m);
1765
+ break;
1766
+ }
1767
+ }
1768
+ if (m.id !== void 0) {
1769
+ (_a = this.requestResolutions.get(m.id)) === null || _a === void 0 ? void 0 : _a(m);
1770
+ }
1771
+ });
1772
+ this.ws = ws;
1773
+ this.http = new WalletLinkHTTP(linkAPIUrl, session.id, session.key);
1774
+ }
1775
+ /**
1776
+ * Make a connection to the server
1777
+ */
1778
+ connect() {
1779
+ if (this.destroyed) {
1780
+ throw new Error("instance is destroyed");
1781
+ }
1782
+ this.ws.connect();
1783
+ }
1784
+ /**
1785
+ * Terminate connection, and mark as destroyed. To reconnect, create a new
1786
+ * instance of WalletSDKConnection
1787
+ */
1788
+ async destroy() {
1789
+ if (this.destroyed)
1790
+ return;
1791
+ await this.makeRequest({
1792
+ type: "SetSessionConfig",
1793
+ id: IntNumber(this.nextReqId++),
1794
+ sessionId: this.session.id,
1795
+ metadata: { __destroyed: "1" }
1796
+ }, { timeout: 1e3 });
1797
+ this.destroyed = true;
1798
+ this.ws.disconnect();
1799
+ this.listener = void 0;
1800
+ }
1801
+ get connected() {
1802
+ return this._connected;
1803
+ }
1804
+ set connected(connected) {
1805
+ this._connected = connected;
1806
+ }
1807
+ get linked() {
1808
+ return this._linked;
1809
+ }
1810
+ set linked(linked) {
1811
+ var _a, _b;
1812
+ this._linked = linked;
1813
+ if (linked)
1814
+ (_a = this.onceLinked) === null || _a === void 0 ? void 0 : _a.call(this);
1815
+ (_b = this.listener) === null || _b === void 0 ? void 0 : _b.linkedUpdated(linked);
1816
+ }
1817
+ setOnceLinked(callback) {
1818
+ return new Promise((resolve) => {
1819
+ if (this.linked) {
1820
+ callback().then(resolve);
1821
+ } else {
1822
+ this.onceLinked = () => {
1823
+ callback().then(resolve);
1824
+ this.onceLinked = void 0;
1825
+ };
1826
+ }
1827
+ });
1828
+ }
1829
+ async handleIncomingEvent(m) {
1830
+ var _a;
1831
+ if (m.type !== "Event" || m.event !== "Web3Response") {
1832
+ return;
1833
+ }
1834
+ const decryptedData = await this.cipher.decrypt(m.data);
1835
+ const message = JSON.parse(decryptedData);
1836
+ if (message.type !== "WEB3_RESPONSE")
1837
+ return;
1838
+ const { id, response } = message;
1839
+ (_a = this.listener) === null || _a === void 0 ? void 0 : _a.handleWeb3ResponseMessage(id, response);
1840
+ }
1841
+ async checkUnseenEvents() {
1842
+ if (!this.connected) {
1843
+ this.shouldFetchUnseenEventsOnConnect = true;
1844
+ return;
1845
+ }
1846
+ await new Promise((resolve) => setTimeout(resolve, 250));
1847
+ try {
1848
+ await this.fetchUnseenEventsAPI();
1849
+ } catch (e) {
1850
+ console.error("Unable to check for unseen events", e);
1851
+ }
1852
+ }
1853
+ async fetchUnseenEventsAPI() {
1854
+ this.shouldFetchUnseenEventsOnConnect = false;
1855
+ const responseEvents = await this.http.fetchUnseenEvents();
1856
+ responseEvents.forEach((e) => this.handleIncomingEvent(e));
1857
+ }
1858
+ /**
1859
+ * Publish an event and emit event ID when successful
1860
+ * @param event event name
1861
+ * @param unencryptedData unencrypted event data
1862
+ * @param callWebhook whether the webhook should be invoked
1863
+ * @returns a Promise that emits event ID when successful
1864
+ */
1865
+ async publishEvent(event, unencryptedData, callWebhook = false) {
1866
+ const data = await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({}, unencryptedData), { origin: location.origin, location: location.href, relaySource: "coinbaseWalletExtension" in window && window.coinbaseWalletExtension ? "injected_sdk" : "sdk" })));
1867
+ const message = {
1868
+ type: "PublishEvent",
1869
+ id: IntNumber(this.nextReqId++),
1870
+ sessionId: this.session.id,
1871
+ event,
1872
+ data,
1873
+ callWebhook
1874
+ };
1875
+ return this.setOnceLinked(async () => {
1876
+ const res = await this.makeRequest(message);
1877
+ if (res.type === "Fail") {
1878
+ throw new Error(res.error || "failed to publish event");
1879
+ }
1880
+ return res.eventId;
1881
+ });
1882
+ }
1883
+ sendData(message) {
1884
+ this.ws.sendData(JSON.stringify(message));
1885
+ }
1886
+ updateLastHeartbeat() {
1887
+ this.lastHeartbeatResponse = Date.now();
1888
+ }
1889
+ heartbeat() {
1890
+ if (Date.now() - this.lastHeartbeatResponse > HEARTBEAT_INTERVAL * 2) {
1891
+ this.ws.disconnect();
1892
+ return;
1893
+ }
1894
+ try {
1895
+ this.ws.sendData("h");
1896
+ } catch (_a) {
1897
+ }
1898
+ }
1899
+ async makeRequest(message, options = { timeout: REQUEST_TIMEOUT }) {
1900
+ const reqId = message.id;
1901
+ this.sendData(message);
1902
+ let timeoutId;
1903
+ return Promise.race([
1904
+ new Promise((_, reject) => {
1905
+ timeoutId = window.setTimeout(() => {
1906
+ reject(new Error(`request ${reqId} timed out`));
1907
+ }, options.timeout);
1908
+ }),
1909
+ new Promise((resolve) => {
1910
+ this.requestResolutions.set(reqId, (m) => {
1911
+ clearTimeout(timeoutId);
1912
+ resolve(m);
1913
+ this.requestResolutions.delete(reqId);
1914
+ });
1915
+ })
1916
+ ]);
1917
+ }
1918
+ async handleConnected() {
1919
+ const res = await this.makeRequest({
1920
+ type: "HostSession",
1921
+ id: IntNumber(this.nextReqId++),
1922
+ sessionId: this.session.id,
1923
+ sessionKey: this.session.key
1924
+ });
1925
+ if (res.type === "Fail")
1926
+ return false;
1927
+ this.sendData({
1928
+ type: "IsLinked",
1929
+ id: IntNumber(this.nextReqId++),
1930
+ sessionId: this.session.id
1931
+ });
1932
+ this.sendData({
1933
+ type: "GetSessionConfig",
1934
+ id: IntNumber(this.nextReqId++),
1935
+ sessionId: this.session.id
1936
+ });
1937
+ return true;
1938
+ }
1939
+ }
1940
+ class RelayEventManager {
1941
+ constructor() {
1942
+ this._nextRequestId = 0;
1943
+ this.callbacks = /* @__PURE__ */ new Map();
1944
+ }
1945
+ makeRequestId() {
1946
+ this._nextRequestId = (this._nextRequestId + 1) % 2147483647;
1947
+ const id = this._nextRequestId;
1948
+ const idStr = prepend0x(id.toString(16));
1949
+ const callback = this.callbacks.get(idStr);
1950
+ if (callback) {
1951
+ this.callbacks.delete(idStr);
1952
+ }
1953
+ return id;
1954
+ }
1955
+ }
1956
+ const STORAGE_KEY_SESSION_ID = "session:id";
1957
+ const STORAGE_KEY_SESSION_SECRET = "session:secret";
1958
+ const STORAGE_KEY_SESSION_LINKED = "session:linked";
1959
+ class WalletLinkSession {
1960
+ constructor(storage2, id, secret, linked = false) {
1961
+ this.storage = storage2;
1962
+ this.id = id;
1963
+ this.secret = secret;
1964
+ this.key = bytesToHex(sha256(`${id}, ${secret} WalletLink`));
1965
+ this._linked = !!linked;
1966
+ }
1967
+ static create(storage2) {
1968
+ const id = randomBytesHex(16);
1969
+ const secret = randomBytesHex(32);
1970
+ return new WalletLinkSession(storage2, id, secret).save();
1971
+ }
1972
+ static load(storage2) {
1973
+ const id = storage2.getItem(STORAGE_KEY_SESSION_ID);
1974
+ const linked = storage2.getItem(STORAGE_KEY_SESSION_LINKED);
1975
+ const secret = storage2.getItem(STORAGE_KEY_SESSION_SECRET);
1976
+ if (id && secret) {
1977
+ return new WalletLinkSession(storage2, id, secret, linked === "1");
1978
+ }
1979
+ return null;
1980
+ }
1981
+ get linked() {
1982
+ return this._linked;
1983
+ }
1984
+ set linked(val) {
1985
+ this._linked = val;
1986
+ this.persistLinked();
1987
+ }
1988
+ save() {
1989
+ this.storage.setItem(STORAGE_KEY_SESSION_ID, this.id);
1990
+ this.storage.setItem(STORAGE_KEY_SESSION_SECRET, this.secret);
1991
+ this.persistLinked();
1992
+ return this;
1993
+ }
1994
+ persistLinked() {
1995
+ this.storage.setItem(STORAGE_KEY_SESSION_LINKED, this._linked ? "1" : "0");
1996
+ }
1997
+ }
1998
+ function isInIFrame() {
1999
+ try {
2000
+ return window.frameElement !== null;
2001
+ } catch (e) {
2002
+ return false;
2003
+ }
2004
+ }
2005
+ function getLocation() {
2006
+ try {
2007
+ if (isInIFrame() && window.top) {
2008
+ return window.top.location;
2009
+ }
2010
+ return window.location;
2011
+ } catch (e) {
2012
+ return window.location;
2013
+ }
2014
+ }
2015
+ function isMobileWeb() {
2016
+ var _a;
2017
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent);
2018
+ }
2019
+ function isDarkMode() {
2020
+ var _a, _b;
2021
+ return (_b = (_a = window === null || window === void 0 ? void 0 : window.matchMedia) === null || _a === void 0 ? void 0 : _a.call(window, "(prefers-color-scheme: dark)").matches) !== null && _b !== void 0 ? _b : false;
2022
+ }
2023
+ const css$2 = /* @__PURE__ */ (() => `@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}`)();
2024
+ function injectCssReset() {
2025
+ const styleEl = document.createElement("style");
2026
+ styleEl.type = "text/css";
2027
+ styleEl.appendChild(document.createTextNode(css$2));
2028
+ document.documentElement.appendChild(styleEl);
2029
+ }
2030
+ const css$1 = /* @__PURE__ */ (() => `.-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}`)();
2031
+ const cblogo = `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+`;
2032
+ const gearIcon = `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=`;
2033
+ class Snackbar {
2034
+ constructor() {
2035
+ this.items = /* @__PURE__ */ new Map();
2036
+ this.nextItemKey = 0;
2037
+ this.root = null;
2038
+ this.darkMode = isDarkMode();
2039
+ }
2040
+ attach(el) {
2041
+ this.root = document.createElement("div");
2042
+ this.root.className = "-cbwsdk-snackbar-root";
2043
+ el.appendChild(this.root);
2044
+ this.render();
2045
+ }
2046
+ presentItem(itemProps) {
2047
+ const key = this.nextItemKey++;
2048
+ this.items.set(key, itemProps);
2049
+ this.render();
2050
+ return () => {
2051
+ this.items.delete(key);
2052
+ this.render();
2053
+ };
2054
+ }
2055
+ clear() {
2056
+ this.items.clear();
2057
+ this.render();
2058
+ }
2059
+ render() {
2060
+ if (!this.root) {
2061
+ return;
2062
+ }
2063
+ D(g(
2064
+ "div",
2065
+ null,
2066
+ g(SnackbarContainer, { darkMode: this.darkMode }, Array.from(this.items.entries()).map(([key, itemProps]) => g(SnackbarInstance, Object.assign({}, itemProps, { key }))))
2067
+ ), this.root);
2068
+ }
2069
+ }
2070
+ const SnackbarContainer = (props) => g(
2071
+ "div",
2072
+ { class: clsx("-cbwsdk-snackbar-container") },
2073
+ g("style", null, css$1),
2074
+ g("div", { class: "-cbwsdk-snackbar" }, props.children)
2075
+ );
2076
+ const SnackbarInstance = ({ autoExpand, message, menuItems }) => {
2077
+ const [hidden, setHidden] = h(true);
2078
+ const [expanded, setExpanded] = h(autoExpand !== null && autoExpand !== void 0 ? autoExpand : false);
2079
+ y(() => {
2080
+ const timers = [
2081
+ window.setTimeout(() => {
2082
+ setHidden(false);
2083
+ }, 1),
2084
+ window.setTimeout(() => {
2085
+ setExpanded(true);
2086
+ }, 1e4)
2087
+ ];
2088
+ return () => {
2089
+ timers.forEach(window.clearTimeout);
2090
+ };
2091
+ });
2092
+ const toggleExpanded = () => {
2093
+ setExpanded(!expanded);
2094
+ };
2095
+ return g(
2096
+ "div",
2097
+ { class: clsx("-cbwsdk-snackbar-instance", hidden && "-cbwsdk-snackbar-instance-hidden", expanded && "-cbwsdk-snackbar-instance-expanded") },
2098
+ g(
2099
+ "div",
2100
+ { class: "-cbwsdk-snackbar-instance-header", onClick: toggleExpanded },
2101
+ g("img", { src: cblogo, class: "-cbwsdk-snackbar-instance-header-cblogo" }),
2102
+ " ",
2103
+ g("div", { class: "-cbwsdk-snackbar-instance-header-message" }, message),
2104
+ g(
2105
+ "div",
2106
+ { class: "-gear-container" },
2107
+ !expanded && g(
2108
+ "svg",
2109
+ { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
2110
+ g("circle", { cx: "12", cy: "12", r: "12", fill: "#F5F7F8" })
2111
+ ),
2112
+ g("img", { src: gearIcon, class: "-gear-icon", title: "Expand" })
2113
+ )
2114
+ ),
2115
+ menuItems && menuItems.length > 0 && g("div", { class: "-cbwsdk-snackbar-instance-menu" }, menuItems.map((action, i) => g(
2116
+ "div",
2117
+ { class: clsx("-cbwsdk-snackbar-instance-menu-item", action.isRed && "-cbwsdk-snackbar-instance-menu-item-is-red"), onClick: action.onClick, key: i },
2118
+ g(
2119
+ "svg",
2120
+ { width: action.svgWidth, height: action.svgHeight, viewBox: "0 0 10 11", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
2121
+ g("path", { "fill-rule": action.defaultFillRule, "clip-rule": action.defaultClipRule, d: action.path, fill: "#AAAAAA" })
2122
+ ),
2123
+ g("span", { class: clsx("-cbwsdk-snackbar-instance-menu-item-info", action.isRed && "-cbwsdk-snackbar-instance-menu-item-info-is-red") }, action.info)
2124
+ )))
2125
+ );
2126
+ };
2127
+ class WalletLinkRelayUI {
2128
+ constructor() {
2129
+ this.attached = false;
2130
+ this.snackbar = new Snackbar();
2131
+ }
2132
+ attach() {
2133
+ if (this.attached) {
2134
+ throw new Error("Coinbase Wallet SDK UI is already attached");
2135
+ }
2136
+ const el = document.documentElement;
2137
+ const container = document.createElement("div");
2138
+ container.className = "-cbwsdk-css-reset";
2139
+ el.appendChild(container);
2140
+ this.snackbar.attach(container);
2141
+ this.attached = true;
2142
+ injectCssReset();
2143
+ }
2144
+ showConnecting(options) {
2145
+ let snackbarProps;
2146
+ if (options.isUnlinkedErrorState) {
2147
+ snackbarProps = {
2148
+ autoExpand: true,
2149
+ message: "Connection lost",
2150
+ menuItems: [
2151
+ {
2152
+ isRed: false,
2153
+ info: "Reset connection",
2154
+ svgWidth: "10",
2155
+ svgHeight: "11",
2156
+ path: "M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",
2157
+ defaultFillRule: "evenodd",
2158
+ defaultClipRule: "evenodd",
2159
+ onClick: options.onResetConnection
2160
+ }
2161
+ ]
2162
+ };
2163
+ } else {
2164
+ snackbarProps = {
2165
+ message: "Confirm on phone",
2166
+ menuItems: [
2167
+ {
2168
+ isRed: true,
2169
+ info: "Cancel transaction",
2170
+ svgWidth: "11",
2171
+ svgHeight: "11",
2172
+ path: "M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",
2173
+ defaultFillRule: "inherit",
2174
+ defaultClipRule: "inherit",
2175
+ onClick: options.onCancel
2176
+ },
2177
+ {
2178
+ isRed: false,
2179
+ info: "Reset connection",
2180
+ svgWidth: "10",
2181
+ svgHeight: "11",
2182
+ path: "M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",
2183
+ defaultFillRule: "evenodd",
2184
+ defaultClipRule: "evenodd",
2185
+ onClick: options.onResetConnection
2186
+ }
2187
+ ]
2188
+ };
2189
+ }
2190
+ return this.snackbar.presentItem(snackbarProps);
2191
+ }
2192
+ }
2193
+ const css = /* @__PURE__ */ (() => `.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}`)();
2194
+ class RedirectDialog {
2195
+ constructor() {
2196
+ this.root = null;
2197
+ this.darkMode = isDarkMode();
2198
+ }
2199
+ attach() {
2200
+ const el = document.documentElement;
2201
+ this.root = document.createElement("div");
2202
+ this.root.className = "-cbwsdk-css-reset";
2203
+ el.appendChild(this.root);
2204
+ injectCssReset();
2205
+ }
2206
+ present(props) {
2207
+ this.render(props);
2208
+ }
2209
+ clear() {
2210
+ this.render(null);
2211
+ }
2212
+ render(props) {
2213
+ if (!this.root)
2214
+ return;
2215
+ D(null, this.root);
2216
+ if (!props)
2217
+ return;
2218
+ D(g(RedirectDialogContent, Object.assign({}, props, { onDismiss: () => {
2219
+ this.clear();
2220
+ }, darkMode: this.darkMode })), this.root);
2221
+ }
2222
+ }
2223
+ const RedirectDialogContent = ({ title, buttonText, darkMode, onButtonClick, onDismiss }) => {
2224
+ const theme = darkMode ? "dark" : "light";
2225
+ return g(
2226
+ SnackbarContainer,
2227
+ { darkMode },
2228
+ g(
2229
+ "div",
2230
+ { class: "-cbwsdk-redirect-dialog" },
2231
+ g("style", null, css),
2232
+ g("div", { class: "-cbwsdk-redirect-dialog-backdrop", onClick: onDismiss }),
2233
+ g(
2234
+ "div",
2235
+ { class: clsx("-cbwsdk-redirect-dialog-box", theme) },
2236
+ g("p", null, title),
2237
+ g("button", { onClick: onButtonClick }, buttonText)
2238
+ )
2239
+ )
2240
+ );
2241
+ };
2242
+ const CB_KEYS_URL = "https://keys.coinbase.com/connect";
2243
+ const CB_WALLET_RPC_URL = "http://rpc.wallet.coinbase.com";
2244
+ const WALLETLINK_URL = "https://www.walletlink.org";
2245
+ const CBW_MOBILE_DEEPLINK_URL = "https://go.cb-w.com/walletlink";
2246
+ class WLMobileRelayUI {
2247
+ constructor() {
2248
+ this.attached = false;
2249
+ this.redirectDialog = new RedirectDialog();
2250
+ }
2251
+ attach() {
2252
+ if (this.attached) {
2253
+ throw new Error("Coinbase Wallet SDK UI is already attached");
2254
+ }
2255
+ this.redirectDialog.attach();
2256
+ this.attached = true;
2257
+ }
2258
+ redirectToCoinbaseWallet(walletLinkUrl) {
2259
+ const url = new URL(CBW_MOBILE_DEEPLINK_URL);
2260
+ url.searchParams.append("redirect_url", getLocation().href);
2261
+ if (walletLinkUrl) {
2262
+ url.searchParams.append("wl_url", walletLinkUrl);
2263
+ }
2264
+ const anchorTag = document.createElement("a");
2265
+ anchorTag.target = "cbw-opener";
2266
+ anchorTag.href = url.href;
2267
+ anchorTag.rel = "noreferrer noopener";
2268
+ anchorTag.click();
2269
+ }
2270
+ openCoinbaseWalletDeeplink(walletLinkUrl) {
2271
+ this.redirectDialog.present({
2272
+ title: "Redirecting to Coinbase Wallet...",
2273
+ buttonText: "Open",
2274
+ onButtonClick: () => {
2275
+ this.redirectToCoinbaseWallet(walletLinkUrl);
2276
+ }
2277
+ });
2278
+ setTimeout(() => {
2279
+ this.redirectToCoinbaseWallet(walletLinkUrl);
2280
+ }, 99);
2281
+ }
2282
+ showConnecting(_options) {
2283
+ return () => {
2284
+ this.redirectDialog.clear();
2285
+ };
2286
+ }
2287
+ }
2288
+ class WalletLinkRelay {
2289
+ constructor(options) {
2290
+ this.chainCallbackParams = { chainId: "", jsonRpcUrl: "" };
2291
+ this.isMobileWeb = isMobileWeb();
2292
+ this.linkedUpdated = (linked) => {
2293
+ this.isLinked = linked;
2294
+ const cachedAddresses = this.storage.getItem(LOCAL_STORAGE_ADDRESSES_KEY);
2295
+ if (linked) {
2296
+ this._session.linked = linked;
2297
+ }
2298
+ this.isUnlinkedErrorState = false;
2299
+ if (cachedAddresses) {
2300
+ const addresses = cachedAddresses.split(" ");
2301
+ const wasConnectedViaStandalone = this.storage.getItem("IsStandaloneSigning") === "true";
2302
+ if (addresses[0] !== "" && !linked && this._session.linked && !wasConnectedViaStandalone) {
2303
+ this.isUnlinkedErrorState = true;
2304
+ }
2305
+ }
2306
+ };
2307
+ this.metadataUpdated = (key, value) => {
2308
+ this.storage.setItem(key, value);
2309
+ };
2310
+ this.chainUpdated = (chainId, jsonRpcUrl) => {
2311
+ if (this.chainCallbackParams.chainId === chainId && this.chainCallbackParams.jsonRpcUrl === jsonRpcUrl) {
2312
+ return;
2313
+ }
2314
+ this.chainCallbackParams = {
2315
+ chainId,
2316
+ jsonRpcUrl
2317
+ };
2318
+ if (this.chainCallback) {
2319
+ this.chainCallback(jsonRpcUrl, Number.parseInt(chainId, 10));
2320
+ }
2321
+ };
2322
+ this.accountUpdated = (selectedAddress) => {
2323
+ if (this.accountsCallback) {
2324
+ this.accountsCallback([selectedAddress]);
2325
+ }
2326
+ if (WalletLinkRelay.accountRequestCallbackIds.size > 0) {
2327
+ Array.from(WalletLinkRelay.accountRequestCallbackIds.values()).forEach((id) => {
2328
+ this.invokeCallback(id, {
2329
+ method: "requestEthereumAccounts",
2330
+ result: [selectedAddress]
2331
+ });
2332
+ });
2333
+ WalletLinkRelay.accountRequestCallbackIds.clear();
2334
+ }
2335
+ };
2336
+ this.resetAndReload = this.resetAndReload.bind(this);
2337
+ this.linkAPIUrl = options.linkAPIUrl;
2338
+ this.storage = options.storage;
2339
+ this.metadata = options.metadata;
2340
+ this.accountsCallback = options.accountsCallback;
2341
+ this.chainCallback = options.chainCallback;
2342
+ const { session, ui, connection } = this.subscribe();
2343
+ this._session = session;
2344
+ this.connection = connection;
2345
+ this.relayEventManager = new RelayEventManager();
2346
+ this.ui = ui;
2347
+ this.ui.attach();
2348
+ }
2349
+ subscribe() {
2350
+ const session = WalletLinkSession.load(this.storage) || WalletLinkSession.create(this.storage);
2351
+ const { linkAPIUrl } = this;
2352
+ const connection = new WalletLinkConnection({
2353
+ session,
2354
+ linkAPIUrl,
2355
+ listener: this
2356
+ });
2357
+ const ui = this.isMobileWeb ? new WLMobileRelayUI() : new WalletLinkRelayUI();
2358
+ connection.connect();
2359
+ return { session, ui, connection };
2360
+ }
2361
+ resetAndReload() {
2362
+ this.connection.destroy().then(() => {
2363
+ const storedSession = WalletLinkSession.load(this.storage);
2364
+ if ((storedSession === null || storedSession === void 0 ? void 0 : storedSession.id) === this._session.id) {
2365
+ ScopedLocalStorage.clearAll();
2366
+ }
2367
+ document.location.reload();
2368
+ }).catch((_) => {
2369
+ });
2370
+ }
2371
+ signEthereumTransaction(params) {
2372
+ return this.sendRequest({
2373
+ method: "signEthereumTransaction",
2374
+ params: {
2375
+ fromAddress: params.fromAddress,
2376
+ toAddress: params.toAddress,
2377
+ weiValue: bigIntStringFromBigInt(params.weiValue),
2378
+ data: hexStringFromBuffer(params.data, true),
2379
+ nonce: params.nonce,
2380
+ gasPriceInWei: params.gasPriceInWei ? bigIntStringFromBigInt(params.gasPriceInWei) : null,
2381
+ maxFeePerGas: params.gasPriceInWei ? bigIntStringFromBigInt(params.gasPriceInWei) : null,
2382
+ maxPriorityFeePerGas: params.gasPriceInWei ? bigIntStringFromBigInt(params.gasPriceInWei) : null,
2383
+ gasLimit: params.gasLimit ? bigIntStringFromBigInt(params.gasLimit) : null,
2384
+ chainId: params.chainId,
2385
+ shouldSubmit: false
2386
+ }
2387
+ });
2388
+ }
2389
+ signAndSubmitEthereumTransaction(params) {
2390
+ return this.sendRequest({
2391
+ method: "signEthereumTransaction",
2392
+ params: {
2393
+ fromAddress: params.fromAddress,
2394
+ toAddress: params.toAddress,
2395
+ weiValue: bigIntStringFromBigInt(params.weiValue),
2396
+ data: hexStringFromBuffer(params.data, true),
2397
+ nonce: params.nonce,
2398
+ gasPriceInWei: params.gasPriceInWei ? bigIntStringFromBigInt(params.gasPriceInWei) : null,
2399
+ maxFeePerGas: params.maxFeePerGas ? bigIntStringFromBigInt(params.maxFeePerGas) : null,
2400
+ maxPriorityFeePerGas: params.maxPriorityFeePerGas ? bigIntStringFromBigInt(params.maxPriorityFeePerGas) : null,
2401
+ gasLimit: params.gasLimit ? bigIntStringFromBigInt(params.gasLimit) : null,
2402
+ chainId: params.chainId,
2403
+ shouldSubmit: true
2404
+ }
2405
+ });
2406
+ }
2407
+ submitEthereumTransaction(signedTransaction, chainId) {
2408
+ return this.sendRequest({
2409
+ method: "submitEthereumTransaction",
2410
+ params: {
2411
+ signedTransaction: hexStringFromBuffer(signedTransaction, true),
2412
+ chainId
2413
+ }
2414
+ });
2415
+ }
2416
+ getWalletLinkSession() {
2417
+ return this._session;
2418
+ }
2419
+ sendRequest(request) {
2420
+ let hideSnackbarItem = null;
2421
+ const id = randomBytesHex(8);
2422
+ const cancel = (error) => {
2423
+ this.publishWeb3RequestCanceledEvent(id);
2424
+ this.handleErrorResponse(id, request.method, error);
2425
+ hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
2426
+ };
2427
+ return new Promise((resolve, reject) => {
2428
+ {
2429
+ hideSnackbarItem = this.ui.showConnecting({
2430
+ isUnlinkedErrorState: this.isUnlinkedErrorState,
2431
+ onCancel: cancel,
2432
+ onResetConnection: this.resetAndReload
2433
+ // eslint-disable-line @typescript-eslint/unbound-method
2434
+ });
2435
+ }
2436
+ this.relayEventManager.callbacks.set(id, (response) => {
2437
+ hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
2438
+ if (isErrorResponse(response)) {
2439
+ return reject(new Error(response.errorMessage));
2440
+ }
2441
+ resolve(response);
2442
+ });
2443
+ this.publishWeb3RequestEvent(id, request);
2444
+ });
2445
+ }
2446
+ publishWeb3RequestEvent(id, request) {
2447
+ const message = { type: "WEB3_REQUEST", id, request };
2448
+ this.publishEvent("Web3Request", message, true).then((_) => {
2449
+ }).catch((err) => {
2450
+ this.handleWeb3ResponseMessage(message.id, {
2451
+ method: request.method,
2452
+ errorMessage: err.message
2453
+ });
2454
+ });
2455
+ if (this.isMobileWeb) {
2456
+ this.openCoinbaseWalletDeeplink(request.method);
2457
+ }
2458
+ }
2459
+ // copied from MobileRelay
2460
+ openCoinbaseWalletDeeplink(method) {
2461
+ if (!(this.ui instanceof WLMobileRelayUI))
2462
+ return;
2463
+ switch (method) {
2464
+ case "requestEthereumAccounts":
2465
+ case "switchEthereumChain":
2466
+ return;
2467
+ default:
2468
+ window.addEventListener("blur", () => {
2469
+ window.addEventListener("focus", () => {
2470
+ this.connection.checkUnseenEvents();
2471
+ }, { once: true });
2472
+ }, { once: true });
2473
+ this.ui.openCoinbaseWalletDeeplink();
2474
+ break;
2475
+ }
2476
+ }
2477
+ publishWeb3RequestCanceledEvent(id) {
2478
+ const message = {
2479
+ type: "WEB3_REQUEST_CANCELED",
2480
+ id
2481
+ };
2482
+ this.publishEvent("Web3RequestCanceled", message, false).then();
2483
+ }
2484
+ publishEvent(event, message, callWebhook) {
2485
+ return this.connection.publishEvent(event, message, callWebhook);
2486
+ }
2487
+ handleWeb3ResponseMessage(id, response) {
2488
+ if (response.method === "requestEthereumAccounts") {
2489
+ WalletLinkRelay.accountRequestCallbackIds.forEach((id2) => this.invokeCallback(id2, response));
2490
+ WalletLinkRelay.accountRequestCallbackIds.clear();
2491
+ return;
2492
+ }
2493
+ this.invokeCallback(id, response);
2494
+ }
2495
+ handleErrorResponse(id, method, error) {
2496
+ var _a;
2497
+ const errorMessage = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : "Unspecified error message.";
2498
+ this.handleWeb3ResponseMessage(id, {
2499
+ method,
2500
+ errorMessage
2501
+ });
2502
+ }
2503
+ invokeCallback(id, response) {
2504
+ const callback = this.relayEventManager.callbacks.get(id);
2505
+ if (callback) {
2506
+ callback(response);
2507
+ this.relayEventManager.callbacks.delete(id);
2508
+ }
2509
+ }
2510
+ requestEthereumAccounts() {
2511
+ const { appName, appLogoUrl } = this.metadata;
2512
+ const request = {
2513
+ method: "requestEthereumAccounts",
2514
+ params: {
2515
+ appName,
2516
+ appLogoUrl
2517
+ }
2518
+ };
2519
+ const id = randomBytesHex(8);
2520
+ return new Promise((resolve, reject) => {
2521
+ this.relayEventManager.callbacks.set(id, (response) => {
2522
+ if (isErrorResponse(response)) {
2523
+ return reject(new Error(response.errorMessage));
2524
+ }
2525
+ resolve(response);
2526
+ });
2527
+ WalletLinkRelay.accountRequestCallbackIds.add(id);
2528
+ this.publishWeb3RequestEvent(id, request);
2529
+ });
2530
+ }
2531
+ watchAsset(type, address, symbol, decimals, image, chainId) {
2532
+ const request = {
2533
+ method: "watchAsset",
2534
+ params: {
2535
+ type,
2536
+ options: {
2537
+ address,
2538
+ symbol,
2539
+ decimals,
2540
+ image
2541
+ },
2542
+ chainId
2543
+ }
2544
+ };
2545
+ let hideSnackbarItem = null;
2546
+ const id = randomBytesHex(8);
2547
+ const cancel = (error) => {
2548
+ this.publishWeb3RequestCanceledEvent(id);
2549
+ this.handleErrorResponse(id, request.method, error);
2550
+ hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
2551
+ };
2552
+ {
2553
+ hideSnackbarItem = this.ui.showConnecting({
2554
+ isUnlinkedErrorState: this.isUnlinkedErrorState,
2555
+ onCancel: cancel,
2556
+ onResetConnection: this.resetAndReload
2557
+ // eslint-disable-line @typescript-eslint/unbound-method
2558
+ });
2559
+ }
2560
+ return new Promise((resolve, reject) => {
2561
+ this.relayEventManager.callbacks.set(id, (response) => {
2562
+ hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
2563
+ if (isErrorResponse(response)) {
2564
+ return reject(new Error(response.errorMessage));
2565
+ }
2566
+ resolve(response);
2567
+ });
2568
+ this.publishWeb3RequestEvent(id, request);
2569
+ });
2570
+ }
2571
+ addEthereumChain(chainId, rpcUrls, iconUrls, blockExplorerUrls, chainName, nativeCurrency) {
2572
+ const request = {
2573
+ method: "addEthereumChain",
2574
+ params: {
2575
+ chainId,
2576
+ rpcUrls,
2577
+ blockExplorerUrls,
2578
+ chainName,
2579
+ iconUrls,
2580
+ nativeCurrency
2581
+ }
2582
+ };
2583
+ let hideSnackbarItem = null;
2584
+ const id = randomBytesHex(8);
2585
+ const cancel = (error) => {
2586
+ this.publishWeb3RequestCanceledEvent(id);
2587
+ this.handleErrorResponse(id, request.method, error);
2588
+ hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
2589
+ };
2590
+ {
2591
+ hideSnackbarItem = this.ui.showConnecting({
2592
+ isUnlinkedErrorState: this.isUnlinkedErrorState,
2593
+ onCancel: cancel,
2594
+ onResetConnection: this.resetAndReload
2595
+ // eslint-disable-line @typescript-eslint/unbound-method
2596
+ });
2597
+ }
2598
+ return new Promise((resolve, reject) => {
2599
+ this.relayEventManager.callbacks.set(id, (response) => {
2600
+ hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
2601
+ if (isErrorResponse(response)) {
2602
+ return reject(new Error(response.errorMessage));
2603
+ }
2604
+ resolve(response);
2605
+ });
2606
+ this.publishWeb3RequestEvent(id, request);
2607
+ });
2608
+ }
2609
+ switchEthereumChain(chainId, address) {
2610
+ const request = {
2611
+ method: "switchEthereumChain",
2612
+ params: Object.assign({ chainId }, { address })
2613
+ };
2614
+ let hideSnackbarItem = null;
2615
+ const id = randomBytesHex(8);
2616
+ const cancel = (error) => {
2617
+ this.publishWeb3RequestCanceledEvent(id);
2618
+ this.handleErrorResponse(id, request.method, error);
2619
+ hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
2620
+ };
2621
+ {
2622
+ hideSnackbarItem = this.ui.showConnecting({
2623
+ isUnlinkedErrorState: this.isUnlinkedErrorState,
2624
+ onCancel: cancel,
2625
+ onResetConnection: this.resetAndReload
2626
+ // eslint-disable-line @typescript-eslint/unbound-method
2627
+ });
2628
+ }
2629
+ return new Promise((resolve, reject) => {
2630
+ this.relayEventManager.callbacks.set(id, (response) => {
2631
+ hideSnackbarItem === null || hideSnackbarItem === void 0 ? void 0 : hideSnackbarItem();
2632
+ if (isErrorResponse(response) && response.errorCode) {
2633
+ return reject(standardErrors.provider.custom({
2634
+ code: response.errorCode,
2635
+ message: `Unrecognized chain ID. Try adding the chain using addEthereumChain first.`
2636
+ }));
2637
+ } else if (isErrorResponse(response)) {
2638
+ return reject(new Error(response.errorMessage));
2639
+ }
2640
+ resolve(response);
2641
+ });
2642
+ this.publishWeb3RequestEvent(id, request);
2643
+ });
2644
+ }
2645
+ }
2646
+ WalletLinkRelay.accountRequestCallbackIds = /* @__PURE__ */ new Set();
2647
+ const DEFAULT_CHAIN_ID_KEY = "DefaultChainId";
2648
+ const DEFAULT_JSON_RPC_URL = "DefaultJsonRpcUrl";
2649
+ class WalletLinkSigner {
2650
+ constructor(options) {
2651
+ this._relay = null;
2652
+ this._addresses = [];
2653
+ this.metadata = options.metadata;
2654
+ this._storage = new ScopedLocalStorage("walletlink", WALLETLINK_URL);
2655
+ this.callback = options.callback || null;
2656
+ const cachedAddresses = this._storage.getItem(LOCAL_STORAGE_ADDRESSES_KEY);
2657
+ if (cachedAddresses) {
2658
+ const addresses = cachedAddresses.split(" ");
2659
+ if (addresses[0] !== "") {
2660
+ this._addresses = addresses.map((address) => ensureAddressString(address));
2661
+ }
2662
+ }
2663
+ this.initializeRelay();
2664
+ }
2665
+ getSession() {
2666
+ const relay = this.initializeRelay();
2667
+ const { id, secret } = relay.getWalletLinkSession();
2668
+ return { id, secret };
2669
+ }
2670
+ async handshake() {
2671
+ await this._eth_requestAccounts();
2672
+ }
2673
+ get selectedAddress() {
2674
+ return this._addresses[0] || void 0;
2675
+ }
2676
+ get jsonRpcUrl() {
2677
+ var _a;
2678
+ return (_a = this._storage.getItem(DEFAULT_JSON_RPC_URL)) !== null && _a !== void 0 ? _a : void 0;
2679
+ }
2680
+ set jsonRpcUrl(value) {
2681
+ this._storage.setItem(DEFAULT_JSON_RPC_URL, value);
2682
+ }
2683
+ updateProviderInfo(jsonRpcUrl, chainId) {
2684
+ var _a;
2685
+ this.jsonRpcUrl = jsonRpcUrl;
2686
+ const originalChainId = this.getChainId();
2687
+ this._storage.setItem(DEFAULT_CHAIN_ID_KEY, chainId.toString(10));
2688
+ const chainChanged = ensureIntNumber(chainId) !== originalChainId;
2689
+ if (chainChanged) {
2690
+ (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, "chainChanged", hexStringFromNumber(chainId));
2691
+ }
2692
+ }
2693
+ async watchAsset(params) {
2694
+ const request = Array.isArray(params) ? params[0] : params;
2695
+ if (!request.type) {
2696
+ throw standardErrors.rpc.invalidParams("Type is required");
2697
+ }
2698
+ if ((request === null || request === void 0 ? void 0 : request.type) !== "ERC20") {
2699
+ throw standardErrors.rpc.invalidParams(`Asset of type '${request.type}' is not supported`);
2700
+ }
2701
+ if (!(request === null || request === void 0 ? void 0 : request.options)) {
2702
+ throw standardErrors.rpc.invalidParams("Options are required");
2703
+ }
2704
+ if (!(request === null || request === void 0 ? void 0 : request.options.address)) {
2705
+ throw standardErrors.rpc.invalidParams("Address is required");
2706
+ }
2707
+ const chainId = this.getChainId();
2708
+ const { address, symbol, image, decimals } = request.options;
2709
+ const relay = this.initializeRelay();
2710
+ const result = await relay.watchAsset(request.type, address, symbol, decimals, image, chainId === null || chainId === void 0 ? void 0 : chainId.toString());
2711
+ if (isErrorResponse(result))
2712
+ return false;
2713
+ return !!result.result;
2714
+ }
2715
+ async addEthereumChain(params) {
2716
+ var _a, _b;
2717
+ const request = params[0];
2718
+ if (((_a = request.rpcUrls) === null || _a === void 0 ? void 0 : _a.length) === 0) {
2719
+ throw standardErrors.rpc.invalidParams("please pass in at least 1 rpcUrl");
2720
+ }
2721
+ if (!request.chainName || request.chainName.trim() === "") {
2722
+ throw standardErrors.rpc.invalidParams("chainName is a required field");
2723
+ }
2724
+ if (!request.nativeCurrency) {
2725
+ throw standardErrors.rpc.invalidParams("nativeCurrency is a required field");
2726
+ }
2727
+ const chainIdNumber = Number.parseInt(request.chainId, 16);
2728
+ if (chainIdNumber === this.getChainId()) {
2729
+ return false;
2730
+ }
2731
+ const relay = this.initializeRelay();
2732
+ const { rpcUrls = [], blockExplorerUrls = [], chainName, iconUrls = [], nativeCurrency } = request;
2733
+ const res = await relay.addEthereumChain(chainIdNumber.toString(), rpcUrls, iconUrls, blockExplorerUrls, chainName, nativeCurrency);
2734
+ if (isErrorResponse(res))
2735
+ return false;
2736
+ if (((_b = res.result) === null || _b === void 0 ? void 0 : _b.isApproved) === true) {
2737
+ this.updateProviderInfo(rpcUrls[0], chainIdNumber);
2738
+ return null;
2739
+ }
2740
+ throw standardErrors.rpc.internal("unable to add ethereum chain");
2741
+ }
2742
+ async switchEthereumChain(params) {
2743
+ const request = params[0];
2744
+ const chainId = Number.parseInt(request.chainId, 16);
2745
+ const relay = this.initializeRelay();
2746
+ const res = await relay.switchEthereumChain(chainId.toString(10), this.selectedAddress || void 0);
2747
+ if (isErrorResponse(res))
2748
+ throw res;
2749
+ const switchResponse = res.result;
2750
+ if (switchResponse.isApproved && switchResponse.rpcUrl.length > 0) {
2751
+ this.updateProviderInfo(switchResponse.rpcUrl, chainId);
2752
+ }
2753
+ return null;
2754
+ }
2755
+ async cleanup() {
2756
+ this.callback = null;
2757
+ if (this._relay) {
2758
+ this._relay.resetAndReload();
2759
+ }
2760
+ this._storage.clear();
2761
+ }
2762
+ _setAddresses(addresses, _) {
2763
+ var _a;
2764
+ if (!Array.isArray(addresses)) {
2765
+ throw new Error("addresses is not an array");
2766
+ }
2767
+ const newAddresses = addresses.map((address) => ensureAddressString(address));
2768
+ if (JSON.stringify(newAddresses) === JSON.stringify(this._addresses)) {
2769
+ return;
2770
+ }
2771
+ this._addresses = newAddresses;
2772
+ (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, "accountsChanged", newAddresses);
2773
+ this._storage.setItem(LOCAL_STORAGE_ADDRESSES_KEY, newAddresses.join(" "));
2774
+ }
2775
+ async request(request) {
2776
+ const params = request.params || [];
2777
+ switch (request.method) {
2778
+ case "eth_accounts":
2779
+ return [...this._addresses];
2780
+ case "eth_coinbase":
2781
+ return this.selectedAddress || null;
2782
+ case "net_version":
2783
+ return this.getChainId().toString(10);
2784
+ case "eth_chainId":
2785
+ return hexStringFromNumber(this.getChainId());
2786
+ case "eth_requestAccounts":
2787
+ return this._eth_requestAccounts();
2788
+ case "eth_ecRecover":
2789
+ case "personal_ecRecover":
2790
+ return this.ecRecover(request);
2791
+ case "personal_sign":
2792
+ return this.personalSign(request);
2793
+ case "eth_signTransaction":
2794
+ return this._eth_signTransaction(params);
2795
+ case "eth_sendRawTransaction":
2796
+ return this._eth_sendRawTransaction(params);
2797
+ case "eth_sendTransaction":
2798
+ return this._eth_sendTransaction(params);
2799
+ case "eth_signTypedData_v1":
2800
+ case "eth_signTypedData_v3":
2801
+ case "eth_signTypedData_v4":
2802
+ case "eth_signTypedData":
2803
+ return this.signTypedData(request);
2804
+ case "wallet_addEthereumChain":
2805
+ return this.addEthereumChain(params);
2806
+ case "wallet_switchEthereumChain":
2807
+ return this.switchEthereumChain(params);
2808
+ case "wallet_watchAsset":
2809
+ return this.watchAsset(params);
2810
+ default:
2811
+ if (!this.jsonRpcUrl)
2812
+ throw standardErrors.rpc.internal("No RPC URL set for chain");
2813
+ return fetchRPCRequest(request, this.jsonRpcUrl);
2814
+ }
2815
+ }
2816
+ _ensureKnownAddress(addressString) {
2817
+ const addressStr = ensureAddressString(addressString);
2818
+ const lowercaseAddresses = this._addresses.map((address) => ensureAddressString(address));
2819
+ if (!lowercaseAddresses.includes(addressStr)) {
2820
+ throw new Error("Unknown Ethereum address");
2821
+ }
2822
+ }
2823
+ _prepareTransactionParams(tx) {
2824
+ const fromAddress = tx.from ? ensureAddressString(tx.from) : this.selectedAddress;
2825
+ if (!fromAddress) {
2826
+ throw new Error("Ethereum address is unavailable");
2827
+ }
2828
+ this._ensureKnownAddress(fromAddress);
2829
+ const toAddress = tx.to ? ensureAddressString(tx.to) : null;
2830
+ const weiValue = tx.value != null ? ensureBigInt(tx.value) : BigInt(0);
2831
+ const data = tx.data ? ensureBuffer(tx.data) : Buffer.alloc(0);
2832
+ const nonce = tx.nonce != null ? ensureIntNumber(tx.nonce) : null;
2833
+ const gasPriceInWei = tx.gasPrice != null ? ensureBigInt(tx.gasPrice) : null;
2834
+ const maxFeePerGas = tx.maxFeePerGas != null ? ensureBigInt(tx.maxFeePerGas) : null;
2835
+ const maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? ensureBigInt(tx.maxPriorityFeePerGas) : null;
2836
+ const gasLimit = tx.gas != null ? ensureBigInt(tx.gas) : null;
2837
+ const chainId = tx.chainId ? ensureIntNumber(tx.chainId) : this.getChainId();
2838
+ return {
2839
+ fromAddress,
2840
+ toAddress,
2841
+ weiValue,
2842
+ data,
2843
+ nonce,
2844
+ gasPriceInWei,
2845
+ maxFeePerGas,
2846
+ maxPriorityFeePerGas,
2847
+ gasLimit,
2848
+ chainId
2849
+ };
2850
+ }
2851
+ async ecRecover(request) {
2852
+ const { method, params } = request;
2853
+ if (!Array.isArray(params))
2854
+ throw standardErrors.rpc.invalidParams();
2855
+ const relay = this.initializeRelay();
2856
+ const res = await relay.sendRequest({
2857
+ method: "ethereumAddressFromSignedMessage",
2858
+ params: {
2859
+ message: encodeToHexString(params[0]),
2860
+ signature: encodeToHexString(params[1]),
2861
+ addPrefix: method === "personal_ecRecover"
2862
+ }
2863
+ });
2864
+ if (isErrorResponse(res))
2865
+ throw res;
2866
+ return res.result;
2867
+ }
2868
+ getChainId() {
2869
+ var _a;
2870
+ return Number.parseInt((_a = this._storage.getItem(DEFAULT_CHAIN_ID_KEY)) !== null && _a !== void 0 ? _a : "1", 10);
2871
+ }
2872
+ async _eth_requestAccounts() {
2873
+ var _a, _b;
2874
+ if (this._addresses.length > 0) {
2875
+ (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, "connect", { chainId: hexStringFromNumber(this.getChainId()) });
2876
+ return this._addresses;
2877
+ }
2878
+ const relay = this.initializeRelay();
2879
+ const res = await relay.requestEthereumAccounts();
2880
+ if (isErrorResponse(res))
2881
+ throw res;
2882
+ if (!res.result) {
2883
+ throw new Error("accounts received is empty");
2884
+ }
2885
+ this._setAddresses(res.result);
2886
+ (_b = this.callback) === null || _b === void 0 ? void 0 : _b.call(this, "connect", { chainId: hexStringFromNumber(this.getChainId()) });
2887
+ return this._addresses;
2888
+ }
2889
+ async personalSign({ params }) {
2890
+ if (!Array.isArray(params))
2891
+ throw standardErrors.rpc.invalidParams();
2892
+ const address = params[1];
2893
+ const rawData = params[0];
2894
+ this._ensureKnownAddress(address);
2895
+ const relay = this.initializeRelay();
2896
+ const res = await relay.sendRequest({
2897
+ method: "signEthereumMessage",
2898
+ params: {
2899
+ address: ensureAddressString(address),
2900
+ message: encodeToHexString(rawData),
2901
+ addPrefix: true,
2902
+ typedDataJson: null
2903
+ }
2904
+ });
2905
+ if (isErrorResponse(res))
2906
+ throw res;
2907
+ return res.result;
2908
+ }
2909
+ async _eth_signTransaction(params) {
2910
+ const tx = this._prepareTransactionParams(params[0] || {});
2911
+ const relay = this.initializeRelay();
2912
+ const res = await relay.signEthereumTransaction(tx);
2913
+ if (isErrorResponse(res))
2914
+ throw res;
2915
+ return res.result;
2916
+ }
2917
+ async _eth_sendRawTransaction(params) {
2918
+ const signedTransaction = ensureBuffer(params[0]);
2919
+ const relay = this.initializeRelay();
2920
+ const res = await relay.submitEthereumTransaction(signedTransaction, this.getChainId());
2921
+ if (isErrorResponse(res))
2922
+ throw res;
2923
+ return res.result;
2924
+ }
2925
+ async _eth_sendTransaction(params) {
2926
+ const tx = this._prepareTransactionParams(params[0] || {});
2927
+ const relay = this.initializeRelay();
2928
+ const res = await relay.signAndSubmitEthereumTransaction(tx);
2929
+ if (isErrorResponse(res))
2930
+ throw res;
2931
+ return res.result;
2932
+ }
2933
+ async signTypedData(request) {
2934
+ const { method, params } = request;
2935
+ if (!Array.isArray(params))
2936
+ throw standardErrors.rpc.invalidParams();
2937
+ const encode = (input) => {
2938
+ const hashFuncMap = {
2939
+ eth_signTypedData_v1: eip712.hashForSignTypedDataLegacy,
2940
+ eth_signTypedData_v3: eip712.hashForSignTypedData_v3,
2941
+ eth_signTypedData_v4: eip712.hashForSignTypedData_v4,
2942
+ eth_signTypedData: eip712.hashForSignTypedData_v4
2943
+ };
2944
+ return hexStringFromBuffer(hashFuncMap[method]({
2945
+ data: ensureParsedJSONObject(input)
2946
+ }), true);
2947
+ };
2948
+ const address = params[method === "eth_signTypedData_v1" ? 1 : 0];
2949
+ const rawData = params[method === "eth_signTypedData_v1" ? 0 : 1];
2950
+ this._ensureKnownAddress(address);
2951
+ const relay = this.initializeRelay();
2952
+ const res = await relay.sendRequest({
2953
+ method: "signEthereumMessage",
2954
+ params: {
2955
+ address: ensureAddressString(address),
2956
+ message: encode(rawData),
2957
+ typedDataJson: JSON.stringify(rawData, null, 2),
2958
+ addPrefix: false
2959
+ }
2960
+ });
2961
+ if (isErrorResponse(res))
2962
+ throw res;
2963
+ return res.result;
2964
+ }
2965
+ initializeRelay() {
2966
+ if (!this._relay) {
2967
+ this._relay = new WalletLinkRelay({
2968
+ linkAPIUrl: WALLETLINK_URL,
2969
+ storage: this._storage,
2970
+ metadata: this.metadata,
2971
+ accountsCallback: this._setAddresses.bind(this),
2972
+ chainCallback: this.updateProviderInfo.bind(this)
2973
+ });
2974
+ }
2975
+ return this._relay;
2976
+ }
2977
+ }
2978
+ const SIGNER_TYPE_KEY = "SignerType";
2979
+ const storage = new ScopedLocalStorage("CBWSDK", "SignerConfigurator");
2980
+ function loadSignerType() {
2981
+ return storage.getItem(SIGNER_TYPE_KEY);
2982
+ }
2983
+ function storeSignerType(signerType) {
2984
+ storage.setItem(SIGNER_TYPE_KEY, signerType);
2985
+ }
2986
+ async function fetchSignerType(params) {
2987
+ const { communicator, metadata, handshakeRequest, callback } = params;
2988
+ listenForWalletLinkSessionRequest(communicator, metadata, callback).catch(() => {
2989
+ });
2990
+ const request = {
2991
+ id: crypto.randomUUID(),
2992
+ event: "selectSignerType",
2993
+ data: Object.assign(Object.assign({}, params.preference), { handshakeRequest })
2994
+ };
2995
+ const { data } = await communicator.postRequestAndWaitForResponse(request);
2996
+ return data;
2997
+ }
2998
+ function createSigner(params) {
2999
+ const { signerType, metadata, communicator, callback } = params;
3000
+ switch (signerType) {
3001
+ case "scw": {
3002
+ return new SCWSigner({
3003
+ metadata,
3004
+ callback,
3005
+ communicator
3006
+ });
3007
+ }
3008
+ case "walletlink": {
3009
+ return new WalletLinkSigner({
3010
+ metadata,
3011
+ callback
3012
+ });
3013
+ }
3014
+ }
3015
+ }
3016
+ async function listenForWalletLinkSessionRequest(communicator, metadata, callback) {
3017
+ await communicator.onMessage(({ event }) => event === "WalletLinkSessionRequest");
3018
+ const walletlink = new WalletLinkSigner({
3019
+ metadata,
3020
+ callback
3021
+ });
3022
+ communicator.postMessage({
3023
+ event: "WalletLinkUpdate",
3024
+ data: { session: walletlink.getSession() }
3025
+ });
3026
+ await walletlink.handshake();
3027
+ communicator.postMessage({
3028
+ event: "WalletLinkUpdate",
3029
+ data: { connected: true }
3030
+ });
3031
+ }
3032
+ const COOP_ERROR_MESSAGE = `Coinbase Wallet SDK requires the Cross-Origin-Opener-Policy header to not be set to 'same-origin'. This is to ensure that the SDK can communicate with the Coinbase Smart Wallet app.
3033
+
3034
+ Please see https://www.smartwallet.dev/guides/tips/popup-tips#cross-origin-opener-policy for more information.`;
3035
+ const createCoopChecker = () => {
3036
+ let crossOriginOpenerPolicy;
3037
+ return {
3038
+ getCrossOriginOpenerPolicy: () => {
3039
+ if (crossOriginOpenerPolicy === void 0) {
3040
+ return "undefined";
3041
+ }
3042
+ return crossOriginOpenerPolicy;
3043
+ },
3044
+ checkCrossOriginOpenerPolicy: async () => {
3045
+ if (typeof window === "undefined") {
3046
+ crossOriginOpenerPolicy = "non-browser-env";
3047
+ return;
3048
+ }
3049
+ try {
3050
+ const url = `${window.location.origin}${window.location.pathname}`;
3051
+ const response = await fetch(url, {
3052
+ method: "HEAD"
3053
+ });
3054
+ if (!response.ok) {
3055
+ throw new Error(`HTTP error! status: ${response.status}`);
3056
+ }
3057
+ const result = response.headers.get("Cross-Origin-Opener-Policy");
3058
+ crossOriginOpenerPolicy = result !== null && result !== void 0 ? result : "null";
3059
+ if (crossOriginOpenerPolicy === "same-origin") {
3060
+ console.error(COOP_ERROR_MESSAGE);
3061
+ }
3062
+ } catch (error) {
3063
+ console.error("Error checking Cross-Origin-Opener-Policy:", error.message);
3064
+ crossOriginOpenerPolicy = "error";
3065
+ }
3066
+ }
3067
+ };
3068
+ };
3069
+ const { checkCrossOriginOpenerPolicy, getCrossOriginOpenerPolicy } = createCoopChecker();
3070
+ const POPUP_WIDTH = 420;
3071
+ const POPUP_HEIGHT = 540;
3072
+ function openPopup(url) {
3073
+ const left = (window.innerWidth - POPUP_WIDTH) / 2 + window.screenX;
3074
+ const top = (window.innerHeight - POPUP_HEIGHT) / 2 + window.screenY;
3075
+ appendAppInfoQueryParams(url);
3076
+ const popupId = `wallet_${crypto.randomUUID()}`;
3077
+ const popup = window.open(url, popupId, `width=${POPUP_WIDTH}, height=${POPUP_HEIGHT}, left=${left}, top=${top}`);
3078
+ popup === null || popup === void 0 ? void 0 : popup.focus();
3079
+ if (!popup) {
3080
+ throw standardErrors.rpc.internal("Pop up window failed to open");
3081
+ }
3082
+ return popup;
3083
+ }
3084
+ function closePopup(popup) {
3085
+ if (popup && !popup.closed) {
3086
+ popup.close();
3087
+ }
3088
+ }
3089
+ function appendAppInfoQueryParams(url) {
3090
+ const params = {
3091
+ sdkName: NAME,
3092
+ sdkVersion: VERSION,
3093
+ origin: window.location.origin,
3094
+ coop: getCrossOriginOpenerPolicy()
3095
+ };
3096
+ for (const [key, value] of Object.entries(params)) {
3097
+ url.searchParams.append(key, value.toString());
3098
+ }
3099
+ }
3100
+ class Communicator {
3101
+ constructor({ url = CB_KEYS_URL, metadata, preference }) {
3102
+ this.popup = null;
3103
+ this.listeners = /* @__PURE__ */ new Map();
3104
+ this.postMessage = async (message) => {
3105
+ const popup = await this.waitForPopupLoaded();
3106
+ popup.postMessage(message, this.url.origin);
3107
+ };
3108
+ this.postRequestAndWaitForResponse = async (request) => {
3109
+ const responsePromise = this.onMessage(({ requestId }) => requestId === request.id);
3110
+ this.postMessage(request);
3111
+ return await responsePromise;
3112
+ };
3113
+ this.onMessage = async (predicate) => {
3114
+ return new Promise((resolve, reject) => {
3115
+ const listener = (event) => {
3116
+ if (event.origin !== this.url.origin)
3117
+ return;
3118
+ const message = event.data;
3119
+ if (predicate(message)) {
3120
+ resolve(message);
3121
+ window.removeEventListener("message", listener);
3122
+ this.listeners.delete(listener);
3123
+ }
3124
+ };
3125
+ window.addEventListener("message", listener);
3126
+ this.listeners.set(listener, { reject });
3127
+ });
3128
+ };
3129
+ this.disconnect = () => {
3130
+ closePopup(this.popup);
3131
+ this.popup = null;
3132
+ this.listeners.forEach(({ reject }, listener) => {
3133
+ reject(standardErrors.provider.userRejectedRequest("Request rejected"));
3134
+ window.removeEventListener("message", listener);
3135
+ });
3136
+ this.listeners.clear();
3137
+ };
3138
+ this.waitForPopupLoaded = async () => {
3139
+ if (this.popup && !this.popup.closed) {
3140
+ this.popup.focus();
3141
+ return this.popup;
3142
+ }
3143
+ this.popup = openPopup(this.url);
3144
+ this.onMessage(({ event }) => event === "PopupUnload").then(this.disconnect).catch(() => {
3145
+ });
3146
+ return this.onMessage(({ event }) => event === "PopupLoaded").then((message) => {
3147
+ this.postMessage({
3148
+ requestId: message.id,
3149
+ data: {
3150
+ version: VERSION,
3151
+ metadata: this.metadata,
3152
+ preference: this.preference,
3153
+ location: window.location.toString()
3154
+ }
3155
+ });
3156
+ }).then(() => {
3157
+ if (!this.popup)
3158
+ throw standardErrors.rpc.internal();
3159
+ return this.popup;
3160
+ });
3161
+ };
3162
+ this.url = new URL(url);
3163
+ this.metadata = metadata;
3164
+ this.preference = preference;
3165
+ }
3166
+ }
3167
+ function serializeError(error) {
3168
+ const serialized = serialize(getErrorObject(error), {
3169
+ shouldIncludeStack: true
3170
+ });
3171
+ const docUrl = new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");
3172
+ docUrl.searchParams.set("version", VERSION);
3173
+ docUrl.searchParams.set("code", serialized.code.toString());
3174
+ docUrl.searchParams.set("message", serialized.message);
3175
+ return Object.assign(Object.assign({}, serialized), { docUrl: docUrl.href });
3176
+ }
3177
+ function getErrorObject(error) {
3178
+ var _a;
3179
+ if (typeof error === "string") {
3180
+ return {
3181
+ message: error,
3182
+ code: standardErrorCodes.rpc.internal
3183
+ };
3184
+ } else if (isErrorResponse(error)) {
3185
+ const message = error.errorMessage;
3186
+ const code = (_a = error.errorCode) !== null && _a !== void 0 ? _a : message.match(/(denied|rejected)/i) ? standardErrorCodes.provider.userRejectedRequest : void 0;
3187
+ return Object.assign(Object.assign({}, error), {
3188
+ message,
3189
+ code,
3190
+ data: { method: error.method }
3191
+ });
3192
+ }
3193
+ return error;
3194
+ }
3195
+ class ProviderEventEmitter extends EventEmitter {
3196
+ }
3197
+ var __rest = function(s, e) {
3198
+ var t = {};
3199
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
3200
+ t[p] = s[p];
3201
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
3202
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
3203
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
3204
+ t[p[i]] = s[p[i]];
3205
+ }
3206
+ return t;
3207
+ };
3208
+ class CoinbaseWalletProvider extends ProviderEventEmitter {
3209
+ constructor(_a) {
3210
+ var { metadata } = _a, _b = _a.preference, { keysUrl } = _b, preference = __rest(_b, ["keysUrl"]);
3211
+ super();
3212
+ this.signer = null;
3213
+ this.isCoinbaseWallet = true;
3214
+ this.metadata = metadata;
3215
+ this.preference = preference;
3216
+ this.communicator = new Communicator({
3217
+ url: keysUrl,
3218
+ metadata,
3219
+ preference
3220
+ });
3221
+ const signerType = loadSignerType();
3222
+ if (signerType) {
3223
+ this.signer = this.initSigner(signerType);
3224
+ }
3225
+ }
3226
+ async request(args) {
3227
+ try {
3228
+ checkErrorForInvalidRequestArgs(args);
3229
+ if (!this.signer) {
3230
+ switch (args.method) {
3231
+ case "eth_requestAccounts": {
3232
+ const signerType = await this.requestSignerSelection(args);
3233
+ const signer = this.initSigner(signerType);
3234
+ await signer.handshake(args);
3235
+ this.signer = signer;
3236
+ storeSignerType(signerType);
3237
+ break;
3238
+ }
3239
+ case "wallet_sendCalls": {
3240
+ const ephemeralSigner = this.initSigner("scw");
3241
+ await ephemeralSigner.handshake({ method: "handshake" });
3242
+ const result = await ephemeralSigner.request(args);
3243
+ await ephemeralSigner.cleanup();
3244
+ return result;
3245
+ }
3246
+ case "wallet_getCallsStatus":
3247
+ return fetchRPCRequest(args, CB_WALLET_RPC_URL);
3248
+ case "net_version":
3249
+ return 1;
3250
+ case "eth_chainId":
3251
+ return hexStringFromNumber(1);
3252
+ default: {
3253
+ throw standardErrors.provider.unauthorized("Must call 'eth_requestAccounts' before other methods");
3254
+ }
3255
+ }
3256
+ }
3257
+ return await this.signer.request(args);
3258
+ } catch (error) {
3259
+ const { code } = error;
3260
+ if (code === standardErrorCodes.provider.unauthorized)
3261
+ this.disconnect();
3262
+ return Promise.reject(serializeError(error));
3263
+ }
3264
+ }
3265
+ /** @deprecated Use `.request({ method: 'eth_requestAccounts' })` instead. */
3266
+ async enable() {
3267
+ console.warn(`.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.`);
3268
+ return await this.request({
3269
+ method: "eth_requestAccounts"
3270
+ });
3271
+ }
3272
+ async disconnect() {
3273
+ var _a;
3274
+ await ((_a = this.signer) === null || _a === void 0 ? void 0 : _a.cleanup());
3275
+ this.signer = null;
3276
+ ScopedLocalStorage.clearAll();
3277
+ this.emit("disconnect", standardErrors.provider.disconnected("User initiated disconnection"));
3278
+ }
3279
+ requestSignerSelection(handshakeRequest) {
3280
+ return fetchSignerType({
3281
+ communicator: this.communicator,
3282
+ preference: this.preference,
3283
+ metadata: this.metadata,
3284
+ handshakeRequest,
3285
+ callback: this.emit.bind(this)
3286
+ });
3287
+ }
3288
+ initSigner(signerType) {
3289
+ return createSigner({
3290
+ signerType,
3291
+ metadata: this.metadata,
3292
+ communicator: this.communicator,
3293
+ callback: this.emit.bind(this)
3294
+ });
3295
+ }
3296
+ }
3297
+ function validatePreferences(preference) {
3298
+ if (!preference) {
3299
+ return;
3300
+ }
3301
+ if (!["all", "smartWalletOnly", "eoaOnly"].includes(preference.options)) {
3302
+ throw new Error(`Invalid options: ${preference.options}`);
3303
+ }
3304
+ if (preference.attribution) {
3305
+ if (preference.attribution.auto !== void 0 && preference.attribution.dataSuffix !== void 0) {
3306
+ throw new Error(`Attribution cannot contain both auto and dataSuffix properties`);
3307
+ }
3308
+ }
3309
+ }
3310
+ function createCoinbaseWalletProvider(options) {
3311
+ var _a;
3312
+ const params = {
3313
+ metadata: options.metadata,
3314
+ preference: options.preference
3315
+ };
3316
+ return (_a = getCoinbaseInjectedProvider(params)) !== null && _a !== void 0 ? _a : new CoinbaseWalletProvider(params);
3317
+ }
3318
+ const DEFAULT_PREFERENCE = {
3319
+ options: "all"
3320
+ };
3321
+ function createCoinbaseWalletSDK(params) {
3322
+ var _a;
3323
+ const versionStorage = new ScopedLocalStorage("CBWSDK");
3324
+ versionStorage.setItem("VERSION", VERSION);
3325
+ void checkCrossOriginOpenerPolicy();
3326
+ const options = {
3327
+ metadata: {
3328
+ appName: params.appName || "Dapp",
3329
+ appLogoUrl: params.appLogoUrl || "",
3330
+ appChainIds: params.appChainIds || []
3331
+ },
3332
+ preference: Object.assign(DEFAULT_PREFERENCE, (_a = params.preference) !== null && _a !== void 0 ? _a : {})
3333
+ };
3334
+ validatePreferences(options.preference);
3335
+ let provider = null;
3336
+ return {
3337
+ getProvider: () => {
3338
+ if (!provider) {
3339
+ provider = createCoinbaseWalletProvider(options);
3340
+ }
3341
+ return provider;
3342
+ }
3343
+ };
3344
+ }
3345
+ export {
3346
+ createCoinbaseWalletSDK
3347
+ };
3348
+ //# sourceMappingURL=index-CRQSbrdZ.js.map