@0xkey-io/core 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 (183) hide show
  1. package/LICENSE +201 -0
  2. package/README.MD +7 -0
  3. package/dist/0xkey-helpers.d.ts +68 -0
  4. package/dist/0xkey-helpers.d.ts.map +1 -0
  5. package/dist/0xkey-helpers.js +466 -0
  6. package/dist/0xkey-helpers.js.map +1 -0
  7. package/dist/0xkey-helpers.mjs +399 -0
  8. package/dist/0xkey-helpers.mjs.map +1 -0
  9. package/dist/__clients__/core.d.ts +1201 -0
  10. package/dist/__clients__/core.d.ts.map +1 -0
  11. package/dist/__clients__/core.js +3489 -0
  12. package/dist/__clients__/core.js.map +1 -0
  13. package/dist/__clients__/core.mjs +3487 -0
  14. package/dist/__clients__/core.mjs.map +1 -0
  15. package/dist/__generated__/sdk-client-base.d.ts +281 -0
  16. package/dist/__generated__/sdk-client-base.d.ts.map +1 -0
  17. package/dist/__generated__/sdk-client-base.js +3906 -0
  18. package/dist/__generated__/sdk-client-base.js.map +1 -0
  19. package/dist/__generated__/sdk-client-base.mjs +3904 -0
  20. package/dist/__generated__/sdk-client-base.mjs.map +1 -0
  21. package/dist/__generated__/version.d.ts +2 -0
  22. package/dist/__generated__/version.d.ts.map +1 -0
  23. package/dist/__generated__/version.js +6 -0
  24. package/dist/__generated__/version.js.map +1 -0
  25. package/dist/__generated__/version.mjs +4 -0
  26. package/dist/__generated__/version.mjs.map +1 -0
  27. package/dist/__inputs__/public_api.types.d.ts +6014 -0
  28. package/dist/__inputs__/public_api.types.d.ts.map +1 -0
  29. package/dist/__polyfills__/jest.setup.webcrypto.d.ts +2 -0
  30. package/dist/__polyfills__/jest.setup.webcrypto.d.ts.map +1 -0
  31. package/dist/__polyfills__/window.d.ts +15 -0
  32. package/dist/__polyfills__/window.d.ts.map +1 -0
  33. package/dist/__polyfills__/window.js +30 -0
  34. package/dist/__polyfills__/window.js.map +1 -0
  35. package/dist/__polyfills__/window.mjs +28 -0
  36. package/dist/__polyfills__/window.mjs.map +1 -0
  37. package/dist/__stampers__/api/base.d.ts +27 -0
  38. package/dist/__stampers__/api/base.d.ts.map +1 -0
  39. package/dist/__stampers__/api/base.js +102 -0
  40. package/dist/__stampers__/api/base.js.map +1 -0
  41. package/dist/__stampers__/api/base.mjs +100 -0
  42. package/dist/__stampers__/api/base.mjs.map +1 -0
  43. package/dist/__stampers__/api/mobile/stamper.d.ts +15 -0
  44. package/dist/__stampers__/api/mobile/stamper.d.ts.map +1 -0
  45. package/dist/__stampers__/api/mobile/stamper.js +119 -0
  46. package/dist/__stampers__/api/mobile/stamper.js.map +1 -0
  47. package/dist/__stampers__/api/mobile/stamper.mjs +117 -0
  48. package/dist/__stampers__/api/mobile/stamper.mjs.map +1 -0
  49. package/dist/__stampers__/api/web/stamper.d.ts +14 -0
  50. package/dist/__stampers__/api/web/stamper.d.ts.map +1 -0
  51. package/dist/__stampers__/api/web/stamper.js +201 -0
  52. package/dist/__stampers__/api/web/stamper.js.map +1 -0
  53. package/dist/__stampers__/api/web/stamper.mjs +199 -0
  54. package/dist/__stampers__/api/web/stamper.mjs.map +1 -0
  55. package/dist/__stampers__/passkey/base.d.ts +16 -0
  56. package/dist/__stampers__/passkey/base.d.ts.map +1 -0
  57. package/dist/__stampers__/passkey/base.js +138 -0
  58. package/dist/__stampers__/passkey/base.js.map +1 -0
  59. package/dist/__stampers__/passkey/base.mjs +134 -0
  60. package/dist/__stampers__/passkey/base.mjs.map +1 -0
  61. package/dist/__storage__/base.d.ts +3 -0
  62. package/dist/__storage__/base.d.ts.map +1 -0
  63. package/dist/__storage__/base.js +27 -0
  64. package/dist/__storage__/base.js.map +1 -0
  65. package/dist/__storage__/base.mjs +25 -0
  66. package/dist/__storage__/base.mjs.map +1 -0
  67. package/dist/__storage__/mobile/storage.d.ts +18 -0
  68. package/dist/__storage__/mobile/storage.d.ts.map +1 -0
  69. package/dist/__storage__/mobile/storage.js +76 -0
  70. package/dist/__storage__/mobile/storage.js.map +1 -0
  71. package/dist/__storage__/mobile/storage.mjs +74 -0
  72. package/dist/__storage__/mobile/storage.mjs.map +1 -0
  73. package/dist/__storage__/web/storage.d.ts +19 -0
  74. package/dist/__storage__/web/storage.d.ts.map +1 -0
  75. package/dist/__storage__/web/storage.js +79 -0
  76. package/dist/__storage__/web/storage.js.map +1 -0
  77. package/dist/__storage__/web/storage.mjs +77 -0
  78. package/dist/__storage__/web/storage.mjs.map +1 -0
  79. package/dist/__typedoc-entry__/index.d.ts +3 -0
  80. package/dist/__typedoc-entry__/index.d.ts.map +1 -0
  81. package/dist/__types__/auth.d.ts +120 -0
  82. package/dist/__types__/auth.d.ts.map +1 -0
  83. package/dist/__types__/auth.js +7 -0
  84. package/dist/__types__/auth.js.map +1 -0
  85. package/dist/__types__/auth.mjs +5 -0
  86. package/dist/__types__/auth.mjs.map +1 -0
  87. package/dist/__types__/config.d.ts +145 -0
  88. package/dist/__types__/config.d.ts.map +1 -0
  89. package/dist/__types__/enums.d.ts +59 -0
  90. package/dist/__types__/enums.d.ts.map +1 -0
  91. package/dist/__types__/enums.js +72 -0
  92. package/dist/__types__/enums.js.map +1 -0
  93. package/dist/__types__/enums.mjs +70 -0
  94. package/dist/__types__/enums.mjs.map +1 -0
  95. package/dist/__types__/error.d.ts +13 -0
  96. package/dist/__types__/error.d.ts.map +1 -0
  97. package/dist/__types__/error.js +18 -0
  98. package/dist/__types__/error.js.map +1 -0
  99. package/dist/__types__/error.mjs +16 -0
  100. package/dist/__types__/error.mjs.map +1 -0
  101. package/dist/__types__/export.d.ts +10 -0
  102. package/dist/__types__/export.d.ts.map +1 -0
  103. package/dist/__types__/external-wallets.d.ts +203 -0
  104. package/dist/__types__/external-wallets.d.ts.map +1 -0
  105. package/dist/__types__/http.d.ts +17 -0
  106. package/dist/__types__/http.d.ts.map +1 -0
  107. package/dist/__types__/http.js +11 -0
  108. package/dist/__types__/http.js.map +1 -0
  109. package/dist/__types__/http.mjs +9 -0
  110. package/dist/__types__/http.mjs.map +1 -0
  111. package/dist/__types__/index.d.ts +10 -0
  112. package/dist/__types__/index.d.ts.map +1 -0
  113. package/dist/__types__/method-types/import-export-params.d.ts +38 -0
  114. package/dist/__types__/method-types/import-export-params.d.ts.map +1 -0
  115. package/dist/__types__/method-types/shared.d.ts +378 -0
  116. package/dist/__types__/method-types/shared.d.ts.map +1 -0
  117. package/dist/__wallet__/base.d.ts +14 -0
  118. package/dist/__wallet__/base.d.ts.map +1 -0
  119. package/dist/__wallet__/base.js +35 -0
  120. package/dist/__wallet__/base.js.map +1 -0
  121. package/dist/__wallet__/base.mjs +33 -0
  122. package/dist/__wallet__/base.mjs.map +1 -0
  123. package/dist/__wallet__/connector.d.ts +60 -0
  124. package/dist/__wallet__/connector.d.ts.map +1 -0
  125. package/dist/__wallet__/connector.js +93 -0
  126. package/dist/__wallet__/connector.js.map +1 -0
  127. package/dist/__wallet__/connector.mjs +91 -0
  128. package/dist/__wallet__/connector.mjs.map +1 -0
  129. package/dist/__wallet__/mobile/manager.d.ts +51 -0
  130. package/dist/__wallet__/mobile/manager.d.ts.map +1 -0
  131. package/dist/__wallet__/mobile/manager.js +115 -0
  132. package/dist/__wallet__/mobile/manager.js.map +1 -0
  133. package/dist/__wallet__/mobile/manager.mjs +113 -0
  134. package/dist/__wallet__/mobile/manager.mjs.map +1 -0
  135. package/dist/__wallet__/stamper.d.ts +90 -0
  136. package/dist/__wallet__/stamper.d.ts.map +1 -0
  137. package/dist/__wallet__/stamper.js +183 -0
  138. package/dist/__wallet__/stamper.js.map +1 -0
  139. package/dist/__wallet__/stamper.mjs +180 -0
  140. package/dist/__wallet__/stamper.mjs.map +1 -0
  141. package/dist/__wallet__/wallet-connect/base.d.ts +182 -0
  142. package/dist/__wallet__/wallet-connect/base.d.ts.map +1 -0
  143. package/dist/__wallet__/wallet-connect/base.js +606 -0
  144. package/dist/__wallet__/wallet-connect/base.js.map +1 -0
  145. package/dist/__wallet__/wallet-connect/base.mjs +604 -0
  146. package/dist/__wallet__/wallet-connect/base.mjs.map +1 -0
  147. package/dist/__wallet__/wallet-connect/client.d.ts +132 -0
  148. package/dist/__wallet__/wallet-connect/client.d.ts.map +1 -0
  149. package/dist/__wallet__/wallet-connect/client.js +262 -0
  150. package/dist/__wallet__/wallet-connect/client.js.map +1 -0
  151. package/dist/__wallet__/wallet-connect/client.mjs +260 -0
  152. package/dist/__wallet__/wallet-connect/client.mjs.map +1 -0
  153. package/dist/__wallet__/web/manager.d.ts +70 -0
  154. package/dist/__wallet__/web/manager.d.ts.map +1 -0
  155. package/dist/__wallet__/web/manager.js +177 -0
  156. package/dist/__wallet__/web/manager.js.map +1 -0
  157. package/dist/__wallet__/web/manager.mjs +175 -0
  158. package/dist/__wallet__/web/manager.mjs.map +1 -0
  159. package/dist/__wallet__/web/native/ethereum.d.ts +101 -0
  160. package/dist/__wallet__/web/native/ethereum.d.ts.map +1 -0
  161. package/dist/__wallet__/web/native/ethereum.js +339 -0
  162. package/dist/__wallet__/web/native/ethereum.js.map +1 -0
  163. package/dist/__wallet__/web/native/ethereum.mjs +336 -0
  164. package/dist/__wallet__/web/native/ethereum.mjs.map +1 -0
  165. package/dist/__wallet__/web/native/solana.d.ts +72 -0
  166. package/dist/__wallet__/web/native/solana.d.ts.map +1 -0
  167. package/dist/__wallet__/web/native/solana.js +215 -0
  168. package/dist/__wallet__/web/native/solana.js.map +1 -0
  169. package/dist/__wallet__/web/native/solana.mjs +212 -0
  170. package/dist/__wallet__/web/native/solana.mjs.map +1 -0
  171. package/dist/index.d.ts +19 -0
  172. package/dist/index.d.ts.map +1 -0
  173. package/dist/index.js +83 -0
  174. package/dist/index.js.map +1 -0
  175. package/dist/index.mjs +10 -0
  176. package/dist/index.mjs.map +1 -0
  177. package/dist/utils.d.ts +160 -0
  178. package/dist/utils.d.ts.map +1 -0
  179. package/dist/utils.js +1047 -0
  180. package/dist/utils.js.map +1 -0
  181. package/dist/utils.mjs +1007 -0
  182. package/dist/utils.mjs.map +1 -0
  183. package/package.json +80 -0
