@metamask/connect-multichain 0.1.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 (241) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +20 -0
  3. package/README.md +15 -0
  4. package/dist/browser/es/connect-multichain.d.mts +585 -0
  5. package/dist/browser/es/connect-multichain.mjs +2609 -0
  6. package/dist/browser/es/connect-multichain.mjs.map +1 -0
  7. package/dist/browser/es/metafile-esm.json +1 -0
  8. package/dist/browser/iife/connect-multichain.d.ts +585 -0
  9. package/dist/browser/iife/connect-multichain.js +30057 -0
  10. package/dist/browser/iife/connect-multichain.js.map +1 -0
  11. package/dist/browser/iife/metafile-iife.json +1 -0
  12. package/dist/browser/umd/connect-multichain.d.ts +585 -0
  13. package/dist/browser/umd/connect-multichain.js +2622 -0
  14. package/dist/browser/umd/connect-multichain.js.map +1 -0
  15. package/dist/browser/umd/metafile-cjs.json +1 -0
  16. package/dist/node/cjs/connect-multichain.d.ts +585 -0
  17. package/dist/node/cjs/connect-multichain.js +2603 -0
  18. package/dist/node/cjs/connect-multichain.js.map +1 -0
  19. package/dist/node/cjs/metafile-cjs.json +1 -0
  20. package/dist/node/es/connect-multichain.d.mts +585 -0
  21. package/dist/node/es/connect-multichain.mjs +2564 -0
  22. package/dist/node/es/connect-multichain.mjs.map +1 -0
  23. package/dist/node/es/metafile-esm.json +1 -0
  24. package/dist/react-native/es/connect-multichain.d.mts +585 -0
  25. package/dist/react-native/es/connect-multichain.mjs +2517 -0
  26. package/dist/react-native/es/connect-multichain.mjs.map +1 -0
  27. package/dist/react-native/es/metafile-esm.json +1 -0
  28. package/dist/src/config/index.d.ts +4 -0
  29. package/dist/src/config/index.d.ts.map +1 -0
  30. package/dist/src/config/index.js +4 -0
  31. package/dist/src/config/index.js.map +1 -0
  32. package/dist/src/domain/errors/base.d.ts +7 -0
  33. package/dist/src/domain/errors/base.d.ts.map +1 -0
  34. package/dist/src/domain/errors/base.js +8 -0
  35. package/dist/src/domain/errors/base.js.map +1 -0
  36. package/dist/src/domain/errors/index.d.ts +3 -0
  37. package/dist/src/domain/errors/index.d.ts.map +1 -0
  38. package/dist/src/domain/errors/index.js +2 -0
  39. package/dist/src/domain/errors/index.js.map +1 -0
  40. package/dist/src/domain/errors/rpc.d.ts +25 -0
  41. package/dist/src/domain/errors/rpc.d.ts.map +1 -0
  42. package/dist/src/domain/errors/rpc.js +33 -0
  43. package/dist/src/domain/errors/rpc.js.map +1 -0
  44. package/dist/src/domain/errors/storage.d.ts +24 -0
  45. package/dist/src/domain/errors/storage.d.ts.map +1 -0
  46. package/dist/src/domain/errors/storage.js +30 -0
  47. package/dist/src/domain/errors/storage.js.map +1 -0
  48. package/dist/src/domain/errors/types.d.ts +7 -0
  49. package/dist/src/domain/errors/types.d.ts.map +1 -0
  50. package/dist/src/domain/errors/types.js +2 -0
  51. package/dist/src/domain/errors/types.js.map +1 -0
  52. package/dist/src/domain/events/index.d.ts +39 -0
  53. package/dist/src/domain/events/index.d.ts.map +1 -0
  54. package/dist/src/domain/events/index.js +58 -0
  55. package/dist/src/domain/events/index.js.map +1 -0
  56. package/dist/src/domain/events/types/index.d.ts +8 -0
  57. package/dist/src/domain/events/types/index.d.ts.map +1 -0
  58. package/dist/src/domain/events/types/index.js +2 -0
  59. package/dist/src/domain/events/types/index.js.map +1 -0
  60. package/dist/src/domain/index.d.ts +9 -0
  61. package/dist/src/domain/index.d.ts.map +1 -0
  62. package/dist/src/domain/index.js +9 -0
  63. package/dist/src/domain/index.js.map +1 -0
  64. package/dist/src/domain/logger/index.d.ts +41 -0
  65. package/dist/src/domain/logger/index.d.ts.map +1 -0
  66. package/dist/src/domain/logger/index.js +79 -0
  67. package/dist/src/domain/logger/index.js.map +1 -0
  68. package/dist/src/domain/multichain/api/constants.d.ts +5 -0
  69. package/dist/src/domain/multichain/api/constants.d.ts.map +1 -0
  70. package/dist/src/domain/multichain/api/constants.js +101 -0
  71. package/dist/src/domain/multichain/api/constants.js.map +1 -0
  72. package/dist/src/domain/multichain/api/eip155.d.ts +58 -0
  73. package/dist/src/domain/multichain/api/eip155.d.ts.map +1 -0
  74. package/dist/src/domain/multichain/api/eip155.js +2 -0
  75. package/dist/src/domain/multichain/api/eip155.js.map +1 -0
  76. package/dist/src/domain/multichain/api/infura.d.ts +3 -0
  77. package/dist/src/domain/multichain/api/infura.d.ts.map +1 -0
  78. package/dist/src/domain/multichain/api/infura.js +10 -0
  79. package/dist/src/domain/multichain/api/infura.js.map +1 -0
  80. package/dist/src/domain/multichain/api/types.d.ts +89 -0
  81. package/dist/src/domain/multichain/api/types.d.ts.map +1 -0
  82. package/dist/src/domain/multichain/api/types.js +2 -0
  83. package/dist/src/domain/multichain/api/types.js.map +1 -0
  84. package/dist/src/domain/multichain/index.d.ts +51 -0
  85. package/dist/src/domain/multichain/index.d.ts.map +1 -0
  86. package/dist/src/domain/multichain/index.js +33 -0
  87. package/dist/src/domain/multichain/index.js.map +1 -0
  88. package/dist/src/domain/multichain/types.d.ts +102 -0
  89. package/dist/src/domain/multichain/types.d.ts.map +1 -0
  90. package/dist/src/domain/multichain/types.js +2 -0
  91. package/dist/src/domain/multichain/types.js.map +1 -0
  92. package/dist/src/domain/platform/index.d.ts +17 -0
  93. package/dist/src/domain/platform/index.d.ts.map +1 -0
  94. package/dist/src/domain/platform/index.js +122 -0
  95. package/dist/src/domain/platform/index.js.map +1 -0
  96. package/dist/src/domain/store/adapter.d.ts +10 -0
  97. package/dist/src/domain/store/adapter.d.ts.map +1 -0
  98. package/dist/src/domain/store/adapter.js +6 -0
  99. package/dist/src/domain/store/adapter.js.map +1 -0
  100. package/dist/src/domain/store/client.d.ts +16 -0
  101. package/dist/src/domain/store/client.d.ts.map +1 -0
  102. package/dist/src/domain/store/client.js +3 -0
  103. package/dist/src/domain/store/client.js.map +1 -0
  104. package/dist/src/domain/store/index.d.ts +3 -0
  105. package/dist/src/domain/store/index.d.ts.map +1 -0
  106. package/dist/src/domain/store/index.js +3 -0
  107. package/dist/src/domain/store/index.js.map +1 -0
  108. package/dist/src/domain/ui/factory.d.ts +26 -0
  109. package/dist/src/domain/ui/factory.d.ts.map +1 -0
  110. package/dist/src/domain/ui/factory.js +2 -0
  111. package/dist/src/domain/ui/factory.js.map +1 -0
  112. package/dist/src/domain/ui/index.d.ts +3 -0
  113. package/dist/src/domain/ui/index.d.ts.map +1 -0
  114. package/dist/src/domain/ui/index.js +2 -0
  115. package/dist/src/domain/ui/index.js.map +1 -0
  116. package/dist/src/domain/ui/types.d.ts +34 -0
  117. package/dist/src/domain/ui/types.d.ts.map +1 -0
  118. package/dist/src/domain/ui/types.js +38 -0
  119. package/dist/src/domain/ui/types.js.map +1 -0
  120. package/dist/src/domain/utils/index.d.ts +7 -0
  121. package/dist/src/domain/utils/index.d.ts.map +1 -0
  122. package/dist/src/domain/utils/index.js +9 -0
  123. package/dist/src/domain/utils/index.js.map +1 -0
  124. package/dist/src/index.browser.d.ts +4 -0
  125. package/dist/src/index.browser.d.ts.map +1 -0
  126. package/dist/src/index.browser.js +28 -0
  127. package/dist/src/index.browser.js.map +1 -0
  128. package/dist/src/index.native.d.ts +4 -0
  129. package/dist/src/index.native.d.ts.map +1 -0
  130. package/dist/src/index.native.js +28 -0
  131. package/dist/src/index.native.js.map +1 -0
  132. package/dist/src/index.node.d.ts +4 -0
  133. package/dist/src/index.node.d.ts.map +1 -0
  134. package/dist/src/index.node.js +28 -0
  135. package/dist/src/index.node.js.map +1 -0
  136. package/dist/src/multichain/index.d.ts +41 -0
  137. package/dist/src/multichain/index.d.ts.map +1 -0
  138. package/dist/src/multichain/index.js +499 -0
  139. package/dist/src/multichain/index.js.map +1 -0
  140. package/dist/src/multichain/rpc/handlers/rpcClient.d.ts +19 -0
  141. package/dist/src/multichain/rpc/handlers/rpcClient.d.ts.map +1 -0
  142. package/dist/src/multichain/rpc/handlers/rpcClient.js +105 -0
  143. package/dist/src/multichain/rpc/handlers/rpcClient.js.map +1 -0
  144. package/dist/src/multichain/rpc/requestRouter.d.ts +29 -0
  145. package/dist/src/multichain/rpc/requestRouter.d.ts.map +1 -0
  146. package/dist/src/multichain/rpc/requestRouter.js +104 -0
  147. package/dist/src/multichain/rpc/requestRouter.js.map +1 -0
  148. package/dist/src/multichain/transports/default/index.d.ts +17 -0
  149. package/dist/src/multichain/transports/default/index.d.ts.map +1 -0
  150. package/dist/src/multichain/transports/default/index.js +101 -0
  151. package/dist/src/multichain/transports/default/index.js.map +1 -0
  152. package/dist/src/multichain/transports/mwp/KeyManager.d.ts +9 -0
  153. package/dist/src/multichain/transports/mwp/KeyManager.d.ts.map +1 -0
  154. package/dist/src/multichain/transports/mwp/KeyManager.js +35 -0
  155. package/dist/src/multichain/transports/mwp/KeyManager.js.map +1 -0
  156. package/dist/src/multichain/transports/mwp/index.d.ts +65 -0
  157. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -0
  158. package/dist/src/multichain/transports/mwp/index.js +323 -0
  159. package/dist/src/multichain/transports/mwp/index.js.map +1 -0
  160. package/dist/src/multichain/utils/index.d.ts +41 -0
  161. package/dist/src/multichain/utils/index.d.ts.map +1 -0
  162. package/dist/src/multichain/utils/index.js +239 -0
  163. package/dist/src/multichain/utils/index.js.map +1 -0
  164. package/dist/src/store/adapters/node.d.ts +9 -0
  165. package/dist/src/store/adapters/node.d.ts.map +1 -0
  166. package/dist/src/store/adapters/node.js +34 -0
  167. package/dist/src/store/adapters/node.js.map +1 -0
  168. package/dist/src/store/adapters/rn.d.ts +8 -0
  169. package/dist/src/store/adapters/rn.d.ts.map +1 -0
  170. package/dist/src/store/adapters/rn.js +33 -0
  171. package/dist/src/store/adapters/rn.js.map +1 -0
  172. package/dist/src/store/adapters/web.d.ts +16 -0
  173. package/dist/src/store/adapters/web.d.ts.map +1 -0
  174. package/dist/src/store/adapters/web.js +99 -0
  175. package/dist/src/store/adapters/web.js.map +1 -0
  176. package/dist/src/store/index.d.ts +17 -0
  177. package/dist/src/store/index.d.ts.map +1 -0
  178. package/dist/src/store/index.js +130 -0
  179. package/dist/src/store/index.js.map +1 -0
  180. package/dist/src/ui/index.d.ts +45 -0
  181. package/dist/src/ui/index.d.ts.map +1 -0
  182. package/dist/src/ui/index.js +185 -0
  183. package/dist/src/ui/index.js.map +1 -0
  184. package/dist/src/ui/modals/base/AbstractInstallModal.d.ts +16 -0
  185. package/dist/src/ui/modals/base/AbstractInstallModal.d.ts.map +1 -0
  186. package/dist/src/ui/modals/base/AbstractInstallModal.js +90 -0
  187. package/dist/src/ui/modals/base/AbstractInstallModal.js.map +1 -0
  188. package/dist/src/ui/modals/base/AbstractOTPModal.d.ts +8 -0
  189. package/dist/src/ui/modals/base/AbstractOTPModal.d.ts.map +1 -0
  190. package/dist/src/ui/modals/base/AbstractOTPModal.js +16 -0
  191. package/dist/src/ui/modals/base/AbstractOTPModal.js.map +1 -0
  192. package/dist/src/ui/modals/base/utils.d.ts +3 -0
  193. package/dist/src/ui/modals/base/utils.d.ts.map +1 -0
  194. package/dist/src/ui/modals/base/utils.js +30 -0
  195. package/dist/src/ui/modals/base/utils.js.map +1 -0
  196. package/dist/src/ui/modals/node/index.d.ts +3 -0
  197. package/dist/src/ui/modals/node/index.d.ts.map +1 -0
  198. package/dist/src/ui/modals/node/index.js +3 -0
  199. package/dist/src/ui/modals/node/index.js.map +1 -0
  200. package/dist/src/ui/modals/node/install.d.ts +9 -0
  201. package/dist/src/ui/modals/node/install.d.ts.map +1 -0
  202. package/dist/src/ui/modals/node/install.js +47 -0
  203. package/dist/src/ui/modals/node/install.js.map +1 -0
  204. package/dist/src/ui/modals/node/otp.d.ts +10 -0
  205. package/dist/src/ui/modals/node/otp.d.ts.map +1 -0
  206. package/dist/src/ui/modals/node/otp.js +10 -0
  207. package/dist/src/ui/modals/node/otp.js.map +1 -0
  208. package/dist/src/ui/modals/rn/index.d.ts +3 -0
  209. package/dist/src/ui/modals/rn/index.d.ts.map +1 -0
  210. package/dist/src/ui/modals/rn/index.js +3 -0
  211. package/dist/src/ui/modals/rn/index.js.map +1 -0
  212. package/dist/src/ui/modals/rn/install.d.ts +7 -0
  213. package/dist/src/ui/modals/rn/install.d.ts.map +1 -0
  214. package/dist/src/ui/modals/rn/install.js +9 -0
  215. package/dist/src/ui/modals/rn/install.js.map +1 -0
  216. package/dist/src/ui/modals/rn/otp.d.ts +10 -0
  217. package/dist/src/ui/modals/rn/otp.d.ts.map +1 -0
  218. package/dist/src/ui/modals/rn/otp.js +10 -0
  219. package/dist/src/ui/modals/rn/otp.js.map +1 -0
  220. package/dist/src/ui/modals/types.d.ts +13 -0
  221. package/dist/src/ui/modals/types.d.ts.map +1 -0
  222. package/dist/src/ui/modals/types.js +2 -0
  223. package/dist/src/ui/modals/types.js.map +1 -0
  224. package/dist/src/ui/modals/web/index.d.ts +3 -0
  225. package/dist/src/ui/modals/web/index.d.ts.map +1 -0
  226. package/dist/src/ui/modals/web/index.js +3 -0
  227. package/dist/src/ui/modals/web/index.js.map +1 -0
  228. package/dist/src/ui/modals/web/install.d.ts +7 -0
  229. package/dist/src/ui/modals/web/install.d.ts.map +1 -0
  230. package/dist/src/ui/modals/web/install.js +32 -0
  231. package/dist/src/ui/modals/web/install.js.map +1 -0
  232. package/dist/src/ui/modals/web/otp.d.ts +10 -0
  233. package/dist/src/ui/modals/web/otp.d.ts.map +1 -0
  234. package/dist/src/ui/modals/web/otp.js +10 -0
  235. package/dist/src/ui/modals/web/otp.js.map +1 -0
  236. package/dist/src/ui/qr.d.ts +3 -0
  237. package/dist/src/ui/qr.d.ts.map +1 -0
  238. package/dist/src/ui/qr.js +32 -0
  239. package/dist/src/ui/qr.js.map +1 -0
  240. package/dist/types/connect-multichain.d.ts +585 -0
  241. package/package.json +111 -0