package/dist/utils.js ADDED
@@ -0,0 +1,1047 @@
1
+ 'use strict';
2
+
3
+ var sdkTypes = require('@0xkey-io/sdk-types');
4
+ var enums = require('./__types__/enums.js');
5
+ var error = require('./__types__/error.js');
6
+ var encoding = require('@0xkey-io/encoding');
7
+ var _0xkeyHelpers = require('./0xkey-helpers.js');
8
+ var crypto$1 = require('@0xkey-io/crypto');
9
+ var ethers = require('ethers');
10
+ var version = require('./__generated__/version.js');
11
+
12
+ /**
13
+ * Configuration for all supported address formats.
14
+ *
15
+ * Includes:
16
+ * - encoding type
17
+ * - hash function
18
+ * - default accounts for the address format
19
+ * - display name for the address format
20
+ *
21
+ * ```ts
22
+ * // Example usage:
23
+ * import { addressFormatConfig } from "@0xkey-io/sdk-core";
24
+ *
25
+ * const config = addressFormatConfig["ADDRESS_FORMAT_ETHEREUM"];
26
+ * ```
27
+ */
28
+ const sessionExpiredErrors = {
29
+ pubKeyNotFound: "could not find public key in organization or its parent organization",
30
+ apiKeyExpired: "Unauthenticated desc = expired api key publicKey",
31
+ };
32
+ // Global errors to match against error messages returned from the API
33
+ const globalErrorsToMatch = Object.freeze({
34
+ [sessionExpiredErrors.pubKeyNotFound]: {
35
+ message: "Session public key could not be found in the sub-organization or parent organization",
36
+ code: sdkTypes.ZeroXKeyErrorCodes.SESSION_EXPIRED,
37
+ },
38
+ [sessionExpiredErrors.apiKeyExpired]: {
39
+ message: "Session API key has expired",
40
+ code: sdkTypes.ZeroXKeyErrorCodes.SESSION_EXPIRED,
41
+ },
42
+ });
43
+ const addressFormatConfig = {
44
+ ADDRESS_FORMAT_UNCOMPRESSED: {
45
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
46
+ hashFunction: "HASH_FUNCTION_SHA256",
47
+ defaultAccounts: null,
48
+ displayName: "Uncompressed",
49
+ },
50
+ ADDRESS_FORMAT_COMPRESSED: {
51
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
52
+ hashFunction: "HASH_FUNCTION_SHA256",
53
+ defaultAccounts: null,
54
+ displayName: "Compressed",
55
+ },
56
+ ADDRESS_FORMAT_ETHEREUM: {
57
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
58
+ hashFunction: "HASH_FUNCTION_KECCAK256",
59
+ defaultAccounts: _0xkeyHelpers.DEFAULT_ETHEREUM_ACCOUNTS,
60
+ displayName: "Ethereum",
61
+ },
62
+ ADDRESS_FORMAT_SOLANA: {
63
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
64
+ hashFunction: "HASH_FUNCTION_NOT_APPLICABLE",
65
+ defaultAccounts: _0xkeyHelpers.DEFAULT_SOLANA_ACCOUNTS,
66
+ displayName: "Solana",
67
+ },
68
+ ADDRESS_FORMAT_COSMOS: {
69
+ encoding: "PAYLOAD_ENCODING_TEXT_UTF8",
70
+ hashFunction: "HASH_FUNCTION_SHA256",
71
+ defaultAccounts: _0xkeyHelpers.DEFAULT_COSMOS_ACCOUNTS,
72
+ displayName: "Cosmos",
73
+ },
74
+ ADDRESS_FORMAT_TRON: {
75
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
76
+ hashFunction: "HASH_FUNCTION_SHA256",
77
+ defaultAccounts: _0xkeyHelpers.DEFAULT_TRON_ACCOUNTS,
78
+ displayName: "Tron",
79
+ },
80
+ ADDRESS_FORMAT_SUI: {
81
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
82
+ hashFunction: "HASH_FUNCTION_NOT_APPLICABLE",
83
+ defaultAccounts: _0xkeyHelpers.DEFAULT_SUI_ACCOUNTS,
84
+ displayName: "Sui",
85
+ },
86
+ ADDRESS_FORMAT_APTOS: {
87
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
88
+ hashFunction: "HASH_FUNCTION_NOT_APPLICABLE",
89
+ defaultAccounts: _0xkeyHelpers.DEFAULT_APTOS_ACCOUNTS,
90
+ displayName: "Aptos",
91
+ },
92
+ ADDRESS_FORMAT_BITCOIN_MAINNET_P2PKH: {
93
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
94
+ hashFunction: "HASH_FUNCTION_SHA256",
95
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_MAINNET_P2PKH_ACCOUNTS,
96
+ displayName: "Bitcoin Mainnet P2PKH",
97
+ },
98
+ ADDRESS_FORMAT_BITCOIN_MAINNET_P2SH: {
99
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
100
+ hashFunction: "HASH_FUNCTION_SHA256",
101
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_MAINNET_P2SH_ACCOUNTS,
102
+ displayName: "Bitcoin Mainnet P2SH",
103
+ },
104
+ ADDRESS_FORMAT_BITCOIN_MAINNET_P2WPKH: {
105
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
106
+ hashFunction: "HASH_FUNCTION_SHA256",
107
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_MAINNET_P2WPKH_ACCOUNTS,
108
+ displayName: "Bitcoin Mainnet P2WPKH",
109
+ },
110
+ ADDRESS_FORMAT_BITCOIN_MAINNET_P2WSH: {
111
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
112
+ hashFunction: "HASH_FUNCTION_SHA256",
113
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_MAINNET_P2WSH_ACCOUNTS,
114
+ displayName: "Bitcoin Mainnet P2WSH",
115
+ },
116
+ ADDRESS_FORMAT_BITCOIN_MAINNET_P2TR: {
117
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
118
+ hashFunction: "HASH_FUNCTION_SHA256",
119
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_MAINNET_P2TR_ACCOUNTS,
120
+ displayName: "Bitcoin Mainnet P2TR",
121
+ },
122
+ ADDRESS_FORMAT_BITCOIN_TESTNET_P2PKH: {
123
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
124
+ hashFunction: "HASH_FUNCTION_SHA256",
125
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_TESTNET_P2PKH_ACCOUNTS,
126
+ displayName: "Bitcoin Testnet P2PKH",
127
+ },
128
+ ADDRESS_FORMAT_BITCOIN_TESTNET_P2SH: {
129
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
130
+ hashFunction: "HASH_FUNCTION_SHA256",
131
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_TESTNET_P2SH_ACCOUNTS,
132
+ displayName: "Bitcoin Testnet P2SH",
133
+ },
134
+ ADDRESS_FORMAT_BITCOIN_TESTNET_P2WPKH: {
135
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
136
+ hashFunction: "HASH_FUNCTION_SHA256",
137
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_TESTNET_P2WPKH_ACCOUNTS,
138
+ displayName: "Bitcoin Testnet P2WPKH",
139
+ },
140
+ ADDRESS_FORMAT_BITCOIN_TESTNET_P2WSH: {
141
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
142
+ hashFunction: "HASH_FUNCTION_SHA256",
143
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_TESTNET_P2WSH_ACCOUNTS,
144
+ displayName: "Bitcoin Testnet P2WSH",
145
+ },
146
+ ADDRESS_FORMAT_BITCOIN_TESTNET_P2TR: {
147
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
148
+ hashFunction: "HASH_FUNCTION_SHA256",
149
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_TESTNET_P2TR_ACCOUNTS,
150
+ displayName: "Bitcoin Testnet P2TR",
151
+ },
152
+ ADDRESS_FORMAT_BITCOIN_SIGNET_P2PKH: {
153
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
154
+ hashFunction: "HASH_FUNCTION_SHA256",
155
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_SIGNET_P2PKH_ACCOUNTS,
156
+ displayName: "Bitcoin Signet P2PKH",
157
+ },
158
+ ADDRESS_FORMAT_BITCOIN_SIGNET_P2SH: {
159
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
160
+ hashFunction: "HASH_FUNCTION_SHA256",
161
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_SIGNET_P2SH_ACCOUNTS,
162
+ displayName: "Bitcoin Signet P2SH",
163
+ },
164
+ ADDRESS_FORMAT_BITCOIN_SIGNET_P2WPKH: {
165
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
166
+ hashFunction: "HASH_FUNCTION_SHA256",
167
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_SIGNET_P2WPKH_ACCOUNTS,
168
+ displayName: "Bitcoin Signet P2WPKH",
169
+ },
170
+ ADDRESS_FORMAT_BITCOIN_SIGNET_P2WSH: {
171
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
172
+ hashFunction: "HASH_FUNCTION_SHA256",
173
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_SIGNET_P2WSH_ACCOUNTS,
174
+ displayName: "Bitcoin Signet P2WSH",
175
+ },
176
+ ADDRESS_FORMAT_BITCOIN_SIGNET_P2TR: {
177
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
178
+ hashFunction: "HASH_FUNCTION_SHA256",
179
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_SIGNET_P2TR_ACCOUNTS,
180
+ displayName: "Bitcoin Signet P2TR",
181
+ },
182
+ ADDRESS_FORMAT_BITCOIN_REGTEST_P2PKH: {
183
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
184
+ hashFunction: "HASH_FUNCTION_SHA256",
185
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_REGTEST_P2PKH_ACCOUNTS,
186
+ displayName: "Bitcoin Regtest P2PKH",
187
+ },
188
+ ADDRESS_FORMAT_BITCOIN_REGTEST_P2SH: {
189
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
190
+ hashFunction: "HASH_FUNCTION_SHA256",
191
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_REGTEST_P2SH_ACCOUNTS,
192
+ displayName: "Bitcoin Regtest P2SH",
193
+ },
194
+ ADDRESS_FORMAT_BITCOIN_REGTEST_P2WPKH: {
195
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
196
+ hashFunction: "HASH_FUNCTION_SHA256",
197
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_REGTEST_P2WPKH_ACCOUNTS,
198
+ displayName: "Bitcoin Regtest P2WPKH",
199
+ },
200
+ ADDRESS_FORMAT_BITCOIN_REGTEST_P2WSH: {
201
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
202
+ hashFunction: "HASH_FUNCTION_SHA256",
203
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_REGTEST_P2WSH_ACCOUNTS,
204
+ displayName: "Bitcoin Regtest P2WSH",
205
+ },
206
+ ADDRESS_FORMAT_BITCOIN_REGTEST_P2TR: {
207
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
208
+ hashFunction: "HASH_FUNCTION_SHA256",
209
+ defaultAccounts: _0xkeyHelpers.DEFAULT_BITCOIN_REGTEST_P2TR_ACCOUNTS,
210
+ displayName: "Bitcoin Regtest P2TR",
211
+ },
212
+ ADDRESS_FORMAT_SEI: {
213
+ encoding: "PAYLOAD_ENCODING_TEXT_UTF8",
214
+ hashFunction: "HASH_FUNCTION_SHA256",
215
+ defaultAccounts: _0xkeyHelpers.DEFAULT_SEI_ACCOUNTS,
216
+ displayName: "Sei",
217
+ },
218
+ ADDRESS_FORMAT_XLM: {
219
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
220
+ hashFunction: "HASH_FUNCTION_NOT_APPLICABLE",
221
+ defaultAccounts: _0xkeyHelpers.DEFAULT_XLM_ACCOUNTS,
222
+ displayName: "Xlm",
223
+ },
224
+ ADDRESS_FORMAT_DOGE_MAINNET: {
225
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
226
+ hashFunction: "HASH_FUNCTION_SHA256",
227
+ defaultAccounts: _0xkeyHelpers.DEFAULT_DOGE_MAINNET_ACCOUNTS,
228
+ displayName: "Doge Mainnet",
229
+ },
230
+ ADDRESS_FORMAT_DOGE_TESTNET: {
231
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
232
+ hashFunction: "HASH_FUNCTION_SHA256",
233
+ defaultAccounts: _0xkeyHelpers.DEFAULT_DOGE_TESTNET_ACCOUNTS,
234
+ displayName: "Doge Testnet",
235
+ },
236
+ ADDRESS_FORMAT_TON_V3R2: {
237
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
238
+ hashFunction: "HASH_FUNCTION_NOT_APPLICABLE",
239
+ defaultAccounts: _0xkeyHelpers.DEFAULT_TON_V3R2_ACCOUNTS,
240
+ displayName: "Ton V3R2",
241
+ },
242
+ ADDRESS_FORMAT_TON_V4R2: {
243
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
244
+ hashFunction: "HASH_FUNCTION_NOT_APPLICABLE",
245
+ defaultAccounts: _0xkeyHelpers.DEFAULT_TON_V4R2_ACCOUNTS,
246
+ displayName: "Ton V4R2",
247
+ },
248
+ ADDRESS_FORMAT_TON_V5R1: {
249
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
250
+ hashFunction: "HASH_FUNCTION_NOT_APPLICABLE",
251
+ defaultAccounts: null,
252
+ displayName: "Ton V5R1",
253
+ },
254
+ ADDRESS_FORMAT_XRP: {
255
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
256
+ hashFunction: "HASH_FUNCTION_SHA256",
257
+ defaultAccounts: _0xkeyHelpers.DEFAULT_XRP_ACCOUNTS,
258
+ displayName: "XRP",
259
+ },
260
+ };
261
+ const googleISS = "https://accounts.google.com";
262
+ const isReactNative = () => {
263
+ const g = typeof globalThis !== "undefined" ? globalThis : global;
264
+ // if we have a DOM, it's definitely not RN
265
+ // RN-web has DOM but we want false for that anyway
266
+ if (typeof document !== "undefined" && typeof window !== "undefined")
267
+ return false;
268
+ // check for RN-specific globals
269
+ // these shouldn't exist in Node, browsers, or webviews
270
+ return (typeof g?.__fbBatchedBridge !== "undefined" ||
271
+ typeof g?.nativeCallSyncHook !== "undefined" ||
272
+ typeof g?.RN$Bridgeless !== "undefined");
273
+ };
274
+ const isWeb = () => {
275
+ return typeof window !== "undefined" && typeof document !== "undefined";
276
+ };
277
+ const generateRandomBuffer = () => {
278
+ const arr = new Uint8Array(32);
279
+ crypto.getRandomValues(arr);
280
+ return arr.buffer;
281
+ };
282
+ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
283
+ const toExternalTimestamp = (date = new Date()) => {
284
+ const millis = date.getTime();
285
+ const seconds = Math.floor(millis / 1000);
286
+ const nanos = (millis % 1000) * 1_000_000;
287
+ return {
288
+ seconds: seconds.toString(),
289
+ nanos: nanos.toString(),
290
+ };
291
+ };
292
+ async function getActiveSessionOrThrowIfRequired(stampWith, getActiveSession) {
293
+ const session = await getActiveSession();
294
+ // the api-key stamper requires an active session
295
+ // if there is no stampWith defined, the default is api-key stamper
296
+ if ((!stampWith || stampWith === enums.StamperType.ApiKey) && !session) {
297
+ throw new sdkTypes.ZeroXKeyError("No active session found. Please log in first.", sdkTypes.ZeroXKeyErrorCodes.NO_SESSION_FOUND);
298
+ }
299
+ return session;
300
+ }
301
+ function parseSession(token) {
302
+ if (typeof token !== "string") {
303
+ return token;
304
+ }
305
+ const [, payload] = token.split(".");
306
+ if (!payload) {
307
+ throw new Error("Invalid JWT: Missing payload");
308
+ }
309
+ const decoded = JSON.parse(atob(payload));
310
+ const { exp, public_key: publicKey, session_type: sessionType, user_id: userId, organization_id: organizationId, } = decoded;
311
+ if (!exp || !publicKey || !sessionType || !userId || !organizationId) {
312
+ throw new Error("JWT payload missing required fields");
313
+ }
314
+ const expSeconds = Math.ceil((exp * 1000 - Date.now()) / 1000);
315
+ return {
316
+ sessionType,
317
+ userId,
318
+ organizationId,
319
+ expiry: exp,
320
+ expirationSeconds: expSeconds.toString(),
321
+ publicKey,
322
+ token,
323
+ };
324
+ }
325
+ function getHashFunction(addressFormat) {
326
+ const config = addressFormatConfig[addressFormat];
327
+ if (!config) {
328
+ throw new sdkTypes.ZeroXKeyError(`Unsupported address format: ${addressFormat}`, sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
329
+ }
330
+ return config.hashFunction;
331
+ }
332
+ function getEncodingType(addressFormat) {
333
+ const config = addressFormatConfig[addressFormat];
334
+ if (!config) {
335
+ throw new sdkTypes.ZeroXKeyError(`Unsupported address format: ${addressFormat}`, sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
336
+ }
337
+ return config.encoding;
338
+ }
339
+ function getEncodedMessage(payloadEncoding, rawMessage) {
340
+ if (payloadEncoding === "PAYLOAD_ENCODING_HEXADECIMAL") {
341
+ return ("0x" +
342
+ Array.from(rawMessage)
343
+ .map((b) => b.toString(16).padStart(2, "0"))
344
+ .join(""));
345
+ }
346
+ // we decode back to a UTF-8 string
347
+ return ethers.toUtf8String(rawMessage);
348
+ }
349
+ function hexSignedTxToBase58(hex) {
350
+ const bytes = encoding.uint8ArrayFromHexString(hex);
351
+ return encoding.bs58.encode(bytes);
352
+ }
353
+ const broadcastTransaction = async (params) => {
354
+ const { signedTransaction, rpcUrl, transactionType } = params;
355
+ switch (transactionType) {
356
+ case "TRANSACTION_TYPE_SOLANA": {
357
+ const encodedTx = hexSignedTxToBase58(signedTransaction);
358
+ const response = await fetch(rpcUrl, {
359
+ method: "POST",
360
+ headers: { "Content-Type": "application/json" },
361
+ body: JSON.stringify({
362
+ jsonrpc: "2.0",
363
+ id: 1,
364
+ method: "sendTransaction",
365
+ params: [encodedTx, { encoding: "base58" }],
366
+ }),
367
+ });
368
+ const json = await response.json();
369
+ if (json.error) {
370
+ throw new sdkTypes.ZeroXKeyError(`Solana RPC Error: ${json.error.message}`, sdkTypes.ZeroXKeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
371
+ }
372
+ return json.result;
373
+ }
374
+ case "TRANSACTION_TYPE_ETHEREUM": {
375
+ const response = await fetch(rpcUrl, {
376
+ method: "POST",
377
+ headers: { "Content-Type": "application/json" },
378
+ body: JSON.stringify({
379
+ jsonrpc: "2.0",
380
+ id: 1,
381
+ method: "eth_sendRawTransaction",
382
+ params: [signedTransaction],
383
+ }),
384
+ });
385
+ const json = await response.json();
386
+ if (json.error) {
387
+ throw new sdkTypes.ZeroXKeyError(`Ethereum RPC Error: ${json.error.message}`, sdkTypes.ZeroXKeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
388
+ }
389
+ return json.result;
390
+ }
391
+ case "TRANSACTION_TYPE_TRON": {
392
+ const response = await fetch(`${rpcUrl}/wallet/broadcasthex`, {
393
+ method: "POST",
394
+ headers: { "Content-Type": "application/json" },
395
+ body: JSON.stringify({ transaction: signedTransaction }),
396
+ });
397
+ const json = await response.json();
398
+ if (!json.result) {
399
+ throw new sdkTypes.ZeroXKeyError(`Tron RPC Error: ${json.message}`, sdkTypes.ZeroXKeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
400
+ }
401
+ return json.txid;
402
+ }
403
+ default:
404
+ throw new sdkTypes.ZeroXKeyError(`Unsupported transaction type for broadcasting: ${transactionType}`, sdkTypes.ZeroXKeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
405
+ }
406
+ };
407
+ function splitSignature(signature, addressFormat) {
408
+ const hex = signature.replace(/^0x/, "");
409
+ if (addressFormat === "ADDRESS_FORMAT_ETHEREUM") {
410
+ // this is a ECDSA signature
411
+ if (hex.length === 130) {
412
+ const r = hex.slice(0, 64);
413
+ const s = hex.slice(64, 128);
414
+ const v = hex.slice(128, 130);
415
+ return { r, s, v };
416
+ }
417
+ // this is a DER-encoded signatures (e.g., Ledger)
418
+ const raw = crypto$1.fromDerSignature(hex);
419
+ const r = encoding.uint8ArrayToHexString(raw.slice(0, 32));
420
+ const s = encoding.uint8ArrayToHexString(raw.slice(32, 64));
421
+ // DER signatures do not have a v component
422
+ // so we return 00 to match what ZeroXKey does
423
+ const v = "00";
424
+ return { r, s, v };
425
+ }
426
+ if (addressFormat === "ADDRESS_FORMAT_SOLANA") {
427
+ if (hex.length !== 128) {
428
+ throw new Error(`Invalid Solana signature length: expected 64 bytes (128 hex), got ${hex.length}`);
429
+ }
430
+ // this is a Ed25519 signature
431
+ const r = hex.slice(0, 64);
432
+ const s = hex.slice(64, 128);
433
+ // solana signatures do not have a v component
434
+ // so we return 00 to match what ZeroXKey does
435
+ return { r, s, v: "00" };
436
+ }
437
+ throw new Error(`Unsupported address format or invalid signature length: ${hex.length}`);
438
+ }
439
+ // Type guard to check if accounts is WalletAccount[]
440
+ function isWalletAccountArray(arr) {
441
+ return (arr.length === 0 ||
442
+ (typeof arr[0] === "object" &&
443
+ "addressFormat" in arr[0] &&
444
+ "curve" in arr[0] &&
445
+ "path" in arr[0] &&
446
+ "pathFormat" in arr[0]));
447
+ }
448
+ function createWalletAccountFromAddressFormat(addressFormat) {
449
+ const walletAccount = addressFormatConfig[addressFormat]?.defaultAccounts;
450
+ if (!walletAccount) {
451
+ throw new Error(`Unsupported address format: ${addressFormat}`);
452
+ }
453
+ if (walletAccount[0]) {
454
+ return walletAccount[0];
455
+ }
456
+ throw new Error(`No default accounts defined for address format: ${addressFormat}`);
457
+ }
458
+ /**@internal */
459
+ function generateWalletAccountsFromAddressFormat(params) {
460
+ const { addresses, existingWalletAccounts } = params;
461
+ const pathMap = new Map();
462
+ // Build a lookup for max index per (addressFormat, basePath)
463
+ const maxIndexMap = new Map();
464
+ if (existingWalletAccounts && existingWalletAccounts.length > 0) {
465
+ for (const acc of existingWalletAccounts) {
466
+ // Normalize base path (remove account index)
467
+ const basePath = acc.path.replace(/^((?:[^\/]+\/){3})[^\/]+/, "$1");
468
+ const key = `${acc.addressFormat}:${basePath}`;
469
+ const idxSegment = acc.path.split("/")[3];
470
+ const idx = idxSegment ? parseInt(idxSegment.replace(/'/, ""), 10) : -1;
471
+ if (!isNaN(idx)) {
472
+ maxIndexMap.set(key, Math.max(maxIndexMap.get(key) ?? -1, idx));
473
+ }
474
+ }
475
+ }
476
+ return addresses.map((addressFormat) => {
477
+ const account = createWalletAccountFromAddressFormat(addressFormat);
478
+ const basePath = account.path.replace(/^((?:[^\/]+\/){3})[^\/]+/, "$1");
479
+ const key = `${addressFormat}:${basePath}`;
480
+ let nextIndex = 0;
481
+ if (maxIndexMap.has(key)) {
482
+ nextIndex = maxIndexMap.get(key) + 1;
483
+ maxIndexMap.set(key, nextIndex);
484
+ }
485
+ else if (pathMap.has(account.path)) {
486
+ nextIndex = pathMap.get(account.path);
487
+ }
488
+ const pathWithIndex = account.path.replace(/^((?:[^\/]*\/){3})(\d+)/, (_, prefix) => `${prefix}${nextIndex}`);
489
+ pathMap.set(account.path, nextIndex + 1);
490
+ return {
491
+ ...account,
492
+ path: pathWithIndex,
493
+ };
494
+ });
495
+ }
496
+ function buildSignUpBody(params) {
497
+ const { createSubOrgParams } = params;
498
+ const authenticatorName = isWeb()
499
+ ? `${window.location.hostname}-${Date.now()}`
500
+ : `passkey-${Date.now()}`;
501
+ let authenticators = [];
502
+ if (createSubOrgParams?.authenticators?.length) {
503
+ authenticators =
504
+ createSubOrgParams?.authenticators?.map((authenticator) => ({
505
+ authenticatorName: authenticator?.authenticatorName || authenticatorName,
506
+ challenge: authenticator.challenge,
507
+ attestation: authenticator.attestation,
508
+ })) || [];
509
+ }
510
+ let apiKeys = [];
511
+ if (createSubOrgParams?.apiKeys?.length) {
512
+ apiKeys = createSubOrgParams.apiKeys
513
+ .filter((apiKey) => apiKey.curveType !== undefined)
514
+ .map((apiKey) => ({
515
+ apiKeyName: apiKey.apiKeyName || `api-key-${Date.now()}`,
516
+ publicKey: apiKey.publicKey,
517
+ curveType: apiKey.curveType,
518
+ ...(apiKey?.expirationSeconds && {
519
+ expirationSeconds: apiKey.expirationSeconds,
520
+ }),
521
+ }));
522
+ }
523
+ return {
524
+ userName: createSubOrgParams?.userName ||
525
+ createSubOrgParams?.userEmail ||
526
+ `user-${Date.now()}`,
527
+ ...(createSubOrgParams?.userEmail && {
528
+ userEmail: createSubOrgParams?.userEmail,
529
+ }),
530
+ ...(createSubOrgParams?.authenticators?.length
531
+ ? {
532
+ authenticators,
533
+ }
534
+ : { authenticators: [] }),
535
+ ...(createSubOrgParams?.userPhoneNumber && {
536
+ userPhoneNumber: createSubOrgParams.userPhoneNumber,
537
+ }),
538
+ ...(createSubOrgParams?.userTag && {
539
+ userTag: createSubOrgParams?.userTag,
540
+ }),
541
+ organizationName: createSubOrgParams?.subOrgName || `sub-org-${Date.now()}`,
542
+ ...(createSubOrgParams?.verificationToken && {
543
+ verificationToken: createSubOrgParams?.verificationToken,
544
+ }),
545
+ ...(createSubOrgParams?.apiKeys?.length
546
+ ? {
547
+ apiKeys,
548
+ }
549
+ : { apiKeys: [] }),
550
+ ...(createSubOrgParams?.oauthProviders?.length
551
+ ? {
552
+ oauthProviders: createSubOrgParams.oauthProviders,
553
+ }
554
+ : { oauthProviders: [] }),
555
+ ...(createSubOrgParams?.customWallet && {
556
+ wallet: {
557
+ walletName: createSubOrgParams.customWallet.walletName,
558
+ accounts: createSubOrgParams.customWallet.walletAccounts,
559
+ },
560
+ }),
561
+ };
562
+ }
563
+ /**
564
+ * Extracts the public key from a ZeroXKey stamp header value.
565
+ * @param stampHeaderValue - The base64url encoded stamp header value
566
+ * @returns The public key as a hex string
567
+ */
568
+ function getPublicKeyFromStampHeader(stampHeaderValue) {
569
+ try {
570
+ // we decode the base64url string to get the JSON stamp
571
+ const stampJson = encoding.decodeBase64urlToString(stampHeaderValue);
572
+ // we parse the JSON to get the stamp object
573
+ const stamp = JSON.parse(stampJson);
574
+ return stamp.publicKey;
575
+ }
576
+ catch (error) {
577
+ throw new Error(`Failed to extract public key from stamp header: ${error instanceof Error ? error.message : String(error)}`);
578
+ }
579
+ }
580
+ /**@internal */
581
+ function getPolicySignature(policy) {
582
+ return JSON.stringify({
583
+ policyName: policy.policyName,
584
+ effect: policy.effect,
585
+ condition: policy.condition ?? null,
586
+ consensus: policy.consensus ?? null,
587
+ });
588
+ }
589
+ /**@internal */
590
+ function isEthereumProvider(provider) {
591
+ return provider.chainInfo.namespace === enums.Chain.Ethereum;
592
+ }
593
+ /**@internal */
594
+ function isSolanaProvider(provider) {
595
+ return provider.chainInfo.namespace === enums.Chain.Solana;
596
+ }
597
+ /** @internal */
598
+ function getCurveTypeFromProvider(provider) {
599
+ if (isEthereumProvider(provider)) {
600
+ return "API_KEY_CURVE_SECP256K1";
601
+ }
602
+ if (isSolanaProvider(provider)) {
603
+ return "API_KEY_CURVE_ED25519";
604
+ }
605
+ // we should never hit this case
606
+ // if we do then it means we added support for a new chain but missed updating this function
607
+ throw new Error(`Unsupported provider namespace: ${provider.chainInfo.namespace}. Expected Ethereum or Solana.`);
608
+ }
609
+ /** @internal */
610
+ function getSignatureSchemeFromProvider(provider) {
611
+ if (isEthereumProvider(provider)) {
612
+ return "SIGNATURE_SCHEME_TK_API_SECP256K1_EIP191";
613
+ }
614
+ if (isSolanaProvider(provider)) {
615
+ return "SIGNATURE_SCHEME_TK_API_ED25519";
616
+ }
617
+ // we should never hit this case
618
+ // if we do then it means we added support for a new chain but missed updating this function
619
+ throw new Error(`Unsupported provider namespace: ${provider.chainInfo.namespace}. Expected Ethereum or Solana.`);
620
+ }
621
+ /** @internal */
622
+ function findWalletProviderFromAddress(address, providers) {
623
+ for (const provider of providers) {
624
+ if (provider.connectedAddresses.includes(address)) {
625
+ return provider;
626
+ }
627
+ }
628
+ // no provider found for that address
629
+ return undefined;
630
+ }
631
+ /**
632
+ * Derives a wallet address from a given public key and chain.
633
+ *
634
+ * @param chain - "ethereum" or "solana"
635
+ * @param publicKey - The raw public key string (can be compressed or uncompressed)
636
+ * @returns The derived wallet address
637
+ */
638
+ function addressFromPublicKey(chain, publicKey) {
639
+ if (chain === enums.Chain.Ethereum) {
640
+ const publicKeyBytes = encoding.uint8ArrayFromHexString(publicKey);
641
+ let uncompressedKey;
642
+ if (publicKeyBytes.length === 65 && publicKeyBytes[0] === 0x04) {
643
+ // it's already uncompressed so we just convert
644
+ // to hex without the 04 prefix
645
+ uncompressedKey = encoding.uint8ArrayToHexString(publicKeyBytes.slice(1));
646
+ }
647
+ else {
648
+ // it's compressed, so we need to uncompress it first
649
+ // then convert to hex without the 04 prefix
650
+ const publicKeyUncompressed = crypto$1.uncompressRawPublicKey(publicKeyBytes, enums.Curve.SECP256K1);
651
+ uncompressedKey = encoding.uint8ArrayToHexString(publicKeyUncompressed.slice(1));
652
+ }
653
+ // hash with Keccak256 and take last 20 bytes
654
+ const hash = ethers.keccak256(encoding.uint8ArrayFromHexString(uncompressedKey));
655
+ return "0x" + hash.slice(-40);
656
+ }
657
+ if (chain === enums.Chain.Solana) {
658
+ return encoding.bs58.encode(encoding.uint8ArrayFromHexString(publicKey));
659
+ }
660
+ throw new Error(`Unsupported chain: ${chain}`);
661
+ }
662
+ /**@internal */
663
+ function getAuthenticatorAddresses(user) {
664
+ const ethereum = [];
665
+ const solana = [];
666
+ for (const key of user.apiKeys) {
667
+ const { type, publicKey } = key.credential;
668
+ switch (type) {
669
+ case "CREDENTIAL_TYPE_API_KEY_SECP256K1":
670
+ ethereum.push(addressFromPublicKey(enums.Chain.Ethereum, publicKey));
671
+ break;
672
+ case "CREDENTIAL_TYPE_API_KEY_ED25519":
673
+ solana.push(addressFromPublicKey(enums.Chain.Solana, publicKey));
674
+ break;
675
+ }
676
+ }
677
+ return { ethereum, solana };
678
+ }
679
+ /**@internal */
680
+ async function getAuthProxyConfig(authProxyConfigId, authProxyUrl) {
681
+ const fullUrl = (authProxyUrl ?? "https://authproxy.0xkey.com") + "/v1/wallet_kit_config";
682
+ var headers = {
683
+ "Content-Type": "application/json",
684
+ "X-Auth-Proxy-Config-ID": authProxyConfigId,
685
+ };
686
+ const response = await fetch(fullUrl, {
687
+ method: "POST",
688
+ headers: headers,
689
+ });
690
+ if (!response.ok) {
691
+ let res;
692
+ try {
693
+ res = await response.json();
694
+ }
695
+ catch (_) {
696
+ throw new Error(`${response.status} ${response.statusText}`);
697
+ }
698
+ throw new error.ZeroXKeyRequestError(res);
699
+ }
700
+ const data = await response.json();
701
+ return data;
702
+ }
703
+ /**
704
+ * Submits a signed request to ZeroXKey.
705
+ *
706
+ * You can pass in the SignedRequest returned by any of the SDK's
707
+ * stamping methods (stampStampLogin, stampGetPolicies, etc.).
708
+ *
709
+ * @deprecated Use `httpClient.sendSignedRequest()` instead, which includes
710
+ * automatic activity polling and result extraction.
711
+ *
712
+ * @param signedRequest A SignedRequest object returned by a stamping method.
713
+ * @returns The parsed JSON response from ZeroXKey.
714
+ * @throws ZeroXKeyNetworkError if the request fails.
715
+ */
716
+ // TODO: (breaking change) remove this function
717
+ async function sendSignedRequest(signedRequest) {
718
+ const headers = {
719
+ "Content-Type": "application/json",
720
+ "X-Client-Version": version.VERSION,
721
+ [signedRequest.stamp.stampHeaderName]: signedRequest.stamp.stampHeaderValue,
722
+ };
723
+ const res = await fetch(signedRequest.url, {
724
+ method: "POST",
725
+ headers,
726
+ body: signedRequest.body,
727
+ });
728
+ if (!res.ok) {
729
+ const errorText = await res.text();
730
+ throw new sdkTypes.ZeroXKeyNetworkError("Signed request failed", res.status, sdkTypes.ZeroXKeyErrorCodes.BAD_RESPONSE, errorText);
731
+ }
732
+ return res.json();
733
+ }
734
+ /**
735
+ * @internal
736
+ * Executes an async function with error handling.
737
+ *
738
+ * @param fn The async function to execute with error handling
739
+ * @param errorOptions Options for customizing error handling
740
+ * @param errorOptions.catchFn Optional function to execute in the catch block
741
+ * @param errorOptions.errorMessage The default error message to use if no custom message is found
742
+ * @param errorOptions.errorCode The default error code to use if no custom message is found
743
+ * @param errorOptions.customErrorsByCodes Optional mapping of error codes to custom messages, if you're trying to target a specific error code and surface a custom message, use this
744
+ * @param errorOptions.customErrorsByMessages Optional mapping of error messages to custom messages, if you're trying to target a specific error message and surface a custom message, use this
745
+ * @param finallyFn Optional function to execute in the finally block
746
+ * @returns The result of the async function or throws an error
747
+ */
748
+ async function withZeroXKeyErrorHandling(fn, catchOptions, finallyOptions) {
749
+ const { errorMessage, errorCode, customErrorsByCodes, catchFn } = catchOptions;
750
+ // Merge global error mappings with any caller-provided ones.
751
+ // - Start with the globals so they’re always available.
752
+ // - Spread the caller’s entries last so they override globals on conflicts.
753
+ // - If the caller didn’t provide any, just fall back to the globals.
754
+ const customErrorsByMessages = catchOptions.customErrorsByMessages
755
+ ? { ...globalErrorsToMatch, ...catchOptions.customErrorsByMessages }
756
+ : globalErrorsToMatch;
757
+ const finallyFn = finallyOptions?.finallyFn;
758
+ try {
759
+ return await fn();
760
+ }
761
+ catch (error$1) {
762
+ await catchFn?.();
763
+ // some things throw plain objects (not Error instances), which would stringify as `[object Object]`
764
+ // we normalize here to always produce a readable error message before wrapping it in ZeroXKeyError.
765
+ const normalizedMessage = error$1 instanceof Error && typeof error$1.message === "string"
766
+ ? error$1.message
767
+ : typeof error$1?.message === "string"
768
+ ? error$1.message
769
+ : JSON.stringify(error$1);
770
+ if (error$1 instanceof sdkTypes.ZeroXKeyError) {
771
+ const customCodeMessage = customErrorsByCodes?.[error$1.code];
772
+ if (customCodeMessage) {
773
+ throw new sdkTypes.ZeroXKeyError(customCodeMessage.message, customCodeMessage.code, error$1);
774
+ }
775
+ throwMatchingMessage(error$1.message, customErrorsByMessages, error$1);
776
+ throw error$1;
777
+ }
778
+ else if (error$1 instanceof error.ZeroXKeyRequestError) {
779
+ throwMatchingMessage(normalizedMessage, customErrorsByMessages, error$1);
780
+ throw new sdkTypes.ZeroXKeyError(errorMessage, errorCode, error$1);
781
+ }
782
+ else if (error$1 instanceof Error) {
783
+ throwMatchingMessage(normalizedMessage, customErrorsByMessages, error$1);
784
+ // Wrap other errors in a ZeroXKeyError
785
+ throw new sdkTypes.ZeroXKeyError(errorMessage, errorCode, error$1);
786
+ }
787
+ else {
788
+ throwMatchingMessage(normalizedMessage, customErrorsByMessages, error$1);
789
+ // Handle non-Error exceptions
790
+ throw new sdkTypes.ZeroXKeyError(normalizedMessage, errorCode, error$1);
791
+ }
792
+ }
793
+ finally {
794
+ await finallyFn?.();
795
+ }
796
+ }
797
+ /**
798
+ * Throws a ZeroXKeyError with a custom message if the error message matches any key in customMessageByMessages.
799
+ * If no match is found, it does nothing.
800
+ *
801
+ * @param errorMessage The error message to check against the custom messages.
802
+ * @param customErrorsByMessages An object mapping error messages to custom messages and codes.
803
+ * @param error The original error that triggered this function.
804
+ */
805
+ const throwMatchingMessage = (errorMessage, customErrorsByMessages, error) => {
806
+ if (customErrorsByMessages &&
807
+ Object.keys(customErrorsByMessages).length > 0) {
808
+ Object.keys(customErrorsByMessages).forEach((key) => {
809
+ if (errorMessage.includes(key)) {
810
+ throw new sdkTypes.ZeroXKeyError(customErrorsByMessages[key].message, customErrorsByMessages[key].code, error);
811
+ }
812
+ });
813
+ }
814
+ };
815
+ /**
816
+ * @internal
817
+ *
818
+ * Asserts that the provided key pair is a valid P-256 ECDSA key pair.
819
+ * @param pair The key pair to validate.
820
+ */
821
+ async function assertValidP256ECDSAKeyPair(pair) {
822
+ const { privateKey, publicKey } = pair;
823
+ // Check basic shape
824
+ if (!(privateKey instanceof CryptoKey) || !(publicKey instanceof CryptoKey)) {
825
+ throw new sdkTypes.ZeroXKeyError("Both keys must be CryptoKey instances.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
826
+ }
827
+ if (privateKey.type !== "private")
828
+ throw new sdkTypes.ZeroXKeyError("privateKey.type must be 'private'.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
829
+ if (publicKey.type !== "public")
830
+ throw new sdkTypes.ZeroXKeyError("publicKey.type must be 'public'.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
831
+ // Verify extractability and usages
832
+ if (privateKey.extractable !== false) {
833
+ throw new sdkTypes.ZeroXKeyError("Provided privateKey must be non-extractable.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
834
+ }
835
+ if (!privateKey.usages.includes("sign")) {
836
+ throw new sdkTypes.ZeroXKeyError("privateKey must have 'sign' in keyUsages.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
837
+ }
838
+ if (!publicKey.usages.includes("verify")) {
839
+ throw new sdkTypes.ZeroXKeyError("publicKey must have 'verify' in keyUsages.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
840
+ }
841
+ // Algorithm checks (must be ECDSA on P-256)
842
+ const pAlg = privateKey.algorithm;
843
+ const pubAlg = publicKey.algorithm;
844
+ if (pAlg.name !== "ECDSA" || pubAlg.name !== "ECDSA") {
845
+ throw new sdkTypes.ZeroXKeyError("Keys must be ECDSA keys.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
846
+ }
847
+ if (pAlg.namedCurve !== "P-256" || pubAlg.namedCurve !== "P-256") {
848
+ throw new sdkTypes.ZeroXKeyError("Keys must be on the P-256 curve.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
849
+ }
850
+ // Public key export sanity (should be uncompressed 65 bytes starting with 0x04)
851
+ const rawPub = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
852
+ if (rawPub.length !== 65 || rawPub[0] !== 0x04) {
853
+ throw new sdkTypes.ZeroXKeyError("Public key must be an uncompressed P-256 point (65 bytes, leading 0x04).", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
854
+ }
855
+ // Prove the pair matches: sign→verify a test message
856
+ const msg = crypto.getRandomValues(new Uint8Array(32));
857
+ const sig = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, privateKey, msg);
858
+ const ok = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, publicKey, sig, msg);
859
+ if (!ok) {
860
+ throw new sdkTypes.ZeroXKeyError("publicKey does not match privateKey (verify failed).", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
861
+ }
862
+ }
863
+ function isValidPasskeyName(name) {
864
+ const nameRegex = isReactNative()
865
+ ? /^[a-zA-Z0-9 _\-:\/\.]{1,64}$/
866
+ : /^[a-zA-Z0-9 _\-:\/\.]+$/;
867
+ if (!nameRegex.test(name)) {
868
+ throw new sdkTypes.ZeroXKeyError("Passkey name must be 1-64 characters and only contain letters, numbers, spaces, dashes, underscores, colons, or slashes.", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
869
+ }
870
+ return name;
871
+ }
872
+ function mapAccountsToWallet(accounts, walletMap) {
873
+ // map of walletId to Wallet
874
+ // map all wallet accounts to their wallets
875
+ accounts.forEach(async (account) => {
876
+ if (walletMap.has(account.walletDetails.walletId)) {
877
+ const wallet = walletMap.get(account.walletDetails.walletId);
878
+ wallet.accounts.push({
879
+ ...account,
880
+ source: enums.WalletSource.Embedded,
881
+ });
882
+ return;
883
+ }
884
+ else {
885
+ walletMap.set(account.walletDetails.walletId, {
886
+ source: enums.WalletSource.Embedded,
887
+ walletId: account.walletDetails.walletId,
888
+ walletName: account.walletDetails.walletName,
889
+ createdAt: account.walletDetails.createdAt,
890
+ updatedAt: account.walletDetails.updatedAt,
891
+ exported: account.walletDetails.exported,
892
+ imported: account.walletDetails.imported,
893
+ accounts: [
894
+ {
895
+ ...account,
896
+ source: enums.WalletSource.Embedded,
897
+ },
898
+ ],
899
+ });
900
+ }
901
+ });
902
+ return Array.from(walletMap.values());
903
+ }
904
+ async function withTimeout(promise, ms, label) {
905
+ let timeout;
906
+ const timer = new Promise((_, reject) => {
907
+ timeout = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
908
+ });
909
+ return Promise.race([promise, timer]).finally(() => clearTimeout(timeout));
910
+ }
911
+ async function fetchAllWalletAccountsWithCursor(httpClient, organizationId, stampWith) {
912
+ let hasMore = true;
913
+ let cursor;
914
+ const accounts = [];
915
+ const limit = 100;
916
+ while (hasMore) {
917
+ const response = await httpClient.getWalletAccounts({
918
+ organizationId,
919
+ includeWalletDetails: true,
920
+ paginationOptions: {
921
+ limit: limit.toString(),
922
+ ...(cursor && { after: cursor }),
923
+ },
924
+ }, stampWith);
925
+ if (!response || !response.accounts) {
926
+ throw new sdkTypes.ZeroXKeyError("No wallet accounts found in the response", sdkTypes.ZeroXKeyErrorCodes.BAD_RESPONSE);
927
+ }
928
+ accounts.push(...response.accounts);
929
+ hasMore = response.accounts.length === limit;
930
+ cursor =
931
+ response.accounts && response.accounts.length > 0
932
+ ? response.accounts[response.accounts.length - 1]?.walletAccountId
933
+ : undefined;
934
+ }
935
+ return accounts;
936
+ }
937
+ function decodeVerificationToken(verificationToken) {
938
+ const [, payloadB64] = verificationToken.split(".");
939
+ if (!payloadB64) {
940
+ throw new Error("Invalid token: missing payload");
941
+ }
942
+ const json = atob(payloadB64);
943
+ return JSON.parse(json);
944
+ }
945
+ function getClientSignatureMessageForLogin({ verificationToken, sessionPublicKey = undefined, }) {
946
+ try {
947
+ const decoded = decodeVerificationToken(verificationToken);
948
+ if (!decoded.public_key)
949
+ throw new sdkTypes.ZeroXKeyError("Invalid verification token: missing publicKey", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
950
+ const verificationPublicKey = decoded.public_key;
951
+ // if a session public key is provided, we use it instead
952
+ const resolvedSessionPublicKey = sessionPublicKey || verificationPublicKey;
953
+ const usage = { publicKey: resolvedSessionPublicKey };
954
+ const payload = {
955
+ login: usage,
956
+ tokenId: decoded.id,
957
+ type: "USAGE_TYPE_LOGIN",
958
+ };
959
+ const json = JSON.stringify(payload);
960
+ return { message: json, publicKey: verificationPublicKey };
961
+ }
962
+ catch (error) {
963
+ throw new sdkTypes.ZeroXKeyError("Failed to create client signature bundle for login", sdkTypes.ZeroXKeyErrorCodes.UNKNOWN, error);
964
+ }
965
+ }
966
+ function getClientSignatureMessageForSignup({ verificationToken, email, phoneNumber, apiKeys, authenticators, oauthProviders, }) {
967
+ try {
968
+ const decoded = decodeVerificationToken(verificationToken);
969
+ if (!decoded.public_key)
970
+ throw new sdkTypes.ZeroXKeyError("Invalid verification token: missing publicKey", sdkTypes.ZeroXKeyErrorCodes.INVALID_REQUEST);
971
+ const verificationPublicKey = decoded.public_key;
972
+ const usage = {
973
+ ...(apiKeys ? { apiKeys } : {}),
974
+ ...(authenticators ? { authenticators } : {}),
975
+ ...(oauthProviders ? { oauthProviders } : {}),
976
+ ...(email ? { email } : {}),
977
+ ...(phoneNumber ? { phoneNumber } : {}),
978
+ };
979
+ const payload = {
980
+ signup: usage,
981
+ tokenId: decoded.id,
982
+ type: "USAGE_TYPE_SIGNUP",
983
+ };
984
+ const json = JSON.stringify(payload);
985
+ return { message: json, publicKey: verificationPublicKey };
986
+ }
987
+ catch (error) {
988
+ throw new sdkTypes.ZeroXKeyError("Failed to create client signature bundle for signup", sdkTypes.ZeroXKeyErrorCodes.UNKNOWN, error);
989
+ }
990
+ }
991
+ /**
992
+ * Wraps a promise with a timeout. If the promise doesn't resolve within
993
+ * the specified duration, it resolves to the fallback value instead of throwing.
994
+ *
995
+ * @param promise - The promise to wrap.
996
+ * @param fallback - Value to return if the timeout is reached.
997
+ * @param timeoutMs - Timeout duration in milliseconds. Defaults to 1000ms.
998
+ * @returns The result of the promise, or the fallback if timed out.
999
+ */
1000
+ const withTimeoutFallback = (promise, fallback, timeoutMs) => {
1001
+ const timeout = 1000;
1002
+ return Promise.race([
1003
+ promise,
1004
+ new Promise((resolve) => setTimeout(() => resolve(fallback), timeout)),
1005
+ ]);
1006
+ };
1007
+
1008
+ exports.addressFormatConfig = addressFormatConfig;
1009
+ exports.addressFromPublicKey = addressFromPublicKey;
1010
+ exports.assertValidP256ECDSAKeyPair = assertValidP256ECDSAKeyPair;
1011
+ exports.broadcastTransaction = broadcastTransaction;
1012
+ exports.buildSignUpBody = buildSignUpBody;
1013
+ exports.createWalletAccountFromAddressFormat = createWalletAccountFromAddressFormat;
1014
+ exports.decodeVerificationToken = decodeVerificationToken;
1015
+ exports.fetchAllWalletAccountsWithCursor = fetchAllWalletAccountsWithCursor;
1016
+ exports.findWalletProviderFromAddress = findWalletProviderFromAddress;
1017
+ exports.generateRandomBuffer = generateRandomBuffer;
1018
+ exports.generateWalletAccountsFromAddressFormat = generateWalletAccountsFromAddressFormat;
1019
+ exports.getActiveSessionOrThrowIfRequired = getActiveSessionOrThrowIfRequired;
1020
+ exports.getAuthProxyConfig = getAuthProxyConfig;
1021
+ exports.getAuthenticatorAddresses = getAuthenticatorAddresses;
1022
+ exports.getClientSignatureMessageForLogin = getClientSignatureMessageForLogin;
1023
+ exports.getClientSignatureMessageForSignup = getClientSignatureMessageForSignup;
1024
+ exports.getCurveTypeFromProvider = getCurveTypeFromProvider;
1025
+ exports.getEncodedMessage = getEncodedMessage;
1026
+ exports.getEncodingType = getEncodingType;
1027
+ exports.getHashFunction = getHashFunction;
1028
+ exports.getPolicySignature = getPolicySignature;
1029
+ exports.getPublicKeyFromStampHeader = getPublicKeyFromStampHeader;
1030
+ exports.getSignatureSchemeFromProvider = getSignatureSchemeFromProvider;
1031
+ exports.googleISS = googleISS;
1032
+ exports.hexSignedTxToBase58 = hexSignedTxToBase58;
1033
+ exports.isEthereumProvider = isEthereumProvider;
1034
+ exports.isReactNative = isReactNative;
1035
+ exports.isSolanaProvider = isSolanaProvider;
1036
+ exports.isValidPasskeyName = isValidPasskeyName;
1037
+ exports.isWalletAccountArray = isWalletAccountArray;
1038
+ exports.isWeb = isWeb;
1039
+ exports.mapAccountsToWallet = mapAccountsToWallet;
1040
+ exports.parseSession = parseSession;
1041
+ exports.sendSignedRequest = sendSignedRequest;
1042
+ exports.splitSignature = splitSignature;
1043
+ exports.toExternalTimestamp = toExternalTimestamp;
1044
+ exports.withTimeout = withTimeout;
1045
+ exports.withTimeoutFallback = withTimeoutFallback;
1046
+ exports.withZeroXKeyErrorHandling = withZeroXKeyErrorHandling;
1047
+ //# sourceMappingURL=utils.js.map