@@ -0,0 +1,2564 @@
1
+ /* Node.js ES build */
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
+ var __typeError = (msg) => {
10
+ throw TypeError(msg);
11
+ };
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __esm = (fn, res) => function __init() {
26
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
27
+ };
28
+ var __export = (target, all) => {
29
+ for (var name in all)
30
+ __defProp(target, name, { get: all[name], enumerable: true });
31
+ };
32
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
33
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
34
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
35
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
36
+ var __async = (__this, __arguments, generator) => {
37
+ return new Promise((resolve, reject) => {
38
+ var fulfilled = (value) => {
39
+ try {
40
+ step(generator.next(value));
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ };
45
+ var rejected = (value) => {
46
+ try {
47
+ step(generator.throw(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
53
+ step((generator = generator.apply(__this, __arguments)).next());
54
+ });
55
+ };
56
+
57
+ // src/domain/errors/base.ts
58
+ var BaseErr;
59
+ var init_base = __esm({
60
+ "src/domain/errors/base.ts"() {
61
+ "use strict";
62
+ BaseErr = class extends Error {
63
+ constructor(message, code) {
64
+ super(message);
65
+ this.message = message;
66
+ this.code = code;
67
+ }
68
+ };
69
+ }
70
+ });
71
+
72
+ // src/domain/errors/rpc.ts
73
+ var _RPCHttpErr, RPCHttpErr, _RPCReadonlyResponseErr, RPCReadonlyResponseErr, _RPCReadonlyRequestErr, RPCReadonlyRequestErr, _RPCInvokeMethodErr, RPCInvokeMethodErr;
74
+ var init_rpc = __esm({
75
+ "src/domain/errors/rpc.ts"() {
76
+ "use strict";
77
+ init_base();
78
+ _RPCHttpErr = class _RPCHttpErr extends BaseErr {
79
+ constructor(rpcEndpoint, method, httpStatus) {
80
+ super(
81
+ `RPCErr${_RPCHttpErr.code}: ${httpStatus} on ${rpcEndpoint} for method ${method}`,
82
+ _RPCHttpErr.code
83
+ );
84
+ this.rpcEndpoint = rpcEndpoint;
85
+ this.method = method;
86
+ this.httpStatus = httpStatus;
87
+ }
88
+ };
89
+ _RPCHttpErr.code = 50;
90
+ RPCHttpErr = _RPCHttpErr;
91
+ _RPCReadonlyResponseErr = class _RPCReadonlyResponseErr extends BaseErr {
92
+ constructor(reason) {
93
+ super(
94
+ `RPCErr${_RPCReadonlyResponseErr.code}: RPC Client response reason ${reason}`,
95
+ _RPCReadonlyResponseErr.code
96
+ );
97
+ this.reason = reason;
98
+ }
99
+ };
100
+ _RPCReadonlyResponseErr.code = 51;
101
+ RPCReadonlyResponseErr = _RPCReadonlyResponseErr;
102
+ _RPCReadonlyRequestErr = class _RPCReadonlyRequestErr extends BaseErr {
103
+ constructor(reason) {
104
+ super(
105
+ `RPCErr${_RPCReadonlyRequestErr.code}: RPC Client fetch reason ${reason}`,
106
+ _RPCReadonlyRequestErr.code
107
+ );
108
+ this.reason = reason;
109
+ }
110
+ };
111
+ _RPCReadonlyRequestErr.code = 52;
112
+ RPCReadonlyRequestErr = _RPCReadonlyRequestErr;
113
+ _RPCInvokeMethodErr = class _RPCInvokeMethodErr extends BaseErr {
114
+ constructor(reason) {
115
+ super(
116
+ `RPCErr${_RPCInvokeMethodErr.code}: RPC Client invoke method reason (${reason})`,
117
+ _RPCInvokeMethodErr.code
118
+ );
119
+ this.reason = reason;
120
+ }
121
+ };
122
+ _RPCInvokeMethodErr.code = 53;
123
+ RPCInvokeMethodErr = _RPCInvokeMethodErr;
124
+ }
125
+ });
126
+
127
+ // src/domain/errors/index.ts
128
+ var init_errors = __esm({
129
+ "src/domain/errors/index.ts"() {
130
+ "use strict";
131
+ init_rpc();
132
+ }
133
+ });
134
+
135
+ // src/domain/events/index.ts
136
+ import { EventEmitter as EventEmitter3 } from "eventemitter3";
137
+ var _emitter, EventEmitter;
138
+ var init_events = __esm({
139
+ "src/domain/events/index.ts"() {
140
+ "use strict";
141
+ EventEmitter = class {
142
+ constructor() {
143
+ __privateAdd(this, _emitter, new EventEmitter3());
144
+ }
145
+ /**
146
+ * Emits an event with the specified name and arguments.
147
+ *
148
+ * @template TEventName - The name of the event to emit (must be a key of TEvents)
149
+ * @param eventName - The name of the event to emit
150
+ * @param eventArg - The arguments to pass to the event handlers
151
+ */
152
+ emit(eventName, ...eventArg) {
153
+ __privateGet(this, _emitter).emit(eventName, ...eventArg);
154
+ }
155
+ /**
156
+ * Registers an event handler for the specified event.
157
+ *
158
+ * @template TEventName - The name of the event to listen for (must be a key of TEvents)
159
+ * @param eventName - The name of the event to listen for
160
+ * @param handler - The function to call when the event is emitted
161
+ * @returns Nothing
162
+ */
163
+ on(eventName, handler) {
164
+ __privateGet(this, _emitter).on(eventName, handler);
165
+ return () => {
166
+ this.off(eventName, handler);
167
+ };
168
+ }
169
+ /**
170
+ * Removes a specific event handler for the specified event.
171
+ *
172
+ * @template TEventName - The name of the event to remove the handler from (must be a key of TEvents)
173
+ * @param eventName - The name of the event to remove the handler from
174
+ * @param handler - The specific handler function to remove
175
+ */
176
+ off(eventName, handler) {
177
+ __privateGet(this, _emitter).off(eventName, handler);
178
+ }
179
+ };
180
+ _emitter = new WeakMap();
181
+ }
182
+ });
183
+
184
+ // src/domain/logger/index.ts
185
+ import debug from "debug";
186
+ function isNamespaceEnabled(debugValue, namespace) {
187
+ return debugValue.includes(namespace) || debugValue.includes("metamask-sdk:*") || debugValue.includes("*");
188
+ }
189
+ var createLogger, enableDebug, isEnabled;
190
+ var init_logger = __esm({
191
+ "src/domain/logger/index.ts"() {
192
+ "use strict";
193
+ createLogger = (namespace = "metamask-sdk", color = "214") => {
194
+ const logger5 = debug(namespace);
195
+ logger5.color = color;
196
+ return logger5;
197
+ };
198
+ enableDebug = (namespace = "metamask-sdk") => {
199
+ debug.enable(namespace);
200
+ };
201
+ isEnabled = (namespace, storage) => __async(null, null, function* () {
202
+ var _a;
203
+ if ("process" in globalThis && ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.DEBUG)) {
204
+ const { DEBUG } = process.env;
205
+ return isNamespaceEnabled(DEBUG, namespace);
206
+ }
207
+ const storageDebug = yield storage.getDebug();
208
+ if (storageDebug) {
209
+ return isNamespaceEnabled(storageDebug, namespace);
210
+ }
211
+ return false;
212
+ });
213
+ }
214
+ });
215
+
216
+ // src/domain/multichain/api/constants.ts
217
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
218
+ var init_constants = __esm({
219
+ "src/domain/multichain/api/constants.ts"() {
220
+ "use strict";
221
+ infuraRpcUrls = {
222
+ // ###### Ethereum ######
223
+ // Mainnet
224
+ "eip155:1": "https://mainnet.infura.io/v3/",
225
+ // Goerli
226
+ "eip155:5": "https://goerli.infura.io/v3/",
227
+ // Sepolia 11155111
228
+ "eip155:11155111": "https://sepolia.infura.io/v3/",
229
+ // ###### Linea ######
230
+ // Mainnet Alpha
231
+ "eip155:59144": "https://linea-mainnet.infura.io/v3/",
232
+ // Testnet ( linea goerli )
233
+ "eip155:59140": "https://linea-goerli.infura.io/v3/",
234
+ // ###### Polygon ######
235
+ // Mainnet
236
+ "eip155:137": "https://polygon-mainnet.infura.io/v3/",
237
+ // Mumbai
238
+ "eip155:80001": "https://polygon-mumbai.infura.io/v3/",
239
+ // ###### Optimism ######
240
+ // Mainnet
241
+ "eip155:10": "https://optimism-mainnet.infura.io/v3/",
242
+ // Goerli
243
+ "eip155:420": "https://optimism-goerli.infura.io/v3/",
244
+ // ###### Arbitrum ######
245
+ // Mainnet
246
+ "eip155:42161": "https://arbitrum-mainnet.infura.io/v3/",
247
+ // Goerli
248
+ "eip155:421613": "https://arbitrum-goerli.infura.io/v3/",
249
+ // ###### Palm ######
250
+ // Mainnet
251
+ "eip155:11297108109": "https://palm-mainnet.infura.io/v3/",
252
+ // Testnet
253
+ "eip155:11297108099": "https://palm-testnet.infura.io/v3/",
254
+ // ###### Avalanche C-Chain ######
255
+ // Mainnet
256
+ "eip155:43114": "https://avalanche-mainnet.infura.io/v3/",
257
+ // Fuji
258
+ "eip155:43113": "https://avalanche-fuji.infura.io/v3/",
259
+ // // ###### NEAR ######
260
+ // // Mainnet
261
+ // 'near:mainnet': `https://near-mainnet.infura.io/v3/`,
262
+ // // Testnet
263
+ // 'near:testnet': `https://near-testnet.infura.io/v3/`,
264
+ // ###### Aurora ######
265
+ // Mainnet
266
+ "eip155:1313161554": "https://aurora-mainnet.infura.io/v3/",
267
+ // Testnet
268
+ "eip155:1313161555": "https://aurora-testnet.infura.io/v3/",
269
+ // ###### StarkNet ######
270
+ // Mainnet
271
+ //
272
+ // 'starknet:SN_MAIN': `https://starknet-mainnet.infura.io/v3/`,
273
+ // // Goerli
274
+ // 'starknet:SN_GOERLI': `https://starknet-goerli.infura.io/v3/`,
275
+ // // Goerli 2
276
+ // 'starknet:SN_GOERLI2': `https://starknet-goerli2.infura.io/v3/`,
277
+ // ###### Celo ######
278
+ // Mainnet
279
+ "eip155:42220": "https://celo-mainnet.infura.io/v3/",
280
+ // Alfajores Testnet
281
+ "eip155:44787": "https://celo-alfajores.infura.io/v3/"
282
+ };
283
+ RPC_HANDLED_METHODS = /* @__PURE__ */ new Set([
284
+ "eth_blockNumber",
285
+ "eth_gasPrice",
286
+ "eth_maxPriorityFeePerGas",
287
+ "eth_blobBaseFee",
288
+ "eth_feeHistory",
289
+ "eth_getBalance",
290
+ "eth_getCode",
291
+ "eth_getStorageAt",
292
+ "eth_call",
293
+ "eth_estimateGas",
294
+ "eth_getLogs",
295
+ "eth_getProof",
296
+ "eth_getTransactionCount",
297
+ "eth_getBlockByNumber",
298
+ "eth_getBlockByHash",
299
+ "eth_getBlockTransactionCountByNumber",
300
+ "eth_getBlockTransactionCountByHash",
301
+ "eth_getUncleCountByBlockNumber",
302
+ "eth_getUncleCountByBlockHash",
303
+ "eth_getTransactionByHash",
304
+ "eth_getTransactionByBlockNumberAndIndex",
305
+ "eth_getTransactionByBlockHashAndIndex",
306
+ "eth_getTransactionReceipt",
307
+ "eth_getUncleByBlockNumberAndIndex",
308
+ "eth_getUncleByBlockHashAndIndex",
309
+ "eth_getFilterChanges",
310
+ "eth_getFilterLogs",
311
+ "eth_newBlockFilter",
312
+ "eth_newFilter",
313
+ "eth_newPendingTransactionFilter",
314
+ "eth_sendRawTransaction",
315
+ "eth_syncing",
316
+ "eth_uninstallFilter"
317
+ ]);
318
+ SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
319
+ }
320
+ });
321
+
322
+ // src/domain/multichain/api/infura.ts
323
+ function getInfuraRpcUrls(infuraAPIKey) {
324
+ return Object.keys(infuraRpcUrls).reduce((acc, key) => {
325
+ const typedKey = key;
326
+ acc[typedKey] = `${infuraRpcUrls[typedKey]}${infuraAPIKey}`;
327
+ return acc;
328
+ }, {});
329
+ }
330
+ var init_infura = __esm({
331
+ "src/domain/multichain/api/infura.ts"() {
332
+ "use strict";
333
+ init_constants();
334
+ }
335
+ });
336
+
337
+ // src/domain/multichain/index.ts
338
+ function getTransportType(type) {
339
+ switch (type) {
340
+ case "browser":
341
+ return "browser" /* Browser */;
342
+ case "mwp":
343
+ return "mwp" /* MPW */;
344
+ default:
345
+ return "unknown" /* UNKNOWN */;
346
+ }
347
+ }
348
+ var TransportType, MultichainCore;
349
+ var init_multichain = __esm({
350
+ "src/domain/multichain/index.ts"() {
351
+ "use strict";
352
+ init_events();
353
+ init_constants();
354
+ init_infura();
355
+ TransportType = /* @__PURE__ */ ((TransportType2) => {
356
+ TransportType2["Browser"] = "browser";
357
+ TransportType2["MPW"] = "mwp";
358
+ TransportType2["UNKNOWN"] = "unknown";
359
+ return TransportType2;
360
+ })(TransportType || {});
361
+ MultichainCore = class extends EventEmitter {
362
+ constructor(options) {
363
+ super();
364
+ this.options = options;
365
+ }
366
+ };
367
+ }
368
+ });
369
+
370
+ // src/domain/platform/index.ts
371
+ import { parse } from "bowser";
372
+ function isNotBrowser() {
373
+ var _a;
374
+ if (typeof window === "undefined") {
375
+ return true;
376
+ }
377
+ if (!(window == null ? void 0 : window.navigator)) {
378
+ return true;
379
+ }
380
+ if (typeof global !== "undefined" && ((_a = global == null ? void 0 : global.navigator) == null ? void 0 : _a.product) === "ReactNative") {
381
+ return true;
382
+ }
383
+ return (navigator == null ? void 0 : navigator.product) === "ReactNative";
384
+ }
385
+ function isReactNative() {
386
+ var _a;
387
+ const hasWindowNavigator = typeof window !== "undefined" && window.navigator !== void 0;
388
+ const nav = hasWindowNavigator ? window.navigator : void 0;
389
+ if (!nav) {
390
+ return false;
391
+ }
392
+ return hasWindowNavigator && ((_a = window.navigator) == null ? void 0 : _a.product) === "ReactNative";
393
+ }
394
+ function isMetaMaskMobileWebView() {
395
+ return typeof window !== "undefined" && // @ts-expect-error ReactNativeWebView should be defined
396
+ Boolean(window.ReactNativeWebView) && Boolean(window.navigator.userAgent.endsWith("MetaMaskMobile"));
397
+ }
398
+ function isMobile() {
399
+ var _a, _b;
400
+ const browser = parse(window.navigator.userAgent);
401
+ return ((_a = browser == null ? void 0 : browser.platform) == null ? void 0 : _a.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
402
+ }
403
+ function getPlatformType() {
404
+ if (isReactNative()) {
405
+ return "react-native" /* ReactNative */;
406
+ }
407
+ if (isNotBrowser()) {
408
+ return "nodejs" /* NonBrowser */;
409
+ }
410
+ if (isMetaMaskMobileWebView()) {
411
+ return "in-app-browser" /* MetaMaskMobileWebview */;
412
+ }
413
+ if (isMobile()) {
414
+ return "web-mobile" /* MobileWeb */;
415
+ }
416
+ return "web-desktop" /* DesktopWeb */;
417
+ }
418
+ function isMetamaskExtensionInstalled() {
419
+ var _a;
420
+ if (typeof window === "undefined") {
421
+ return false;
422
+ }
423
+ return Boolean((_a = window.ethereum) == null ? void 0 : _a.isMetaMask);
424
+ }
425
+ function isSecure() {
426
+ const platformType = getPlatformType();
427
+ return isReactNative() || platformType === "web-mobile" /* MobileWeb */;
428
+ }
429
+ function hasExtension() {
430
+ return __async(this, null, function* () {
431
+ return detectionPromise;
432
+ });
433
+ }
434
+ var PlatformType, detectionPromise;
435
+ var init_platform = __esm({
436
+ "src/domain/platform/index.ts"() {
437
+ "use strict";
438
+ PlatformType = /* @__PURE__ */ ((PlatformType2) => {
439
+ PlatformType2["NonBrowser"] = "nodejs";
440
+ PlatformType2["MetaMaskMobileWebview"] = "in-app-browser";
441
+ PlatformType2["DesktopWeb"] = "web-desktop";
442
+ PlatformType2["MobileWeb"] = "web-mobile";
443
+ PlatformType2["ReactNative"] = "react-native";
444
+ return PlatformType2;
445
+ })(PlatformType || {});
446
+ detectionPromise = (() => __async(null, null, function* () {
447
+ const pt = getPlatformType();
448
+ if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
449
+ return Promise.resolve(false);
450
+ }
451
+ return new Promise((resolve) => {
452
+ const providers = [];
453
+ const handler = (event) => {
454
+ var _a, _b;
455
+ if ((_b = (_a = event == null ? void 0 : event.detail) == null ? void 0 : _a.info) == null ? void 0 : _b.rdns) {
456
+ providers.push(event.detail);
457
+ }
458
+ };
459
+ window.addEventListener("eip6963:announceProvider", handler);
460
+ window.dispatchEvent(new Event("eip6963:requestProvider"));
461
+ setTimeout(() => {
462
+ window.removeEventListener("eip6963:announceProvider", handler);
463
+ const hasMetaMask = providers.some(
464
+ (provider) => {
465
+ var _a;
466
+ return ((_a = provider == null ? void 0 : provider.info) == null ? void 0 : _a.rdns) === "io.metamask";
467
+ }
468
+ );
469
+ resolve(hasMetaMask);
470
+ }, 300);
471
+ });
472
+ }))();
473
+ }
474
+ });
475
+
476
+ // src/domain/store/adapter.ts
477
+ var StoreAdapter;
478
+ var init_adapter = __esm({
479
+ "src/domain/store/adapter.ts"() {
480
+ "use strict";
481
+ StoreAdapter = class {
482
+ constructor(options) {
483
+ this.options = options;
484
+ }
485
+ };
486
+ }
487
+ });
488
+
489
+ // src/domain/store/client.ts
490
+ var StoreClient;
491
+ var init_client = __esm({
492
+ "src/domain/store/client.ts"() {
493
+ "use strict";
494
+ StoreClient = class {
495
+ };
496
+ }
497
+ });
498
+
499
+ // src/domain/store/index.ts
500
+ var init_store = __esm({
501
+ "src/domain/store/index.ts"() {
502
+ "use strict";
503
+ init_adapter();
504
+ init_client();
505
+ }
506
+ });
507
+
508
+ // src/domain/ui/types.ts
509
+ var Modal;
510
+ var init_types = __esm({
511
+ "src/domain/ui/types.ts"() {
512
+ "use strict";
513
+ Modal = class {
514
+ // eslint-disable-next-line @typescript-eslint/parameter-properties
515
+ constructor(options) {
516
+ this.options = options;
517
+ }
518
+ get isMounted() {
519
+ return this.instance !== void 0;
520
+ }
521
+ get data() {
522
+ if (typeof this.options === "object" && this.options && "link" in this.options) {
523
+ return this.options.link;
524
+ }
525
+ if (typeof this.options === "object" && this.options && "otpCode" in this.options) {
526
+ return this.options.otpCode;
527
+ }
528
+ throw new Error("Invalid options");
529
+ }
530
+ set data(data) {
531
+ if (typeof this.options === "object" && this.options && "link" in this.options) {
532
+ this.options.link = data;
533
+ }
534
+ if (typeof this.options === "object" && this.options && "otpCode" in this.options) {
535
+ this.options.otpCode = data;
536
+ }
537
+ }
538
+ };
539
+ }
540
+ });
541
+
542
+ // src/domain/ui/index.ts
543
+ var init_ui = __esm({
544
+ "src/domain/ui/index.ts"() {
545
+ "use strict";
546
+ init_types();
547
+ }
548
+ });
549
+
550
+ // src/domain/utils/index.ts
551
+ function getVersion() {
552
+ return "0.0.0";
553
+ }
554
+ var init_utils = __esm({
555
+ "src/domain/utils/index.ts"() {
556
+ "use strict";
557
+ }
558
+ });
559
+
560
+ // src/domain/index.ts
561
+ var init_domain = __esm({
562
+ "src/domain/index.ts"() {
563
+ "use strict";
564
+ init_errors();
565
+ init_events();
566
+ init_logger();
567
+ init_multichain();
568
+ init_platform();
569
+ init_store();
570
+ init_ui();
571
+ init_utils();
572
+ }
573
+ });
574
+
575
+ // src/ui/qr.ts
576
+ function preloadQR() {
577
+ return __async(this, null, function* () {
578
+ if (encodeQRImpl) {
579
+ return;
580
+ }
581
+ const mod = yield import("@paulmillr/qr");
582
+ encodeQRImpl = mod.default;
583
+ });
584
+ }
585
+ function encodeQRSync(input) {
586
+ if (!encodeQRImpl) {
587
+ throw new Error("QR module not preloaded. Call preloadQR() first.");
588
+ }
589
+ return encodeQRImpl(input, "ascii");
590
+ }
591
+ var encodeQRImpl;
592
+ var init_qr = __esm({
593
+ "src/ui/qr.ts"() {
594
+ "use strict";
595
+ encodeQRImpl = null;
596
+ }
597
+ });
598
+
599
+ // src/ui/modals/base/utils.ts
600
+ function formatRemainingTime(milliseconds) {
601
+ if (milliseconds <= 0) return "EXPIRED";
602
+ const seconds = Math.floor(milliseconds / 1e3);
603
+ return `${seconds}s`;
604
+ }
605
+ function shouldLogCountdown(remainingSeconds) {
606
+ if (remainingSeconds <= 10) {
607
+ return true;
608
+ } else if (remainingSeconds <= 30) {
609
+ return remainingSeconds % 5 === 0;
610
+ } else if (remainingSeconds <= 60) {
611
+ return remainingSeconds % 10 === 0;
612
+ } else if (remainingSeconds <= 300) {
613
+ return remainingSeconds % 30 === 0;
614
+ } else {
615
+ return remainingSeconds % 60 === 0;
616
+ }
617
+ }
618
+ var init_utils2 = __esm({
619
+ "src/ui/modals/base/utils.ts"() {
620
+ "use strict";
621
+ }
622
+ });
623
+
624
+ // src/ui/modals/base/AbstractInstallModal.ts
625
+ var logger3, AbstractInstallModal;
626
+ var init_AbstractInstallModal = __esm({
627
+ "src/ui/modals/base/AbstractInstallModal.ts"() {
628
+ "use strict";
629
+ init_domain();
630
+ init_utils2();
631
+ logger3 = createLogger("metamask-sdk:ui");
632
+ AbstractInstallModal = class extends Modal {
633
+ constructor() {
634
+ super(...arguments);
635
+ this.expirationInterval = null;
636
+ this.lastLoggedCountdown = -1;
637
+ }
638
+ get link() {
639
+ return this.data;
640
+ }
641
+ set link(link) {
642
+ this.data = link;
643
+ }
644
+ get connectionRequest() {
645
+ return this.options.connectionRequest;
646
+ }
647
+ set connectionRequest(connectionRequest) {
648
+ this.options.connectionRequest = connectionRequest;
649
+ }
650
+ updateLink(link) {
651
+ this.link = link;
652
+ if (this.instance) {
653
+ this.instance.link = link;
654
+ }
655
+ }
656
+ updateExpiresIn(expiresIn) {
657
+ if (expiresIn >= 0 && this.instance) {
658
+ this.instance.expiresIn = expiresIn;
659
+ }
660
+ }
661
+ startExpirationCheck(connectionRequest) {
662
+ this.stopExpirationCheck();
663
+ let currentConnectionRequest = connectionRequest;
664
+ this.expirationInterval = setInterval(() => __async(this, null, function* () {
665
+ const { sessionRequest } = currentConnectionRequest;
666
+ const now = Date.now();
667
+ const remainingMs = sessionRequest.expiresAt - now;
668
+ const remainingSeconds = Math.floor(remainingMs / 1e3);
669
+ if (remainingMs > 0 && shouldLogCountdown(remainingSeconds) && this.lastLoggedCountdown !== remainingSeconds) {
670
+ const formattedTime = formatRemainingTime(remainingMs);
671
+ logger3(
672
+ `[UI: InstallModal-nodejs()] QR code expires in: ${formattedTime} (${remainingSeconds}s)`
673
+ );
674
+ this.lastLoggedCountdown = remainingSeconds;
675
+ }
676
+ if (now >= sessionRequest.expiresAt) {
677
+ this.stopExpirationCheck();
678
+ logger3(
679
+ "[UI: InstallModal-nodejs()] \u23F0 QR code EXPIRED! Generating new one..."
680
+ );
681
+ try {
682
+ currentConnectionRequest = yield this.options.createConnectionRequest();
683
+ const generateQRCode = yield this.options.generateQRCode(
684
+ currentConnectionRequest
685
+ );
686
+ this.lastLoggedCountdown = -1;
687
+ this.updateLink(generateQRCode);
688
+ this.updateExpiresIn(remainingSeconds);
689
+ this.renderQRCode(generateQRCode, currentConnectionRequest);
690
+ } catch (error) {
691
+ logger3(
692
+ `[UI: InstallModal-nodejs()] \u274C Error generating new QR code: ${error}`
693
+ );
694
+ }
695
+ } else {
696
+ const generateQRCode = yield this.options.generateQRCode(
697
+ currentConnectionRequest
698
+ );
699
+ this.renderQRCode(generateQRCode, currentConnectionRequest);
700
+ }
701
+ }), 1e3);
702
+ }
703
+ stopExpirationCheck() {
704
+ if (this.expirationInterval) {
705
+ clearInterval(this.expirationInterval);
706
+ this.expirationInterval = null;
707
+ logger3(
708
+ "[UI: InstallModal-nodejs()] \u{1F6D1} Stopped QR code expiration checking"
709
+ );
710
+ }
711
+ }
712
+ };
713
+ }
714
+ });
715
+
716
+ // src/ui/modals/node/install.ts
717
+ var logger4, InstallModal;
718
+ var init_install = __esm({
719
+ "src/ui/modals/node/install.ts"() {
720
+ "use strict";
721
+ init_domain();
722
+ init_qr();
723
+ init_AbstractInstallModal();
724
+ init_utils2();
725
+ logger4 = createLogger("metamask-sdk:ui");
726
+ InstallModal = class extends AbstractInstallModal {
727
+ displayQRWithCountdown(qrCodeLink, expiresInMs) {
728
+ const isExpired = expiresInMs <= 0;
729
+ const formattedTime = formatRemainingTime(expiresInMs);
730
+ const qrCode = encodeQRSync(qrCodeLink);
731
+ console.clear();
732
+ console.log(qrCode);
733
+ if (isExpired) {
734
+ console.log("EXPIRED - Generating new QR code...");
735
+ } else {
736
+ console.log(`EXPIRES IN: ${formattedTime}`);
737
+ }
738
+ }
739
+ renderQRCode(link, connectionRequest) {
740
+ const { sessionRequest } = connectionRequest;
741
+ const expiresIn = sessionRequest.expiresAt - Date.now();
742
+ const expiresInSeconds = Math.floor(expiresIn / 1e3);
743
+ const shouldLog = shouldLogCountdown(expiresInSeconds);
744
+ const formattedTime = formatRemainingTime(expiresIn);
745
+ this.startExpirationCheck(connectionRequest);
746
+ this.displayQRWithCountdown(link, expiresIn);
747
+ if (shouldLog) {
748
+ logger4(
749
+ `[UI: InstallModal-nodejs()] QR code expires in: ${formattedTime} (${expiresIn}ms)`
750
+ );
751
+ }
752
+ }
753
+ mount() {
754
+ if (!this.link) {
755
+ throw new Error("Session request is required");
756
+ }
757
+ const { link, connectionRequest } = this;
758
+ this.renderQRCode(link, connectionRequest);
759
+ }
760
+ unmount() {
761
+ console.clear();
762
+ this.stopExpirationCheck();
763
+ }
764
+ };
765
+ }
766
+ });
767
+
768
+ // src/ui/modals/base/AbstractOTPModal.ts
769
+ var AbstractOTPCodeModal;
770
+ var init_AbstractOTPModal = __esm({
771
+ "src/ui/modals/base/AbstractOTPModal.ts"() {
772
+ "use strict";
773
+ init_domain();
774
+ AbstractOTPCodeModal = class extends Modal {
775
+ get otpCode() {
776
+ return this.data;
777
+ }
778
+ set otpCode(code) {
779
+ this.data = code;
780
+ }
781
+ updateOTPCode(code) {
782
+ this.otpCode = code;
783
+ if (this.instance) {
784
+ this.instance.otpCode = code;
785
+ }
786
+ }
787
+ };
788
+ }
789
+ });
790
+
791
+ // src/ui/modals/node/otp.ts
792
+ var OTPCodeModal;
793
+ var init_otp = __esm({
794
+ "src/ui/modals/node/otp.ts"() {
795
+ "use strict";
796
+ init_AbstractOTPModal();
797
+ OTPCodeModal = class extends AbstractOTPCodeModal {
798
+ mount() {
799
+ }
800
+ unmount() {
801
+ }
802
+ };
803
+ }
804
+ });
805
+
806
+ // src/ui/modals/node/index.ts
807
+ var node_exports = {};
808
+ __export(node_exports, {
809
+ InstallModal: () => InstallModal,
810
+ OTPCodeModal: () => OTPCodeModal
811
+ });
812
+ var init_node = __esm({
813
+ "src/ui/modals/node/index.ts"() {
814
+ "use strict";
815
+ init_install();
816
+ init_otp();
817
+ }
818
+ });
819
+
820
+ // src/store/adapters/node.ts
821
+ var node_exports2 = {};
822
+ __export(node_exports2, {
823
+ StoreAdapterNode: () => StoreAdapterNode
824
+ });
825
+ var StoreAdapterNode;
826
+ var init_node2 = __esm({
827
+ "src/store/adapters/node.ts"() {
828
+ "use strict";
829
+ init_domain();
830
+ StoreAdapterNode = class extends StoreAdapter {
831
+ constructor() {
832
+ super(...arguments);
833
+ this.platform = "node";
834
+ this.storage = /* @__PURE__ */ new Map();
835
+ }
836
+ get(key) {
837
+ return __async(this, null, function* () {
838
+ var _a;
839
+ return (_a = this.storage.get(key)) != null ? _a : null;
840
+ });
841
+ }
842
+ set(key, value) {
843
+ return __async(this, null, function* () {
844
+ this.storage.set(key, value);
845
+ });
846
+ }
847
+ delete(key) {
848
+ return __async(this, null, function* () {
849
+ this.storage.delete(key);
850
+ });
851
+ }
852
+ };
853
+ }
854
+ });
855
+
856
+ // src/multichain/index.ts
857
+ import { analytics } from "@metamask/analytics";
858
+ import {
859
+ ErrorCode,
860
+ ProtocolError,
861
+ SessionStore as SessionStore2,
862
+ WebSocketTransport
863
+ } from "@metamask/mobile-wallet-protocol-core";
864
+ import { DappClient } from "@metamask/mobile-wallet-protocol-dapp-client";
865
+ import {
866
+ getMultichainClient
867
+ } from "@metamask/multichain-api-client";
868
+
869
+ // src/config/index.ts
870
+ var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
871
+ var METAMASK_CONNECT_BASE_URL = "https://metamask.app.link/connect";
872
+ var METAMASK_DEEPLINK_BASE = "metamask://connect";
873
+
874
+ // src/multichain/index.ts
875
+ init_domain();
876
+ init_logger();
877
+ init_multichain();
878
+ init_platform();
879
+
880
+ // src/multichain/rpc/requestRouter.ts
881
+ init_domain();
882
+
883
+ // src/multichain/utils/index.ts
884
+ init_domain();
885
+ import { deflate } from "pako";
886
+ import {
887
+ parseCaipAccountId,
888
+ parseCaipChainId
889
+ } from "@metamask/utils";
890
+ function base64Encode(str) {
891
+ if (typeof btoa !== "undefined") {
892
+ return btoa(str);
893
+ } else if (typeof Buffer !== "undefined") {
894
+ return Buffer.from(str).toString("base64");
895
+ }
896
+ throw new Error("No base64 encoding method available");
897
+ }
898
+ function compressString(str) {
899
+ const compressed = deflate(str);
900
+ const binaryString = String.fromCharCode.apply(null, Array.from(compressed));
901
+ return base64Encode(binaryString);
902
+ }
903
+ function getDappId(dapp) {
904
+ var _a, _b;
905
+ if (typeof window === "undefined" || typeof window.location === "undefined") {
906
+ return (_b = (_a = dapp == null ? void 0 : dapp.name) != null ? _a : dapp == null ? void 0 : dapp.url) != null ? _b : "N/A";
907
+ }
908
+ return window.location.hostname;
909
+ }
910
+ function openDeeplink(options, deeplink, universalLink) {
911
+ const { mobile } = options;
912
+ const useDeeplink = mobile && mobile.useDeeplink !== void 0 ? mobile.useDeeplink : true;
913
+ if (useDeeplink) {
914
+ if (typeof window !== "undefined") {
915
+ window.location.href = deeplink;
916
+ }
917
+ } else if (typeof document !== "undefined") {
918
+ const link = document.createElement("a");
919
+ link.href = universalLink;
920
+ link.target = "_self";
921
+ link.rel = "noreferrer noopener";
922
+ link.click();
923
+ }
924
+ }
925
+ function getOptionalScopes(scopes) {
926
+ return scopes.reduce(
927
+ (prev, scope) => __spreadProps(__spreadValues({}, prev), {
928
+ [scope]: {
929
+ methods: [],
930
+ notifications: [],
931
+ accounts: []
932
+ }
933
+ }),
934
+ {}
935
+ );
936
+ }
937
+ var extractFavicon = () => {
938
+ var _a;
939
+ if (typeof document === "undefined") {
940
+ return void 0;
941
+ }
942
+ let favicon;
943
+ const nodeList = document.getElementsByTagName("link");
944
+ for (let i = 0; i < nodeList.length; i++) {
945
+ if (nodeList[i].getAttribute("rel") === "icon" || nodeList[i].getAttribute("rel") === "shortcut icon") {
946
+ favicon = (_a = nodeList[i].getAttribute("href")) != null ? _a : void 0;
947
+ }
948
+ }
949
+ return favicon;
950
+ };
951
+ function setupInfuraProvider(options) {
952
+ var _a, _b;
953
+ const infuraAPIKey = (_a = options.api) == null ? void 0 : _a.infuraAPIKey;
954
+ if (!infuraAPIKey) {
955
+ return options;
956
+ }
957
+ const urlsWithToken = getInfuraRpcUrls(infuraAPIKey);
958
+ if ((_b = options.api) == null ? void 0 : _b.readonlyRPCMap) {
959
+ options.api.readonlyRPCMap = __spreadValues(__spreadValues({}, options.api.readonlyRPCMap), urlsWithToken);
960
+ } else if (options.api) {
961
+ options.api.readonlyRPCMap = urlsWithToken;
962
+ }
963
+ return options;
964
+ }
965
+ function setupDappMetadata(options) {
966
+ var _a;
967
+ const platform = getPlatformType();
968
+ const isBrowser = platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */ || platform === "in-app-browser" /* MetaMaskMobileWebview */;
969
+ if (!((_a = options.dapp) == null ? void 0 : _a.url)) {
970
+ if (isBrowser) {
971
+ options.dapp = __spreadProps(__spreadValues({}, options.dapp), {
972
+ url: `${window.location.protocol}//${window.location.host}`
973
+ });
974
+ } else {
975
+ throw new Error("You must provide dapp url");
976
+ }
977
+ }
978
+ const BASE_64_ICON_MAX_LENGTH = 163400;
979
+ const urlPattern = /^(http|https):\/\/[^\s]*$/;
980
+ if (options.dapp) {
981
+ if ("iconUrl" in options.dapp) {
982
+ if (options.dapp.iconUrl && !urlPattern.test(options.dapp.iconUrl)) {
983
+ console.warn(
984
+ "Invalid dappMetadata.iconUrl: URL must start with http:// or https://"
985
+ );
986
+ options.dapp.iconUrl = void 0;
987
+ }
988
+ }
989
+ if ("base64Icon" in options.dapp) {
990
+ if (options.dapp.base64Icon && options.dapp.base64Icon.length > BASE_64_ICON_MAX_LENGTH) {
991
+ console.warn(
992
+ "Invalid dappMetadata.base64Icon: Base64-encoded icon string length must be less than 163400 characters"
993
+ );
994
+ options.dapp.base64Icon = void 0;
995
+ }
996
+ }
997
+ if (options.dapp.url && !urlPattern.test(options.dapp.url)) {
998
+ console.warn(
999
+ "Invalid dappMetadata.url: URL must start with http:// or https://"
1000
+ );
1001
+ }
1002
+ const favicon = extractFavicon();
1003
+ if (favicon && !("iconUrl" in options.dapp) && !("base64Icon" in options.dapp)) {
1004
+ const faviconUrl = `${window.location.protocol}//${window.location.host}${favicon}`;
1005
+ options.dapp.iconUrl = faviconUrl;
1006
+ }
1007
+ }
1008
+ return options;
1009
+ }
1010
+ function isSameScopesAndAccounts(currentScopes, proposedScopes, walletSession, proposedCaipAccountIds) {
1011
+ const isSameScopes = currentScopes.every((scope) => proposedScopes.includes(scope)) && proposedScopes.every((scope) => currentScopes.includes(scope));
1012
+ if (!isSameScopes) {
1013
+ return false;
1014
+ }
1015
+ const existingAccountIds = Object.values(
1016
+ walletSession.sessionScopes
1017
+ ).filter(({ accounts }) => Boolean(accounts)).flatMap(({ accounts }) => accounts != null ? accounts : []);
1018
+ const allProposedAccountsIncluded = proposedCaipAccountIds.every(
1019
+ (proposedAccountId) => existingAccountIds.includes(proposedAccountId)
1020
+ );
1021
+ return allProposedAccountsIncluded;
1022
+ }
1023
+ function getValidAccounts(caipAccountIds) {
1024
+ return caipAccountIds.reduce(
1025
+ (caipAccounts, caipAccountId) => {
1026
+ try {
1027
+ return [...caipAccounts, parseCaipAccountId(caipAccountId)];
1028
+ } catch (err) {
1029
+ const stringifiedAccountId = JSON.stringify(caipAccountId);
1030
+ console.error(`Invalid CAIP account ID: ${stringifiedAccountId}`, err);
1031
+ return caipAccounts;
1032
+ }
1033
+ },
1034
+ []
1035
+ );
1036
+ }
1037
+ function addValidAccounts(optionalScopes, validAccounts) {
1038
+ var _a;
1039
+ if (!optionalScopes || !(validAccounts == null ? void 0 : validAccounts.length)) {
1040
+ return optionalScopes;
1041
+ }
1042
+ const result = Object.fromEntries(
1043
+ Object.entries(optionalScopes).map(([scope, scopeData]) => {
1044
+ var _a2, _b, _c;
1045
+ return [
1046
+ scope,
1047
+ {
1048
+ methods: [...(_a2 = scopeData == null ? void 0 : scopeData.methods) != null ? _a2 : []],
1049
+ notifications: [...(_b = scopeData == null ? void 0 : scopeData.notifications) != null ? _b : []],
1050
+ accounts: [...(_c = scopeData == null ? void 0 : scopeData.accounts) != null ? _c : []]
1051
+ }
1052
+ ];
1053
+ })
1054
+ );
1055
+ const accountsByChain = /* @__PURE__ */ new Map();
1056
+ for (const account of validAccounts) {
1057
+ const chainKey = `${account.chain.namespace}:${account.chain.reference}`;
1058
+ const accountId = `${account.chainId}:${account.address}`;
1059
+ if (!accountsByChain.has(chainKey)) {
1060
+ accountsByChain.set(chainKey, []);
1061
+ }
1062
+ (_a = accountsByChain.get(chainKey)) == null ? void 0 : _a.push(accountId);
1063
+ }
1064
+ for (const [scopeKey, scopeData] of Object.entries(result)) {
1065
+ if (!(scopeData == null ? void 0 : scopeData.accounts)) {
1066
+ continue;
1067
+ }
1068
+ try {
1069
+ const scope = scopeKey;
1070
+ const scopeDetails = parseCaipChainId(scope);
1071
+ const chainKey = `${scopeDetails.namespace}:${scopeDetails.reference}`;
1072
+ const matchingAccounts = accountsByChain.get(chainKey);
1073
+ if (matchingAccounts) {
1074
+ const existingAccounts = new Set(scopeData.accounts);
1075
+ const newAccounts = matchingAccounts.filter(
1076
+ (account) => !existingAccounts.has(account)
1077
+ );
1078
+ scopeData.accounts.push(...newAccounts);
1079
+ }
1080
+ } catch (error) {
1081
+ console.error(`Invalid scope format: ${scopeKey}`, error);
1082
+ }
1083
+ }
1084
+ return result;
1085
+ }
1086
+
1087
+ // src/multichain/rpc/handlers/rpcClient.ts
1088
+ init_domain();
1089
+ import fetch from "cross-fetch";
1090
+ var rpcId = 1;
1091
+ function getNextRpcId() {
1092
+ rpcId += 1;
1093
+ return rpcId;
1094
+ }
1095
+ var MissingRpcEndpointErr = class extends Error {
1096
+ };
1097
+ var RpcClient = class {
1098
+ constructor(config, sdkInfo) {
1099
+ this.config = config;
1100
+ this.sdkInfo = sdkInfo;
1101
+ }
1102
+ /**
1103
+ * Routes the request to a configured RPC node.
1104
+ */
1105
+ request(options) {
1106
+ return __async(this, null, function* () {
1107
+ const { request } = options;
1108
+ const body = JSON.stringify({
1109
+ jsonrpc: "2.0",
1110
+ method: request.method,
1111
+ params: request.params,
1112
+ id: getNextRpcId()
1113
+ });
1114
+ const rpcEndpoint = this.getRpcEndpoint(options.scope);
1115
+ const rpcRequest = yield this.fetch(rpcEndpoint, body, "POST", this.getHeaders(rpcEndpoint));
1116
+ const response = yield this.parseResponse(rpcRequest);
1117
+ return response;
1118
+ });
1119
+ }
1120
+ getRpcEndpoint(scope) {
1121
+ var _a, _b, _c, _d, _e;
1122
+ let infuraAPIKey = (_b = (_a = this.config) == null ? void 0 : _a.api) == null ? void 0 : _b.infuraAPIKey;
1123
+ let readonlyRPCMap = (_e = (_d = (_c = this.config) == null ? void 0 : _c.api) == null ? void 0 : _d.readonlyRPCMap) != null ? _e : {};
1124
+ if (infuraAPIKey) {
1125
+ const urlsWithToken = getInfuraRpcUrls(infuraAPIKey);
1126
+ if (readonlyRPCMap) {
1127
+ readonlyRPCMap = __spreadValues(__spreadValues({}, urlsWithToken), readonlyRPCMap);
1128
+ } else {
1129
+ readonlyRPCMap = urlsWithToken;
1130
+ }
1131
+ }
1132
+ const rpcEndpoint = readonlyRPCMap[scope];
1133
+ if (!rpcEndpoint) {
1134
+ throw new MissingRpcEndpointErr(`No RPC endpoint found for scope ${scope}`);
1135
+ }
1136
+ return rpcEndpoint;
1137
+ }
1138
+ fetch(endpoint, body, method, headers) {
1139
+ return __async(this, null, function* () {
1140
+ try {
1141
+ const response = yield fetch(endpoint, {
1142
+ method,
1143
+ headers,
1144
+ body
1145
+ });
1146
+ if (!response.ok) {
1147
+ throw new RPCHttpErr(endpoint, method, response.status);
1148
+ }
1149
+ return response;
1150
+ } catch (error) {
1151
+ if (error instanceof RPCHttpErr) {
1152
+ throw error;
1153
+ }
1154
+ throw new RPCReadonlyRequestErr(error.message);
1155
+ }
1156
+ });
1157
+ }
1158
+ parseResponse(response) {
1159
+ return __async(this, null, function* () {
1160
+ try {
1161
+ const rpcResponse = yield response.json();
1162
+ return rpcResponse.result;
1163
+ } catch (error) {
1164
+ throw new RPCReadonlyResponseErr(error.message);
1165
+ }
1166
+ });
1167
+ }
1168
+ getHeaders(rpcEndpoint) {
1169
+ const defaultHeaders = {
1170
+ Accept: "application/json",
1171
+ "Content-Type": "application/json"
1172
+ };
1173
+ if (rpcEndpoint.includes("infura")) {
1174
+ return __spreadProps(__spreadValues({}, defaultHeaders), {
1175
+ "Metamask-Sdk-Info": this.sdkInfo
1176
+ });
1177
+ }
1178
+ return defaultHeaders;
1179
+ }
1180
+ };
1181
+
1182
+ // src/multichain/rpc/requestRouter.ts
1183
+ var RequestRouter = class {
1184
+ constructor(transport, rpcClient, config) {
1185
+ this.transport = transport;
1186
+ this.rpcClient = rpcClient;
1187
+ this.config = config;
1188
+ }
1189
+ /**
1190
+ * The main entry point for invoking an RPC method.
1191
+ * This method acts as a router, determining the correct handling strategy
1192
+ * for the request and delegating to the appropriate private handler.
1193
+ */
1194
+ invokeMethod(options) {
1195
+ return __async(this, null, function* () {
1196
+ const method = options.request.method;
1197
+ if (RPC_HANDLED_METHODS.has(method)) {
1198
+ return this.handleWithRpcNode(options);
1199
+ }
1200
+ if (SDK_HANDLED_METHODS.has(method)) {
1201
+ return this.handleWithSdkState(options);
1202
+ }
1203
+ return this.handleWithWallet(options);
1204
+ });
1205
+ }
1206
+ /**
1207
+ * Forwards the request directly to the wallet via the transport.
1208
+ */
1209
+ handleWithWallet(options) {
1210
+ return __async(this, null, function* () {
1211
+ try {
1212
+ const request = this.transport.request({
1213
+ method: "wallet_invokeMethod",
1214
+ params: options
1215
+ });
1216
+ const { ui, mobile } = this.config;
1217
+ const { preferDesktop = false } = ui != null ? ui : {};
1218
+ const secure = isSecure();
1219
+ const shouldOpenDeeplink = secure && !preferDesktop;
1220
+ if (shouldOpenDeeplink) {
1221
+ setTimeout(() => {
1222
+ if (mobile == null ? void 0 : mobile.preferredOpenLink) {
1223
+ mobile.preferredOpenLink(METAMASK_DEEPLINK_BASE, "_self");
1224
+ } else {
1225
+ openDeeplink(this.config, METAMASK_DEEPLINK_BASE, METAMASK_CONNECT_BASE_URL);
1226
+ }
1227
+ }, 10);
1228
+ }
1229
+ const response = yield request;
1230
+ if (response.error) {
1231
+ throw new RPCInvokeMethodErr(`RPC Request failed with code ${response.error.code}: ${response.error.message}`);
1232
+ }
1233
+ return response.result;
1234
+ } catch (error) {
1235
+ throw new RPCInvokeMethodErr(error.message);
1236
+ }
1237
+ });
1238
+ }
1239
+ /**
1240
+ * Routes the request to a configured RPC node.
1241
+ */
1242
+ handleWithRpcNode(options) {
1243
+ return __async(this, null, function* () {
1244
+ try {
1245
+ return yield this.rpcClient.request(options);
1246
+ } catch (error) {
1247
+ if (error instanceof MissingRpcEndpointErr) {
1248
+ return this.handleWithWallet(options);
1249
+ }
1250
+ throw error;
1251
+ }
1252
+ });
1253
+ }
1254
+ /**
1255
+ * Responds directly from the SDK's session state.
1256
+ */
1257
+ handleWithSdkState(options) {
1258
+ return __async(this, null, function* () {
1259
+ console.warn(`Method "${options.request.method}" is configured for SDK state handling, but this is not yet implemented. Falling back to wallet passthrough.`);
1260
+ return this.handleWithWallet(options);
1261
+ });
1262
+ }
1263
+ };
1264
+
1265
+ // src/multichain/transports/default/index.ts
1266
+ import {
1267
+ getDefaultTransport
1268
+ } from "@metamask/multichain-api-client";
1269
+ var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
1270
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _DefaultTransport_instances, notifyCallbacks_fn;
1271
+ var DefaultTransport = class {
1272
+ constructor() {
1273
+ __privateAdd(this, _DefaultTransport_instances);
1274
+ __privateAdd(this, _notificationCallbacks, /* @__PURE__ */ new Set());
1275
+ __privateAdd(this, _transport, getDefaultTransport());
1276
+ __privateAdd(this, _defaultRequestOptions, {
1277
+ timeout: DEFAULT_REQUEST_TIMEOUT
1278
+ });
1279
+ }
1280
+ connect(options) {
1281
+ return __async(this, null, function* () {
1282
+ var _a, _b, _c, _d, _e, _f, _g;
1283
+ yield __privateGet(this, _transport).connect();
1284
+ const sessionRequest = yield this.request(
1285
+ { method: "wallet_getSession" },
1286
+ __privateGet(this, _defaultRequestOptions)
1287
+ );
1288
+ if (sessionRequest.error) {
1289
+ throw new Error(sessionRequest.error.message);
1290
+ }
1291
+ let walletSession = sessionRequest.result;
1292
+ if (walletSession && options) {
1293
+ const currentScopes = Object.keys(
1294
+ (_a = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a : {}
1295
+ );
1296
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1297
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1298
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1299
+ currentScopes,
1300
+ proposedScopes,
1301
+ walletSession,
1302
+ proposedCaipAccountIds
1303
+ );
1304
+ if (!hasSameScopesAndAccounts) {
1305
+ yield this.request(
1306
+ { method: "wallet_revokeSession", params: walletSession },
1307
+ __privateGet(this, _defaultRequestOptions)
1308
+ );
1309
+ const optionalScopes = addValidAccounts(
1310
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1311
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1312
+ );
1313
+ const sessionRequest2 = { optionalScopes };
1314
+ const response = yield this.request(
1315
+ { method: "wallet_createSession", params: sessionRequest2 },
1316
+ __privateGet(this, _defaultRequestOptions)
1317
+ );
1318
+ if (response.error) {
1319
+ throw new Error(response.error.message);
1320
+ }
1321
+ walletSession = response.result;
1322
+ }
1323
+ } else if (!walletSession) {
1324
+ const optionalScopes = addValidAccounts(
1325
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1326
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1327
+ );
1328
+ const sessionRequest2 = { optionalScopes };
1329
+ const response = yield this.request(
1330
+ { method: "wallet_createSession", params: sessionRequest2 },
1331
+ __privateGet(this, _defaultRequestOptions)
1332
+ );
1333
+ if (response.error) {
1334
+ throw new Error(response.error.message);
1335
+ }
1336
+ walletSession = response.result;
1337
+ }
1338
+ __privateMethod(this, _DefaultTransport_instances, notifyCallbacks_fn).call(this, {
1339
+ method: "wallet_sessionChanged",
1340
+ params: walletSession
1341
+ });
1342
+ });
1343
+ }
1344
+ disconnect() {
1345
+ return __async(this, null, function* () {
1346
+ __privateGet(this, _notificationCallbacks).clear();
1347
+ return __privateGet(this, _transport).disconnect();
1348
+ });
1349
+ }
1350
+ isConnected() {
1351
+ return __privateGet(this, _transport).isConnected();
1352
+ }
1353
+ request(_0) {
1354
+ return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
1355
+ return __privateGet(this, _transport).request(request, options);
1356
+ });
1357
+ }
1358
+ onNotification(callback) {
1359
+ __privateGet(this, _transport).onNotification(callback);
1360
+ __privateGet(this, _notificationCallbacks).add(callback);
1361
+ return () => {
1362
+ __privateGet(this, _notificationCallbacks).delete(callback);
1363
+ };
1364
+ }
1365
+ };
1366
+ _notificationCallbacks = new WeakMap();
1367
+ _transport = new WeakMap();
1368
+ _defaultRequestOptions = new WeakMap();
1369
+ _DefaultTransport_instances = new WeakSet();
1370
+ notifyCallbacks_fn = function(data) {
1371
+ for (const cb of __privateGet(this, _notificationCallbacks)) {
1372
+ try {
1373
+ cb(data);
1374
+ } catch (err) {
1375
+ console.log("[WindowPostMessageTransport] notifyCallbacks error:", err);
1376
+ }
1377
+ }
1378
+ };
1379
+
1380
+ // src/multichain/transports/mwp/index.ts
1381
+ init_domain();
1382
+ import { SessionStore } from "@metamask/mobile-wallet-protocol-core";
1383
+ import {
1384
+ TransportTimeoutError
1385
+ } from "@metamask/multichain-api-client";
1386
+ var DEFAULT_REQUEST_TIMEOUT2 = 60 * 1e3;
1387
+ var CONNECTION_GRACE_PERIOD = 60 * 1e3;
1388
+ var DEFAULT_CONNECTION_TIMEOUT = DEFAULT_REQUEST_TIMEOUT2 + CONNECTION_GRACE_PERIOD;
1389
+ var SESSION_STORE_KEY = "cache_wallet_getSession";
1390
+ var CACHED_METHOD_LIST = [
1391
+ "wallet_getSession",
1392
+ "wallet_createSession",
1393
+ "wallet_sessionChanged"
1394
+ ];
1395
+ var CACHED_RESET_METHOD_LIST = ["wallet_revokeSession"];
1396
+ var logger = createLogger("metamask-sdk:transport");
1397
+ var MWPTransport = class {
1398
+ constructor(dappClient, kvstore, options = {
1399
+ requestTimeout: DEFAULT_REQUEST_TIMEOUT2,
1400
+ connectionTimeout: DEFAULT_CONNECTION_TIMEOUT
1401
+ }) {
1402
+ this.dappClient = dappClient;
1403
+ this.kvstore = kvstore;
1404
+ this.options = options;
1405
+ this.__reqId = 0;
1406
+ this.__pendingRequests = /* @__PURE__ */ new Map();
1407
+ this.notificationCallbacks = /* @__PURE__ */ new Set();
1408
+ this.dappClient.on("message", this.handleMessage.bind(this));
1409
+ if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1410
+ this.windowFocusHandler = this.onWindowFocus.bind(this);
1411
+ window.addEventListener("focus", this.windowFocusHandler);
1412
+ }
1413
+ }
1414
+ get pendingRequests() {
1415
+ return this.__pendingRequests;
1416
+ }
1417
+ set pendingRequests(pendingRequests) {
1418
+ this.__pendingRequests = pendingRequests;
1419
+ }
1420
+ get sessionRequest() {
1421
+ return this.currentSessionRequest;
1422
+ }
1423
+ onWindowFocus() {
1424
+ if (!this.isConnected()) {
1425
+ this.dappClient.reconnect();
1426
+ }
1427
+ }
1428
+ notifyCallbacks(data) {
1429
+ this.notificationCallbacks.forEach((callback) => callback(data));
1430
+ }
1431
+ rejectRequest(id, error = new Error("Request rejected")) {
1432
+ const request = this.pendingRequests.get(id);
1433
+ if (request) {
1434
+ this.pendingRequests.delete(id);
1435
+ clearTimeout(request.timeout);
1436
+ request.reject(error);
1437
+ }
1438
+ }
1439
+ handleMessage(message) {
1440
+ if (typeof message === "object" && message !== null) {
1441
+ if ("data" in message) {
1442
+ const messagePayload = message.data;
1443
+ if ("id" in messagePayload && typeof messagePayload.id === "string") {
1444
+ const request = this.pendingRequests.get(messagePayload.id);
1445
+ if (request) {
1446
+ const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
1447
+ method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
1448
+ });
1449
+ const notification = __spreadProps(__spreadValues({}, messagePayload), {
1450
+ method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
1451
+ params: requestWithName.result
1452
+ });
1453
+ clearTimeout(request.timeout);
1454
+ this.notifyCallbacks(notification);
1455
+ request.resolve(requestWithName);
1456
+ this.pendingRequests.delete(messagePayload.id);
1457
+ }
1458
+ } else {
1459
+ this.notifyCallbacks(message.data);
1460
+ }
1461
+ }
1462
+ }
1463
+ }
1464
+ onResumeSuccess(resumeResolve, resumeReject, options) {
1465
+ return __async(this, null, function* () {
1466
+ var _a, _b, _c, _d, _e, _f, _g;
1467
+ try {
1468
+ const sessionRequest = yield this.request({
1469
+ method: "wallet_getSession"
1470
+ });
1471
+ if (sessionRequest.error) {
1472
+ return resumeReject(new Error(sessionRequest.error.message));
1473
+ }
1474
+ let walletSession = sessionRequest.result;
1475
+ if (walletSession && options) {
1476
+ const currentScopes = Object.keys(
1477
+ (_a = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a : {}
1478
+ );
1479
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1480
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1481
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1482
+ currentScopes,
1483
+ proposedScopes,
1484
+ walletSession,
1485
+ proposedCaipAccountIds
1486
+ );
1487
+ if (!hasSameScopesAndAccounts) {
1488
+ const optionalScopes = addValidAccounts(
1489
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1490
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1491
+ );
1492
+ const sessionRequest2 = {
1493
+ optionalScopes
1494
+ };
1495
+ const response = yield this.request({
1496
+ method: "wallet_createSession",
1497
+ params: sessionRequest2
1498
+ });
1499
+ if (response.error) {
1500
+ return resumeReject(new Error(response.error.message));
1501
+ }
1502
+ walletSession = response.result;
1503
+ }
1504
+ } else if (!walletSession) {
1505
+ const optionalScopes = addValidAccounts(
1506
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1507
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1508
+ );
1509
+ const sessionRequest2 = { optionalScopes };
1510
+ const response = yield this.request({
1511
+ method: "wallet_createSession",
1512
+ params: sessionRequest2
1513
+ });
1514
+ if (response.error) {
1515
+ return resumeReject(new Error(response.error.message));
1516
+ }
1517
+ walletSession = response.result;
1518
+ }
1519
+ this.notifyCallbacks({
1520
+ method: "wallet_sessionChanged",
1521
+ params: walletSession
1522
+ });
1523
+ return resumeResolve();
1524
+ } catch (err) {
1525
+ return resumeReject(err);
1526
+ }
1527
+ });
1528
+ }
1529
+ connect(options) {
1530
+ return __async(this, null, function* () {
1531
+ const { dappClient, kvstore } = this;
1532
+ const sessionStore = new SessionStore(kvstore);
1533
+ let session;
1534
+ try {
1535
+ const [activeSession] = yield sessionStore.list();
1536
+ if (activeSession) {
1537
+ logger("active session found", activeSession);
1538
+ session = activeSession;
1539
+ }
1540
+ } catch (e) {
1541
+ }
1542
+ let timeout;
1543
+ const connectionPromise = new Promise((resolve, reject) => {
1544
+ let connection;
1545
+ if (session) {
1546
+ connection = new Promise((resumeResolve, resumeReject) => {
1547
+ var _a;
1548
+ if (this.dappClient.state === "CONNECTED") {
1549
+ this.onResumeSuccess(resumeResolve, resumeReject, options);
1550
+ } else {
1551
+ this.dappClient.once("connected", () => __async(this, null, function* () {
1552
+ this.onResumeSuccess(resumeResolve, resumeReject, options);
1553
+ }));
1554
+ dappClient.resume((_a = session == null ? void 0 : session.id) != null ? _a : "");
1555
+ }
1556
+ });
1557
+ } else {
1558
+ connection = new Promise(
1559
+ (resolveConnection, rejectConnection) => {
1560
+ var _a, _b;
1561
+ const optionalScopes = addValidAccounts(
1562
+ getOptionalScopes((_a = options == null ? void 0 : options.scopes) != null ? _a : []),
1563
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1564
+ );
1565
+ const sessionRequest = {
1566
+ optionalScopes
1567
+ };
1568
+ const request = {
1569
+ jsonrpc: "2.0",
1570
+ id: `${this.__reqId++}`,
1571
+ method: "wallet_createSession",
1572
+ params: sessionRequest
1573
+ };
1574
+ this.dappClient.on("message", (message) => __async(this, null, function* () {
1575
+ if (typeof message === "object" && message !== null) {
1576
+ if ("data" in message) {
1577
+ const messagePayload = message.data;
1578
+ if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
1579
+ if (messagePayload.error) {
1580
+ return rejectConnection(messagePayload.error);
1581
+ }
1582
+ this.notifyCallbacks(message.data);
1583
+ yield this.storeWalletSession(
1584
+ request,
1585
+ messagePayload
1586
+ );
1587
+ return resolveConnection();
1588
+ }
1589
+ }
1590
+ }
1591
+ }));
1592
+ dappClient.connect({ mode: "trusted", initialPayload: request }).catch(rejectConnection);
1593
+ }
1594
+ );
1595
+ }
1596
+ timeout = setTimeout(() => {
1597
+ reject(new TransportTimeoutError());
1598
+ }, this.options.connectionTimeout);
1599
+ connection.then(resolve).catch(reject);
1600
+ });
1601
+ return connectionPromise.finally(() => {
1602
+ if (timeout) {
1603
+ clearTimeout(timeout);
1604
+ }
1605
+ });
1606
+ });
1607
+ }
1608
+ /**
1609
+ * Disconnects from the Mobile Wallet Protocol
1610
+ *
1611
+ * @returns Nothing
1612
+ */
1613
+ disconnect() {
1614
+ return __async(this, null, function* () {
1615
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
1616
+ window.removeEventListener("focus", this.windowFocusHandler);
1617
+ this.windowFocusHandler = void 0;
1618
+ }
1619
+ return this.dappClient.disconnect();
1620
+ });
1621
+ }
1622
+ /**
1623
+ * Checks if the transport is connected
1624
+ *
1625
+ * @returns True if transport is connected, false otherwise
1626
+ */
1627
+ isConnected() {
1628
+ return this.dappClient.state === "CONNECTED";
1629
+ }
1630
+ fetchCachedWalletSession(request) {
1631
+ return __async(this, null, function* () {
1632
+ var _a;
1633
+ if (request.method === "wallet_getSession") {
1634
+ const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
1635
+ if (walletGetSession) {
1636
+ const walletSession = JSON.parse(walletGetSession);
1637
+ return {
1638
+ id: request.id,
1639
+ jsonrpc: "2.0",
1640
+ result: (_a = walletSession.params) != null ? _a : walletSession.result,
1641
+ method: request.method
1642
+ };
1643
+ }
1644
+ }
1645
+ });
1646
+ }
1647
+ storeWalletSession(request, response) {
1648
+ return __async(this, null, function* () {
1649
+ if (CACHED_METHOD_LIST.includes(request.method)) {
1650
+ yield this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
1651
+ } else if (CACHED_RESET_METHOD_LIST.includes(request.method)) {
1652
+ yield this.kvstore.delete(SESSION_STORE_KEY);
1653
+ }
1654
+ });
1655
+ }
1656
+ request(payload, options) {
1657
+ return __async(this, null, function* () {
1658
+ const request = __spreadValues({
1659
+ jsonrpc: "2.0",
1660
+ id: `${this.__reqId++}`
1661
+ }, payload);
1662
+ const cachedWalletSession = yield this.fetchCachedWalletSession(request);
1663
+ if (cachedWalletSession) {
1664
+ this.notifyCallbacks(cachedWalletSession);
1665
+ return cachedWalletSession;
1666
+ }
1667
+ return new Promise((resolve, reject) => {
1668
+ var _a;
1669
+ const timeout = setTimeout(() => {
1670
+ this.rejectRequest(request.id, new TransportTimeoutError());
1671
+ }, (_a = options == null ? void 0 : options.timeout) != null ? _a : this.options.requestTimeout);
1672
+ this.pendingRequests.set(request.id, {
1673
+ request,
1674
+ method: request.method,
1675
+ resolve: (response) => __async(this, null, function* () {
1676
+ if (CACHED_METHOD_LIST.includes(request.method)) {
1677
+ yield this.storeWalletSession(request, response);
1678
+ }
1679
+ return resolve(response);
1680
+ }),
1681
+ reject,
1682
+ timeout
1683
+ });
1684
+ this.dappClient.sendRequest(request).catch(reject);
1685
+ });
1686
+ });
1687
+ }
1688
+ onNotification(callback) {
1689
+ this.notificationCallbacks.add(callback);
1690
+ return () => {
1691
+ this.notificationCallbacks.delete(callback);
1692
+ };
1693
+ }
1694
+ };
1695
+
1696
+ // src/multichain/transports/mwp/KeyManager.ts
1697
+ import { decrypt, encrypt, PrivateKey } from "eciesjs";
1698
+ var KeyManager = class {
1699
+ generateKeyPair() {
1700
+ const privateKey = new PrivateKey();
1701
+ return {
1702
+ privateKey: new Uint8Array(privateKey.secret),
1703
+ publicKey: privateKey.publicKey.toBytes(true)
1704
+ };
1705
+ }
1706
+ encrypt(plaintext, theirPublicKey) {
1707
+ return __async(this, null, function* () {
1708
+ const plaintextBuffer = Buffer.from(plaintext, "utf8");
1709
+ const encryptedBuffer = encrypt(theirPublicKey, plaintextBuffer);
1710
+ return encryptedBuffer.toString("base64");
1711
+ });
1712
+ }
1713
+ decrypt(encryptedB64, myPrivateKey) {
1714
+ return __async(this, null, function* () {
1715
+ const encryptedBuffer = Buffer.from(encryptedB64, "base64");
1716
+ const decryptedBuffer = yield decrypt(myPrivateKey, encryptedBuffer);
1717
+ return Buffer.from(decryptedBuffer).toString("utf8");
1718
+ });
1719
+ }
1720
+ };
1721
+ var keymanager = new KeyManager();
1722
+
1723
+ // src/multichain/index.ts
1724
+ var logger2 = createLogger("metamask-sdk:core");
1725
+ var MultichainSDK = class _MultichainSDK extends MultichainCore {
1726
+ constructor(options) {
1727
+ var _a, _b, _c, _d, _e, _f;
1728
+ const withInfuraRPCMethods = setupInfuraProvider(options);
1729
+ const withDappMetadata = setupDappMetadata(withInfuraRPCMethods);
1730
+ const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
1731
+ ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
1732
+ preferExtension: (_a = withDappMetadata.ui.preferExtension) != null ? _a : true,
1733
+ preferDesktop: (_b = withDappMetadata.ui.preferDesktop) != null ? _b : false,
1734
+ headless: (_c = withDappMetadata.ui.headless) != null ? _c : false
1735
+ }),
1736
+ analytics: __spreadProps(__spreadValues({}, (_d = options.analytics) != null ? _d : {}), {
1737
+ enabled: (_f = (_e = options.analytics) == null ? void 0 : _e.enabled) != null ? _f : true,
1738
+ integrationType: "unknown"
1739
+ })
1740
+ });
1741
+ super(allOptions);
1742
+ this.__provider = void 0;
1743
+ this.__transport = void 0;
1744
+ this.__dappClient = void 0;
1745
+ this.__state = "pending";
1746
+ }
1747
+ get state() {
1748
+ return this.__state;
1749
+ }
1750
+ set state(value) {
1751
+ var _a, _b;
1752
+ this.__state = value;
1753
+ (_b = (_a = this.options.transport) == null ? void 0 : _a.onNotification) == null ? void 0 : _b.call(_a, {
1754
+ method: "stateChanged",
1755
+ params: value
1756
+ });
1757
+ }
1758
+ get provider() {
1759
+ if (!this.__provider) {
1760
+ throw new Error("Provider not initialized, establish connection first");
1761
+ }
1762
+ return this.__provider;
1763
+ }
1764
+ get transport() {
1765
+ if (!this.__transport) {
1766
+ throw new Error("Transport not initialized, establish connection first");
1767
+ }
1768
+ return this.__transport;
1769
+ }
1770
+ get dappClient() {
1771
+ if (!this.__dappClient) {
1772
+ throw new Error("DappClient not initialized, establish connection first");
1773
+ }
1774
+ return this.__dappClient;
1775
+ }
1776
+ get storage() {
1777
+ return this.options.storage;
1778
+ }
1779
+ get sdkInfo() {
1780
+ var _a;
1781
+ return `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a = this.options.dapp.url) != null ? _a : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`;
1782
+ }
1783
+ static create(options) {
1784
+ return __async(this, null, function* () {
1785
+ const instance = new _MultichainSDK(options);
1786
+ const isEnabled2 = yield isEnabled(
1787
+ "metamask-sdk:core",
1788
+ instance.options.storage
1789
+ );
1790
+ if (isEnabled2) {
1791
+ enableDebug("metamask-sdk:core");
1792
+ }
1793
+ yield instance.init();
1794
+ return instance;
1795
+ });
1796
+ }
1797
+ setupAnalytics() {
1798
+ return __async(this, null, function* () {
1799
+ var _a, _b;
1800
+ if (!((_a = this.options.analytics) == null ? void 0 : _a.enabled)) {
1801
+ return;
1802
+ }
1803
+ const platform = getPlatformType();
1804
+ const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
1805
+ const isReactNative2 = platform === "react-native" /* ReactNative */;
1806
+ if (!isBrowser && !isReactNative2) {
1807
+ return;
1808
+ }
1809
+ const version = getVersion();
1810
+ const dappId = getDappId(this.options.dapp);
1811
+ const anonId = yield this.storage.getAnonId();
1812
+ const { integrationType } = (_b = this.options.analytics) != null ? _b : {
1813
+ integrationType: ""
1814
+ };
1815
+ analytics.setGlobalProperty("sdk_version", version);
1816
+ analytics.setGlobalProperty("dapp_id", dappId);
1817
+ analytics.setGlobalProperty("anon_id", anonId);
1818
+ analytics.setGlobalProperty("platform", platform);
1819
+ analytics.setGlobalProperty("integration_type", integrationType);
1820
+ analytics.enable();
1821
+ });
1822
+ }
1823
+ onTransportNotification(payload) {
1824
+ return __async(this, null, function* () {
1825
+ var _a;
1826
+ if (typeof payload === "object" && payload !== null && "method" in payload) {
1827
+ this.emit(payload.method, (_a = payload.params) != null ? _a : payload.result);
1828
+ }
1829
+ });
1830
+ }
1831
+ getStoredTransport() {
1832
+ return __async(this, null, function* () {
1833
+ const { ui } = this.options;
1834
+ const { preferExtension = true } = ui;
1835
+ const transportType = yield this.storage.getTransport();
1836
+ const hasExtensionInstalled = yield hasExtension();
1837
+ if (transportType) {
1838
+ if (transportType === "browser" /* Browser */) {
1839
+ if (hasExtensionInstalled && preferExtension) {
1840
+ const apiTransport = new DefaultTransport();
1841
+ this.__transport = apiTransport;
1842
+ this.listener = apiTransport.onNotification(
1843
+ this.onTransportNotification.bind(this)
1844
+ );
1845
+ return apiTransport;
1846
+ }
1847
+ } else if (transportType === "mwp" /* MPW */) {
1848
+ const { adapter: kvstore } = this.options.storage;
1849
+ const dappClient = yield this.createDappClient();
1850
+ const apiTransport = new MWPTransport(dappClient, kvstore);
1851
+ this.__dappClient = dappClient;
1852
+ this.__transport = apiTransport;
1853
+ this.listener = apiTransport.onNotification(
1854
+ this.onTransportNotification.bind(this)
1855
+ );
1856
+ return apiTransport;
1857
+ }
1858
+ yield this.storage.removeTransport();
1859
+ }
1860
+ return void 0;
1861
+ });
1862
+ }
1863
+ setupTransport() {
1864
+ return __async(this, null, function* () {
1865
+ const transport = yield this.getStoredTransport();
1866
+ if (transport) {
1867
+ if (!this.transport.isConnected()) {
1868
+ this.state = "connecting";
1869
+ yield this.transport.connect();
1870
+ }
1871
+ this.state = "connected";
1872
+ if (this.transport instanceof MWPTransport) {
1873
+ yield this.storage.setTransport("mwp" /* MPW */);
1874
+ } else {
1875
+ yield this.storage.setTransport("browser" /* Browser */);
1876
+ }
1877
+ } else {
1878
+ this.state = "loaded";
1879
+ }
1880
+ });
1881
+ }
1882
+ init() {
1883
+ return __async(this, null, function* () {
1884
+ var _a;
1885
+ try {
1886
+ if (typeof window !== "undefined" && ((_a = window.mmsdk) == null ? void 0 : _a.isInitialized)) {
1887
+ logger2("MetaMaskSDK: init already initialized");
1888
+ } else {
1889
+ yield this.setupAnalytics();
1890
+ yield this.setupTransport();
1891
+ analytics.track("sdk_initialized", {});
1892
+ if (typeof window !== "undefined") {
1893
+ window.mmsdk = this;
1894
+ }
1895
+ }
1896
+ } catch (error) {
1897
+ yield this.storage.removeTransport();
1898
+ this.state = "pending";
1899
+ logger2("MetaMaskSDK error during initialization", error);
1900
+ }
1901
+ });
1902
+ }
1903
+ createDappClient() {
1904
+ return __async(this, null, function* () {
1905
+ const { adapter: kvstore } = this.options.storage;
1906
+ const sessionstore = new SessionStore2(kvstore);
1907
+ const websocket = (
1908
+ // eslint-disable-next-line no-negated-condition
1909
+ typeof window !== "undefined" ? WebSocket : (yield import("ws")).WebSocket
1910
+ );
1911
+ const transport = yield WebSocketTransport.create({
1912
+ url: MWP_RELAY_URL,
1913
+ kvstore,
1914
+ websocket
1915
+ });
1916
+ const dappClient = new DappClient({ transport, sessionstore, keymanager });
1917
+ return dappClient;
1918
+ });
1919
+ }
1920
+ setupMWP() {
1921
+ return __async(this, null, function* () {
1922
+ if (this.__transport instanceof MWPTransport) {
1923
+ return;
1924
+ }
1925
+ const { adapter: kvstore } = this.options.storage;
1926
+ const dappClient = yield this.createDappClient();
1927
+ this.__dappClient = dappClient;
1928
+ const apiTransport = new MWPTransport(dappClient, kvstore);
1929
+ this.__transport = apiTransport;
1930
+ this.listener = this.transport.onNotification(
1931
+ this.onTransportNotification.bind(this)
1932
+ );
1933
+ yield this.storage.setTransport("mwp" /* MPW */);
1934
+ });
1935
+ }
1936
+ onBeforeUnload() {
1937
+ return __async(this, null, function* () {
1938
+ var _a;
1939
+ if ((_a = this.options.ui.factory.modal) == null ? void 0 : _a.isMounted) {
1940
+ yield this.storage.removeTransport();
1941
+ }
1942
+ });
1943
+ }
1944
+ createBeforeUnloadListener() {
1945
+ if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1946
+ window.addEventListener("beforeunload", this.onBeforeUnload.bind(this));
1947
+ }
1948
+ return () => {
1949
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
1950
+ window.removeEventListener(
1951
+ "beforeunload",
1952
+ this.onBeforeUnload.bind(this)
1953
+ );
1954
+ }
1955
+ };
1956
+ }
1957
+ showInstallModal(desktopPreferred, scopes, caipAccountIds) {
1958
+ return __async(this, null, function* () {
1959
+ var _a;
1960
+ (_a = this.__beforeUnloadListener) != null ? _a : this.__beforeUnloadListener = this.createBeforeUnloadListener();
1961
+ return new Promise((resolve, reject) => {
1962
+ this.options.ui.factory.renderInstallModal(
1963
+ desktopPreferred,
1964
+ () => __async(this, null, function* () {
1965
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
1966
+ yield this.dappClient.disconnect();
1967
+ }
1968
+ return new Promise((resolveConnectionRequest) => {
1969
+ this.dappClient.on(
1970
+ "session_request",
1971
+ (sessionRequest) => {
1972
+ resolveConnectionRequest({
1973
+ sessionRequest,
1974
+ metadata: {
1975
+ dapp: this.options.dapp,
1976
+ sdk: {
1977
+ version: getVersion(),
1978
+ platform: getPlatformType()
1979
+ }
1980
+ }
1981
+ });
1982
+ }
1983
+ );
1984
+ this.transport.connect({ scopes, caipAccountIds }).then(() => {
1985
+ var _a2;
1986
+ this.options.ui.factory.unload();
1987
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
1988
+ this.state = "connected";
1989
+ return this.storage.setTransport("mwp" /* MPW */);
1990
+ }).catch((error) => {
1991
+ if (error instanceof ProtocolError) {
1992
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
1993
+ this.state = "disconnected";
1994
+ reject(error);
1995
+ }
1996
+ } else {
1997
+ this.state = "disconnected";
1998
+ reject(error);
1999
+ }
2000
+ });
2001
+ });
2002
+ }),
2003
+ (error) => __async(this, null, function* () {
2004
+ if (!error) {
2005
+ yield this.storage.setTransport("mwp" /* MPW */);
2006
+ resolve();
2007
+ } else {
2008
+ yield this.storage.removeTransport();
2009
+ reject(error);
2010
+ }
2011
+ })
2012
+ );
2013
+ });
2014
+ });
2015
+ }
2016
+ setupDefaultTransport() {
2017
+ return __async(this, null, function* () {
2018
+ this.state = "connecting";
2019
+ yield this.storage.setTransport("browser" /* Browser */);
2020
+ const transport = new DefaultTransport();
2021
+ this.listener = transport.onNotification(
2022
+ this.onTransportNotification.bind(this)
2023
+ );
2024
+ this.__transport = transport;
2025
+ return transport;
2026
+ });
2027
+ }
2028
+ deeplinkConnect(scopes, caipAccountIds) {
2029
+ return __async(this, null, function* () {
2030
+ return new Promise((resolve, reject) => __async(this, null, function* () {
2031
+ this.dappClient.on("message", (payload) => {
2032
+ var _a, _b, _c;
2033
+ const data = payload.data;
2034
+ if (typeof data === "object" && data !== null) {
2035
+ if ("method" in data && data.method === "wallet_createSession") {
2036
+ if (data.error) {
2037
+ this.state = "loaded";
2038
+ return reject(data.error);
2039
+ }
2040
+ const session = (_a = data.params) != null ? _a : data.result;
2041
+ if (session) {
2042
+ (_c = (_b = this.options.transport) == null ? void 0 : _b.onNotification) == null ? void 0 : _c.call(_b, payload.data);
2043
+ this.emit("wallet_sessionChanged", session);
2044
+ }
2045
+ }
2046
+ }
2047
+ });
2048
+ let timeout;
2049
+ if (!this.transport.isConnected()) {
2050
+ this.dappClient.once(
2051
+ "session_request",
2052
+ (sessionRequest) => {
2053
+ var _a;
2054
+ const connectionRequest = {
2055
+ sessionRequest,
2056
+ metadata: {
2057
+ dapp: this.options.dapp,
2058
+ sdk: { version: getVersion(), platform: getPlatformType() }
2059
+ }
2060
+ };
2061
+ const deeplink = this.options.ui.factory.createDeeplink(connectionRequest);
2062
+ const universalLink = this.options.ui.factory.createUniversalLink(connectionRequest);
2063
+ if ((_a = this.options.mobile) == null ? void 0 : _a.preferredOpenLink) {
2064
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
2065
+ } else {
2066
+ openDeeplink(this.options, deeplink, universalLink);
2067
+ }
2068
+ }
2069
+ );
2070
+ } else {
2071
+ timeout = setTimeout(() => {
2072
+ var _a;
2073
+ const deeplink = this.options.ui.factory.createDeeplink();
2074
+ const universalLink = this.options.ui.factory.createUniversalLink();
2075
+ if ((_a = this.options.mobile) == null ? void 0 : _a.preferredOpenLink) {
2076
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
2077
+ } else {
2078
+ openDeeplink(this.options, deeplink, universalLink);
2079
+ }
2080
+ }, 250);
2081
+ }
2082
+ this.transport.connect({ scopes, caipAccountIds }).then(resolve).catch((error) => {
2083
+ this.storage.removeTransport();
2084
+ reject(error);
2085
+ }).finally(() => {
2086
+ if (timeout) {
2087
+ clearTimeout(timeout);
2088
+ }
2089
+ });
2090
+ }));
2091
+ });
2092
+ }
2093
+ handleConnection(promise) {
2094
+ return __async(this, null, function* () {
2095
+ this.state = "connecting";
2096
+ return promise.then(() => {
2097
+ this.state = "connected";
2098
+ }).catch((error) => {
2099
+ this.state = "disconnected";
2100
+ return Promise.reject(error);
2101
+ });
2102
+ });
2103
+ }
2104
+ connect(scopes, caipAccountIds) {
2105
+ return __async(this, null, function* () {
2106
+ var _a;
2107
+ const { ui } = this.options;
2108
+ const platformType = getPlatformType();
2109
+ const isWeb = platformType === "in-app-browser" /* MetaMaskMobileWebview */ || platformType === "web-desktop" /* DesktopWeb */;
2110
+ const { preferExtension = true, preferDesktop = false } = ui;
2111
+ const secure = isSecure();
2112
+ const hasExtensionInstalled = yield hasExtension();
2113
+ if (((_a = this.__transport) == null ? void 0 : _a.isConnected()) && !secure) {
2114
+ return this.handleConnection(
2115
+ this.__transport.connect({ scopes, caipAccountIds }).then(() => {
2116
+ if (this.__transport instanceof MWPTransport) {
2117
+ return this.storage.setTransport("mwp" /* MPW */);
2118
+ } else {
2119
+ return this.storage.setTransport("browser" /* Browser */);
2120
+ }
2121
+ })
2122
+ );
2123
+ }
2124
+ if (isWeb && hasExtensionInstalled && preferExtension) {
2125
+ const defaultTransport = yield this.setupDefaultTransport();
2126
+ return this.handleConnection(
2127
+ defaultTransport.connect({ scopes, caipAccountIds })
2128
+ );
2129
+ }
2130
+ yield this.setupMWP();
2131
+ const isDesktopPreferred = hasExtensionInstalled ? preferDesktop : !preferExtension || preferDesktop;
2132
+ if (secure && !isDesktopPreferred) {
2133
+ return this.handleConnection(
2134
+ this.deeplinkConnect(scopes, caipAccountIds)
2135
+ );
2136
+ }
2137
+ return this.handleConnection(
2138
+ this.showInstallModal(isDesktopPreferred, scopes, caipAccountIds)
2139
+ );
2140
+ });
2141
+ }
2142
+ emit(event, args) {
2143
+ var _a, _b;
2144
+ (_b = (_a = this.options.transport) == null ? void 0 : _a.onNotification) == null ? void 0 : _b.call(_a, { method: event, params: args });
2145
+ super.emit(event, args);
2146
+ }
2147
+ disconnect() {
2148
+ return __async(this, null, function* () {
2149
+ var _a, _b, _c;
2150
+ (_a = this.listener) == null ? void 0 : _a.call(this);
2151
+ (_b = this.__beforeUnloadListener) == null ? void 0 : _b.call(this);
2152
+ yield (_c = this.__transport) == null ? void 0 : _c.disconnect();
2153
+ yield this.storage.removeTransport();
2154
+ this.emit("wallet_sessionChanged", void 0);
2155
+ this.emit("stateChanged", "disconnected");
2156
+ this.listener = void 0;
2157
+ this.__beforeUnloadListener = void 0;
2158
+ this.__transport = void 0;
2159
+ this.__provider = void 0;
2160
+ this.__dappClient = void 0;
2161
+ });
2162
+ }
2163
+ invokeMethod(request) {
2164
+ return __async(this, null, function* () {
2165
+ var _a;
2166
+ const { sdkInfo, transport, options } = this;
2167
+ (_a = this.__provider) != null ? _a : this.__provider = getMultichainClient({ transport });
2168
+ const rpcClient = new RpcClient(options, sdkInfo);
2169
+ const requestRouter = new RequestRouter(transport, rpcClient, options);
2170
+ return requestRouter.invokeMethod(request);
2171
+ });
2172
+ }
2173
+ };
2174
+
2175
+ // src/store/index.ts
2176
+ import * as uuid from "uuid";
2177
+
2178
+ // src/domain/errors/storage.ts
2179
+ init_base();
2180
+ var _StorageGetErr = class _StorageGetErr extends BaseErr {
2181
+ constructor(platform, key, reason) {
2182
+ super(
2183
+ `StorageErr${_StorageGetErr.code}: ${platform} storage get error in key: ${key} - ${reason}`,
2184
+ _StorageGetErr.code
2185
+ );
2186
+ this.platform = platform;
2187
+ this.key = key;
2188
+ this.reason = reason;
2189
+ }
2190
+ };
2191
+ _StorageGetErr.code = 60;
2192
+ var StorageGetErr = _StorageGetErr;
2193
+ var _StorageSetErr = class _StorageSetErr extends BaseErr {
2194
+ constructor(platform, key, reason) {
2195
+ super(
2196
+ `StorageErr${_StorageSetErr.code}: ${platform} storage set error in key: ${key} - ${reason}`,
2197
+ _StorageSetErr.code
2198
+ );
2199
+ this.platform = platform;
2200
+ this.key = key;
2201
+ this.reason = reason;
2202
+ }
2203
+ };
2204
+ _StorageSetErr.code = 61;
2205
+ var StorageSetErr = _StorageSetErr;
2206
+ var _StorageDeleteErr = class _StorageDeleteErr extends BaseErr {
2207
+ constructor(platform, key, reason) {
2208
+ super(
2209
+ `StorageErr${_StorageDeleteErr.code}: ${platform} storage delete error in key: ${key} - ${reason}`,
2210
+ _StorageDeleteErr.code
2211
+ );
2212
+ this.platform = platform;
2213
+ this.key = key;
2214
+ this.reason = reason;
2215
+ }
2216
+ };
2217
+ _StorageDeleteErr.code = 62;
2218
+ var StorageDeleteErr = _StorageDeleteErr;
2219
+
2220
+ // src/store/index.ts
2221
+ init_multichain();
2222
+ init_client();
2223
+ var Store = class extends StoreClient {
2224
+ constructor(adapter) {
2225
+ super();
2226
+ this.adapter = adapter;
2227
+ }
2228
+ getTransport() {
2229
+ return __async(this, null, function* () {
2230
+ try {
2231
+ const transport = yield this.adapter.get("multichain-transport");
2232
+ if (!transport) {
2233
+ return null;
2234
+ }
2235
+ return getTransportType(transport);
2236
+ } catch (err) {
2237
+ throw new StorageGetErr(
2238
+ this.adapter.platform,
2239
+ "multichain-transport",
2240
+ err.message
2241
+ );
2242
+ }
2243
+ });
2244
+ }
2245
+ setTransport(transport) {
2246
+ return __async(this, null, function* () {
2247
+ try {
2248
+ yield this.adapter.set("multichain-transport", transport);
2249
+ } catch (err) {
2250
+ throw new StorageSetErr(
2251
+ this.adapter.platform,
2252
+ "multichain-transport",
2253
+ err.message
2254
+ );
2255
+ }
2256
+ });
2257
+ }
2258
+ removeTransport() {
2259
+ return __async(this, null, function* () {
2260
+ try {
2261
+ yield this.adapter.delete("multichain-transport");
2262
+ } catch (err) {
2263
+ throw new StorageDeleteErr(
2264
+ this.adapter.platform,
2265
+ "multichain-transport",
2266
+ err.message
2267
+ );
2268
+ }
2269
+ });
2270
+ }
2271
+ getAnonId() {
2272
+ return __async(this, null, function* () {
2273
+ try {
2274
+ const anonId = yield this.adapter.get("anonId");
2275
+ if (anonId) {
2276
+ return anonId;
2277
+ }
2278
+ const newAnonId = uuid.v4();
2279
+ yield this.adapter.set("anonId", newAnonId);
2280
+ return newAnonId;
2281
+ } catch (err) {
2282
+ throw new StorageGetErr(this.adapter.platform, "anonId", err.message);
2283
+ }
2284
+ });
2285
+ }
2286
+ getExtensionId() {
2287
+ return __async(this, null, function* () {
2288
+ try {
2289
+ return yield this.adapter.get("extensionId");
2290
+ } catch (err) {
2291
+ throw new StorageGetErr(
2292
+ this.adapter.platform,
2293
+ "extensionId",
2294
+ err.message
2295
+ );
2296
+ }
2297
+ });
2298
+ }
2299
+ setAnonId(anonId) {
2300
+ return __async(this, null, function* () {
2301
+ try {
2302
+ return yield this.adapter.set("anonId", anonId);
2303
+ } catch (err) {
2304
+ throw new StorageSetErr(this.adapter.platform, "anonId", err.message);
2305
+ }
2306
+ });
2307
+ }
2308
+ setExtensionId(extensionId) {
2309
+ return __async(this, null, function* () {
2310
+ try {
2311
+ return yield this.adapter.set("extensionId", extensionId);
2312
+ } catch (err) {
2313
+ throw new StorageSetErr(
2314
+ this.adapter.platform,
2315
+ "extensionId",
2316
+ err.message
2317
+ );
2318
+ }
2319
+ });
2320
+ }
2321
+ removeExtensionId() {
2322
+ return __async(this, null, function* () {
2323
+ try {
2324
+ return yield this.adapter.delete("extensionId");
2325
+ } catch (err) {
2326
+ throw new StorageDeleteErr(
2327
+ this.adapter.platform,
2328
+ "extensionId",
2329
+ err.message
2330
+ );
2331
+ }
2332
+ });
2333
+ }
2334
+ removeAnonId() {
2335
+ return __async(this, null, function* () {
2336
+ try {
2337
+ return yield this.adapter.delete("anonId");
2338
+ } catch (err) {
2339
+ throw new StorageDeleteErr(this.adapter.platform, "anonId", err.message);
2340
+ }
2341
+ });
2342
+ }
2343
+ getDebug() {
2344
+ return __async(this, null, function* () {
2345
+ try {
2346
+ return yield this.adapter.get("DEBUG");
2347
+ } catch (err) {
2348
+ throw new StorageGetErr(this.adapter.platform, "DEBUG", err.message);
2349
+ }
2350
+ });
2351
+ }
2352
+ };
2353
+
2354
+ // src/ui/index.ts
2355
+ import MetaMaskOnboarding from "@metamask/onboarding";
2356
+ init_domain();
2357
+ init_qr();
2358
+ var __instance;
2359
+ function preload() {
2360
+ return __async(this, null, function* () {
2361
+ __instance != null ? __instance : __instance = yield import(
2362
+ // Use a non-literal specifier to avoid Vite static analysis of deep imports
2363
+ // and gracefully handle absence of the Stencil loader in this package build.
2364
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2365
+ // @ts-ignore
2366
+ "@metamask/multichain-ui".concat("/dist/loader/index.js")
2367
+ // Prefer ESM loader in browsers
2368
+ ).then((loader) => __async(null, null, function* () {
2369
+ if (typeof (loader == null ? void 0 : loader.defineCustomElements) === "function") {
2370
+ loader.defineCustomElements();
2371
+ }
2372
+ return Promise.resolve(loader);
2373
+ })).catch((error) => __async(null, null, function* () {
2374
+ console.error(`Gracefully Failed to load modal customElements:`, error);
2375
+ return Promise.resolve(void 0);
2376
+ }));
2377
+ });
2378
+ }
2379
+ var ModalFactory = class {
2380
+ /**
2381
+ * Creates a new modal factory instance.
2382
+ *
2383
+ * @param options - The modals configuration object
2384
+ */
2385
+ constructor(options) {
2386
+ this.options = options;
2387
+ this.platform = getPlatformType();
2388
+ this.validateModals();
2389
+ }
2390
+ validateModals() {
2391
+ const requiredModals = ["InstallModal", "OTPCodeModal"];
2392
+ const missingModals = requiredModals.filter(
2393
+ (modal) => !this.options[modal]
2394
+ );
2395
+ if (missingModals.length > 0) {
2396
+ throw new Error(`Missing required modals: ${missingModals.join(", ")}`);
2397
+ }
2398
+ }
2399
+ unload(error) {
2400
+ return __async(this, null, function* () {
2401
+ var _a, _b;
2402
+ (_a = this.modal) == null ? void 0 : _a.unmount();
2403
+ yield (_b = this.successCallback) == null ? void 0 : _b.call(this, error);
2404
+ });
2405
+ }
2406
+ /**
2407
+ * Determines if the current platform is a mobile native environment.
2408
+ * Currently only includes React Native.
2409
+ */
2410
+ get isMobile() {
2411
+ return this.platform === "react-native" /* ReactNative */;
2412
+ }
2413
+ /**
2414
+ * Determines if the current platform is a Node.js environment.
2415
+ * Used for server-side or non-browser environments.
2416
+ */
2417
+ get isNode() {
2418
+ return this.platform === "nodejs" /* NonBrowser */;
2419
+ }
2420
+ /**
2421
+ * Determines if the current platform is a web environment.
2422
+ * Includes desktop web, MetaMask mobile webview, and mobile web.
2423
+ */
2424
+ get isWeb() {
2425
+ return this.platform === "web-desktop" /* DesktopWeb */ || this.platform === "in-app-browser" /* MetaMaskMobileWebview */ || this.platform === "web-mobile" /* MobileWeb */;
2426
+ }
2427
+ getContainer() {
2428
+ return typeof document === "undefined" ? void 0 : document.createElement("div");
2429
+ }
2430
+ getMountedContainer() {
2431
+ if (typeof document === "undefined") {
2432
+ return void 0;
2433
+ }
2434
+ const container = this.getContainer();
2435
+ if (container) {
2436
+ document.body.appendChild(container);
2437
+ }
2438
+ return container;
2439
+ }
2440
+ createDeeplink(connectionRequest) {
2441
+ if (!connectionRequest) {
2442
+ return `${METAMASK_DEEPLINK_BASE}`;
2443
+ }
2444
+ const json = JSON.stringify(connectionRequest);
2445
+ const compressed = compressString(json);
2446
+ const urlEncoded = encodeURIComponent(compressed);
2447
+ return `${METAMASK_DEEPLINK_BASE}/mwp?p=${urlEncoded}&c=1`;
2448
+ }
2449
+ createUniversalLink(connectionRequest) {
2450
+ if (!connectionRequest) {
2451
+ return `${METAMASK_CONNECT_BASE_URL}`;
2452
+ }
2453
+ const json = JSON.stringify(connectionRequest);
2454
+ const compressed = compressString(json);
2455
+ const urlEncoded = encodeURIComponent(compressed);
2456
+ return `${METAMASK_CONNECT_BASE_URL}/mwp?p=${urlEncoded}&c=1`;
2457
+ }
2458
+ onCloseModal(shouldTerminate = true) {
2459
+ return __async(this, null, function* () {
2460
+ return this.unload(
2461
+ shouldTerminate ? new Error("User closed modal") : void 0
2462
+ );
2463
+ });
2464
+ }
2465
+ onStartDesktopOnboarding() {
2466
+ new MetaMaskOnboarding().startOnboarding();
2467
+ }
2468
+ renderInstallModal(preferDesktop, createConnectionRequest, successCallback) {
2469
+ return __async(this, null, function* () {
2470
+ var _a;
2471
+ (_a = this.modal) == null ? void 0 : _a.unmount();
2472
+ yield Promise.all([preload(), preloadQR()]);
2473
+ this.successCallback = successCallback;
2474
+ const parentElement = this.getMountedContainer();
2475
+ const connectionRequest = yield createConnectionRequest();
2476
+ const qrCodeLink = this.createDeeplink(connectionRequest);
2477
+ const modal = new this.options.InstallModal({
2478
+ expiresIn: (connectionRequest.sessionRequest.expiresAt - Date.now()) / 1e3,
2479
+ connectionRequest,
2480
+ parentElement,
2481
+ preferDesktop,
2482
+ link: qrCodeLink,
2483
+ sdkVersion: getVersion(),
2484
+ generateQRCode: (request) => __async(this, null, function* () {
2485
+ return this.createDeeplink(request);
2486
+ }),
2487
+ onClose: this.onCloseModal.bind(this),
2488
+ startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
2489
+ createConnectionRequest
2490
+ });
2491
+ this.modal = modal;
2492
+ modal.mount();
2493
+ });
2494
+ }
2495
+ renderOTPCodeModal(createOTPCode, successCallback, updateOTPCode) {
2496
+ return __async(this, null, function* () {
2497
+ var _a;
2498
+ (_a = this.modal) == null ? void 0 : _a.unmount();
2499
+ yield Promise.all([preload(), preloadQR()]);
2500
+ this.successCallback = successCallback;
2501
+ const container = this.getMountedContainer();
2502
+ const otpCode = yield createOTPCode();
2503
+ const modal = new this.options.OTPCodeModal({
2504
+ parentElement: container,
2505
+ sdkVersion: getVersion(),
2506
+ otpCode,
2507
+ onClose: this.onCloseModal.bind(this),
2508
+ createOTPCode,
2509
+ updateOTPCode: (otpCode2) => updateOTPCode(otpCode2, modal)
2510
+ });
2511
+ this.modal = modal;
2512
+ modal.mount();
2513
+ });
2514
+ }
2515
+ };
2516
+
2517
+ // src/index.node.ts
2518
+ init_domain();
2519
+ var createMetamaskConnect = (options) => __async(null, null, function* () {
2520
+ const uiModules = yield Promise.resolve().then(() => (init_node(), node_exports));
2521
+ let storage;
2522
+ if (!options.storage) {
2523
+ const { StoreAdapterNode: StoreAdapterNode2 } = yield Promise.resolve().then(() => (init_node2(), node_exports2));
2524
+ const adapter = new StoreAdapterNode2();
2525
+ storage = new Store(adapter);
2526
+ } else {
2527
+ storage = options.storage;
2528
+ }
2529
+ const factory = new ModalFactory(uiModules);
2530
+ return MultichainSDK.create(__spreadProps(__spreadValues({}, options), {
2531
+ storage,
2532
+ ui: __spreadProps(__spreadValues({}, options.ui), {
2533
+ factory
2534
+ })
2535
+ }));
2536
+ });
2537
+ export {
2538
+ EventEmitter,
2539
+ Modal,
2540
+ MultichainCore,
2541
+ PlatformType,
2542
+ RPCHttpErr,
2543
+ RPCInvokeMethodErr,
2544
+ RPCReadonlyRequestErr,
2545
+ RPCReadonlyResponseErr,
2546
+ RPC_HANDLED_METHODS,
2547
+ SDK_HANDLED_METHODS,
2548
+ StoreAdapter,
2549
+ StoreClient,
2550
+ TransportType,
2551
+ createLogger,
2552
+ createMetamaskConnect,
2553
+ enableDebug,
2554
+ getInfuraRpcUrls,
2555
+ getPlatformType,
2556
+ getTransportType,
2557
+ getVersion,
2558
+ hasExtension,
2559
+ infuraRpcUrls,
2560
+ isEnabled,
2561
+ isMetamaskExtensionInstalled,
2562
+ isSecure
2563
+ };
2564
+ //# sourceMappingURL=connect-multichain.mjs.map