@spacesops/wdk-react-native-core 1.0.0-beta.40

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 (275) hide show
  1. package/README.md +551 -0
  2. package/dist/__mocks__/react.d.ts +40 -0
  3. package/dist/__mocks__/react.js +33 -0
  4. package/dist/__mocks__/react.js.map +1 -0
  5. package/dist/__mocks__/secureStorage.d.ts +26 -0
  6. package/dist/__mocks__/secureStorage.js +80 -0
  7. package/dist/__mocks__/secureStorage.js.map +1 -0
  8. package/dist/__tests__/hooks/useBalance.test.d.ts +6 -0
  9. package/dist/__tests__/hooks/useBalance.test.js +217 -0
  10. package/dist/__tests__/hooks/useBalance.test.js.map +1 -0
  11. package/dist/__tests__/hooks/useWallet.test.d.ts +6 -0
  12. package/dist/__tests__/hooks/useWallet.test.js +105 -0
  13. package/dist/__tests__/hooks/useWallet.test.js.map +1 -0
  14. package/dist/__tests__/hooks/useWalletManager.test.d.ts +6 -0
  15. package/dist/__tests__/hooks/useWalletManager.test.js +193 -0
  16. package/dist/__tests__/hooks/useWalletManager.test.js.map +1 -0
  17. package/dist/__tests__/hooks/useWdkApp.test.d.ts +6 -0
  18. package/dist/__tests__/hooks/useWdkApp.test.js +55 -0
  19. package/dist/__tests__/hooks/useWdkApp.test.js.map +1 -0
  20. package/dist/__tests__/hooks/useWorklet.test.d.ts +6 -0
  21. package/dist/__tests__/hooks/useWorklet.test.js +168 -0
  22. package/dist/__tests__/hooks/useWorklet.test.js.map +1 -0
  23. package/dist/__tests__/provider/WdkAppProvider.test.d.ts +6 -0
  24. package/dist/__tests__/provider/WdkAppProvider.test.js +57 -0
  25. package/dist/__tests__/provider/WdkAppProvider.test.js.map +1 -0
  26. package/dist/__tests__/services/accountService.test.d.ts +6 -0
  27. package/dist/__tests__/services/accountService.test.js +216 -0
  28. package/dist/__tests__/services/accountService.test.js.map +1 -0
  29. package/dist/__tests__/services/addressService.test.d.ts +6 -0
  30. package/dist/__tests__/services/addressService.test.js +246 -0
  31. package/dist/__tests__/services/addressService.test.js.map +1 -0
  32. package/dist/__tests__/services/balanceService.test.d.ts +6 -0
  33. package/dist/__tests__/services/balanceService.test.js +333 -0
  34. package/dist/__tests__/services/balanceService.test.js.map +1 -0
  35. package/dist/__tests__/services/walletSetupService.test.d.ts +6 -0
  36. package/dist/__tests__/services/walletSetupService.test.js +304 -0
  37. package/dist/__tests__/services/walletSetupService.test.js.map +1 -0
  38. package/dist/__tests__/services/walletSwitchingService.test.d.ts +6 -0
  39. package/dist/__tests__/services/walletSwitchingService.test.js +209 -0
  40. package/dist/__tests__/services/walletSwitchingService.test.js.map +1 -0
  41. package/dist/__tests__/services/workletLifecycleService.test.d.ts +6 -0
  42. package/dist/__tests__/services/workletLifecycleService.test.js +451 -0
  43. package/dist/__tests__/services/workletLifecycleService.test.js.map +1 -0
  44. package/dist/__tests__/setup.d.ts +7 -0
  45. package/dist/__tests__/setup.js +49 -0
  46. package/dist/__tests__/setup.js.map +1 -0
  47. package/dist/__tests__/storage/mmkvStorage.test.d.ts +6 -0
  48. package/dist/__tests__/storage/mmkvStorage.test.js +213 -0
  49. package/dist/__tests__/storage/mmkvStorage.test.js.map +1 -0
  50. package/dist/__tests__/store/walletStore.test.d.ts +4 -0
  51. package/dist/__tests__/store/walletStore.test.js +86 -0
  52. package/dist/__tests__/store/walletStore.test.js.map +1 -0
  53. package/dist/__tests__/store/workletStore.test.d.ts +4 -0
  54. package/dist/__tests__/store/workletStore.test.js +255 -0
  55. package/dist/__tests__/store/workletStore.test.js.map +1 -0
  56. package/dist/__tests__/types/hrpc.test.d.ts +4 -0
  57. package/dist/__tests__/types/hrpc.test.js +99 -0
  58. package/dist/__tests__/types/hrpc.test.js.map +1 -0
  59. package/dist/__tests__/utils/balanceUtils.test.d.ts +4 -0
  60. package/dist/__tests__/utils/balanceUtils.test.js +133 -0
  61. package/dist/__tests__/utils/balanceUtils.test.js.map +1 -0
  62. package/dist/__tests__/utils/errorHandling.test.d.ts +6 -0
  63. package/dist/__tests__/utils/errorHandling.test.js +119 -0
  64. package/dist/__tests__/utils/errorHandling.test.js.map +1 -0
  65. package/dist/__tests__/utils/errorUtils.test.d.ts +4 -0
  66. package/dist/__tests__/utils/errorUtils.test.js +133 -0
  67. package/dist/__tests__/utils/errorUtils.test.js.map +1 -0
  68. package/dist/__tests__/utils/initializationState.test.d.ts +6 -0
  69. package/dist/__tests__/utils/initializationState.test.js +243 -0
  70. package/dist/__tests__/utils/initializationState.test.js.map +1 -0
  71. package/dist/__tests__/utils/jsonUtils.test.d.ts +4 -0
  72. package/dist/__tests__/utils/jsonUtils.test.js +118 -0
  73. package/dist/__tests__/utils/jsonUtils.test.js.map +1 -0
  74. package/dist/__tests__/utils/mmkvKeyManager.test.d.ts +6 -0
  75. package/dist/__tests__/utils/mmkvKeyManager.test.js +158 -0
  76. package/dist/__tests__/utils/mmkvKeyManager.test.js.map +1 -0
  77. package/dist/__tests__/utils/mnemonicUtils.test.d.ts +4 -0
  78. package/dist/__tests__/utils/mnemonicUtils.test.js +40 -0
  79. package/dist/__tests__/utils/mnemonicUtils.test.js.map +1 -0
  80. package/dist/__tests__/utils/raceConditions.test.d.ts +6 -0
  81. package/dist/__tests__/utils/raceConditions.test.js +239 -0
  82. package/dist/__tests__/utils/raceConditions.test.js.map +1 -0
  83. package/dist/__tests__/utils/result.test.d.ts +4 -0
  84. package/dist/__tests__/utils/result.test.js +66 -0
  85. package/dist/__tests__/utils/result.test.js.map +1 -0
  86. package/dist/__tests__/utils/schemas.test.d.ts +4 -0
  87. package/dist/__tests__/utils/schemas.test.js +66 -0
  88. package/dist/__tests__/utils/schemas.test.js.map +1 -0
  89. package/dist/__tests__/utils/storeHelpers.test.d.ts +4 -0
  90. package/dist/__tests__/utils/storeHelpers.test.js +227 -0
  91. package/dist/__tests__/utils/storeHelpers.test.js.map +1 -0
  92. package/dist/__tests__/utils/typeGuards.test.d.ts +4 -0
  93. package/dist/__tests__/utils/typeGuards.test.js +175 -0
  94. package/dist/__tests__/utils/typeGuards.test.js.map +1 -0
  95. package/dist/__tests__/utils/validation.test.d.ts +4 -0
  96. package/dist/__tests__/utils/validation.test.js +126 -0
  97. package/dist/__tests__/utils/validation.test.js.map +1 -0
  98. package/dist/__tests__/utils/walletUtils.test.d.ts +4 -0
  99. package/dist/__tests__/utils/walletUtils.test.js +156 -0
  100. package/dist/__tests__/utils/walletUtils.test.js.map +1 -0
  101. package/dist/hooks/useBalance.d.ts +170 -0
  102. package/dist/hooks/useBalance.js +442 -0
  103. package/dist/hooks/useBalance.js.map +1 -0
  104. package/dist/hooks/useWallet.d.ts +43 -0
  105. package/dist/hooks/useWallet.js +193 -0
  106. package/dist/hooks/useWallet.js.map +1 -0
  107. package/dist/hooks/useWalletManager.d.ts +100 -0
  108. package/dist/hooks/useWalletManager.js +526 -0
  109. package/dist/hooks/useWalletManager.js.map +1 -0
  110. package/dist/hooks/useWdkApp.d.ts +66 -0
  111. package/dist/hooks/useWdkApp.js +74 -0
  112. package/dist/hooks/useWdkApp.js.map +1 -0
  113. package/dist/hooks/useWorklet.d.ts +66 -0
  114. package/dist/hooks/useWorklet.js +42 -0
  115. package/dist/hooks/useWorklet.js.map +1 -0
  116. package/dist/index.d.ts +33 -0
  117. package/dist/index.js +36 -0
  118. package/dist/index.js.map +1 -0
  119. package/dist/provider/WdkAppProvider.d.ts +112 -0
  120. package/dist/provider/WdkAppProvider.js +558 -0
  121. package/dist/provider/WdkAppProvider.js.map +1 -0
  122. package/dist/services/accountService.d.ts +52 -0
  123. package/dist/services/accountService.js +119 -0
  124. package/dist/services/accountService.js.map +1 -0
  125. package/dist/services/addressService.d.ts +22 -0
  126. package/dist/services/addressService.js +110 -0
  127. package/dist/services/addressService.js.map +1 -0
  128. package/dist/services/balanceService.d.ts +114 -0
  129. package/dist/services/balanceService.js +208 -0
  130. package/dist/services/balanceService.js.map +1 -0
  131. package/dist/services/walletSetupService.d.ts +217 -0
  132. package/dist/services/walletSetupService.js +535 -0
  133. package/dist/services/walletSetupService.js.map +1 -0
  134. package/dist/services/walletSwitchingService.d.ts +48 -0
  135. package/dist/services/walletSwitchingService.js +143 -0
  136. package/dist/services/walletSwitchingService.js.map +1 -0
  137. package/dist/services/workletLifecycleService.d.ts +117 -0
  138. package/dist/services/workletLifecycleService.js +433 -0
  139. package/dist/services/workletLifecycleService.js.map +1 -0
  140. package/dist/storage/mmkvStorage.d.ts +44 -0
  141. package/dist/storage/mmkvStorage.js +348 -0
  142. package/dist/storage/mmkvStorage.js.map +1 -0
  143. package/dist/store/walletStore.d.ts +130 -0
  144. package/dist/store/walletStore.js +204 -0
  145. package/dist/store/walletStore.js.map +1 -0
  146. package/dist/store/workletStore.d.ts +121 -0
  147. package/dist/store/workletStore.js +256 -0
  148. package/dist/store/workletStore.js.map +1 -0
  149. package/dist/types/hrpc.d.ts +60 -0
  150. package/dist/types/hrpc.js +26 -0
  151. package/dist/types/hrpc.js.map +1 -0
  152. package/dist/types.d.ts +168 -0
  153. package/dist/types.js +7 -0
  154. package/dist/types.js.map +1 -0
  155. package/dist/utils/balanceUtils.d.ts +30 -0
  156. package/dist/utils/balanceUtils.js +86 -0
  157. package/dist/utils/balanceUtils.js.map +1 -0
  158. package/dist/utils/constants.d.ts +66 -0
  159. package/dist/utils/constants.js +73 -0
  160. package/dist/utils/constants.js.map +1 -0
  161. package/dist/utils/errorHandling.d.ts +47 -0
  162. package/dist/utils/errorHandling.js +54 -0
  163. package/dist/utils/errorHandling.js.map +1 -0
  164. package/dist/utils/errorUtils.d.ts +89 -0
  165. package/dist/utils/errorUtils.js +264 -0
  166. package/dist/utils/errorUtils.js.map +1 -0
  167. package/dist/utils/initializationState.d.ts +129 -0
  168. package/dist/utils/initializationState.js +220 -0
  169. package/dist/utils/initializationState.js.map +1 -0
  170. package/dist/utils/jsonUtils.d.ts +21 -0
  171. package/dist/utils/jsonUtils.js +67 -0
  172. package/dist/utils/jsonUtils.js.map +1 -0
  173. package/dist/utils/logger.d.ts +27 -0
  174. package/dist/utils/logger.js +50 -0
  175. package/dist/utils/logger.js.map +1 -0
  176. package/dist/utils/mmkvKeyManager.d.ts +57 -0
  177. package/dist/utils/mmkvKeyManager.js +214 -0
  178. package/dist/utils/mmkvKeyManager.js.map +1 -0
  179. package/dist/utils/mnemonicUtils.d.ts +17 -0
  180. package/dist/utils/mnemonicUtils.js +28 -0
  181. package/dist/utils/mnemonicUtils.js.map +1 -0
  182. package/dist/utils/operationMutex.d.ts +69 -0
  183. package/dist/utils/operationMutex.js +150 -0
  184. package/dist/utils/operationMutex.js.map +1 -0
  185. package/dist/utils/result.d.ts +34 -0
  186. package/dist/utils/result.js +43 -0
  187. package/dist/utils/result.js.map +1 -0
  188. package/dist/utils/schemas.d.ts +365 -0
  189. package/dist/utils/schemas.js +152 -0
  190. package/dist/utils/schemas.js.map +1 -0
  191. package/dist/utils/storeHelpers.d.ts +112 -0
  192. package/dist/utils/storeHelpers.js +198 -0
  193. package/dist/utils/storeHelpers.js.map +1 -0
  194. package/dist/utils/typeGuards.d.ts +70 -0
  195. package/dist/utils/typeGuards.js +95 -0
  196. package/dist/utils/typeGuards.js.map +1 -0
  197. package/dist/utils/validation.d.ts +53 -0
  198. package/dist/utils/validation.js +152 -0
  199. package/dist/utils/validation.js.map +1 -0
  200. package/dist/utils/walletStateHelpers.d.ts +62 -0
  201. package/dist/utils/walletStateHelpers.js +81 -0
  202. package/dist/utils/walletStateHelpers.js.map +1 -0
  203. package/dist/utils/walletUtils.d.ts +38 -0
  204. package/dist/utils/walletUtils.js +87 -0
  205. package/dist/utils/walletUtils.js.map +1 -0
  206. package/package.json +79 -0
  207. package/src/__mocks__/react.ts +34 -0
  208. package/src/__mocks__/secureStorage.ts +87 -0
  209. package/src/__tests__/hooks/useBalance.test.ts +286 -0
  210. package/src/__tests__/hooks/useWallet.test.ts +122 -0
  211. package/src/__tests__/hooks/useWalletManager.test.ts +271 -0
  212. package/src/__tests__/hooks/useWdkApp.test.tsx +59 -0
  213. package/src/__tests__/hooks/useWorklet.test.ts +195 -0
  214. package/src/__tests__/provider/WdkAppProvider.test.tsx +67 -0
  215. package/src/__tests__/services/accountService.test.ts +337 -0
  216. package/src/__tests__/services/addressService.test.ts +312 -0
  217. package/src/__tests__/services/balanceService.test.ts +411 -0
  218. package/src/__tests__/services/walletSetupService.test.ts +463 -0
  219. package/src/__tests__/services/walletSwitchingService.test.ts +258 -0
  220. package/src/__tests__/services/workletLifecycleService.test.ts +514 -0
  221. package/src/__tests__/setup.ts +54 -0
  222. package/src/__tests__/storage/mmkvStorage.test.ts +325 -0
  223. package/src/__tests__/store/walletStore.test.ts +101 -0
  224. package/src/__tests__/store/workletStore.test.ts +329 -0
  225. package/src/__tests__/types/hrpc.test.ts +125 -0
  226. package/src/__tests__/utils/balanceUtils.test.ts +151 -0
  227. package/src/__tests__/utils/errorHandling.test.ts +147 -0
  228. package/src/__tests__/utils/errorUtils.test.ts +170 -0
  229. package/src/__tests__/utils/initializationState.test.ts +337 -0
  230. package/src/__tests__/utils/jsonUtils.test.ts +131 -0
  231. package/src/__tests__/utils/mmkvKeyManager.test.ts +205 -0
  232. package/src/__tests__/utils/mnemonicUtils.test.ts +48 -0
  233. package/src/__tests__/utils/raceConditions.test.ts +292 -0
  234. package/src/__tests__/utils/result.test.ts +73 -0
  235. package/src/__tests__/utils/schemas.test.ts +82 -0
  236. package/src/__tests__/utils/storeHelpers.test.ts +323 -0
  237. package/src/__tests__/utils/typeGuards.test.ts +209 -0
  238. package/src/__tests__/utils/validation.test.ts +152 -0
  239. package/src/__tests__/utils/walletUtils.test.ts +195 -0
  240. package/src/hooks/useBalance.ts +597 -0
  241. package/src/hooks/useWallet.ts +288 -0
  242. package/src/hooks/useWalletManager.ts +654 -0
  243. package/src/hooks/useWdkApp.ts +78 -0
  244. package/src/hooks/useWorklet.ts +109 -0
  245. package/src/index.ts +112 -0
  246. package/src/provider/WdkAppProvider.tsx +764 -0
  247. package/src/services/accountService.ts +134 -0
  248. package/src/services/addressService.ts +125 -0
  249. package/src/services/balanceService.ts +291 -0
  250. package/src/services/walletSetupService.ts +695 -0
  251. package/src/services/walletSwitchingService.ts +157 -0
  252. package/src/services/workletLifecycleService.ts +561 -0
  253. package/src/storage/mmkvStorage.ts +417 -0
  254. package/src/store/walletStore.ts +301 -0
  255. package/src/store/workletStore.ts +340 -0
  256. package/src/types/hrpc.ts +78 -0
  257. package/src/types.ts +188 -0
  258. package/src/utils/balanceUtils.ts +96 -0
  259. package/src/utils/constants.ts +84 -0
  260. package/src/utils/errorHandling.md +163 -0
  261. package/src/utils/errorHandling.ts +61 -0
  262. package/src/utils/errorUtils.ts +300 -0
  263. package/src/utils/initializationState.ts +242 -0
  264. package/src/utils/jsonUtils.ts +75 -0
  265. package/src/utils/logger.ts +54 -0
  266. package/src/utils/mmkvKeyManager.ts +256 -0
  267. package/src/utils/mnemonicUtils.ts +35 -0
  268. package/src/utils/operationMutex.ts +181 -0
  269. package/src/utils/result.ts +57 -0
  270. package/src/utils/schemas.ts +190 -0
  271. package/src/utils/storeHelpers.ts +236 -0
  272. package/src/utils/typeGuards.ts +129 -0
  273. package/src/utils/validation.ts +174 -0
  274. package/src/utils/walletStateHelpers.ts +104 -0
  275. package/src/utils/walletUtils.ts +107 -0
@@ -0,0 +1,78 @@
1
+ /**
2
+ * HRPC Type Extensions
3
+ *
4
+ * Type definitions for HRPC methods that may not be in the @spacesops/pear-wrk-wdk types yet.
5
+ * These types extend the HRPC interface to provide proper type safety.
6
+ */
7
+
8
+ import type { HRPC } from '@spacesops/pear-wrk-wdk'
9
+
10
+ /**
11
+ * Extended HRPC interface with additional methods
12
+ */
13
+ export interface ExtendedHRPC extends HRPC {
14
+ /**
15
+ * Initialize WDK with encrypted seed
16
+ */
17
+ initializeWDK: (options: {
18
+ encryptionKey: string
19
+ encryptedSeed: string
20
+ config: string
21
+ }) => Promise<{ status?: string | null }>
22
+
23
+ /**
24
+ * Generate entropy and encrypt it
25
+ */
26
+ generateEntropyAndEncrypt: (options: {
27
+ wordCount: number
28
+ }) => Promise<{
29
+ encryptionKey: string
30
+ encryptedSeedBuffer: string
31
+ encryptedEntropyBuffer: string
32
+ }>
33
+
34
+ /**
35
+ * Get mnemonic from encrypted entropy
36
+ */
37
+ getMnemonicFromEntropy: (options: {
38
+ encryptedEntropy: string
39
+ encryptionKey: string
40
+ }) => Promise<{
41
+ mnemonic: string
42
+ }>
43
+
44
+ /**
45
+ * Get seed and entropy from mnemonic phrase
46
+ */
47
+ getSeedAndEntropyFromMnemonic: (options: {
48
+ mnemonic: string
49
+ }) => Promise<{
50
+ encryptionKey: string
51
+ encryptedSeedBuffer: string
52
+ encryptedEntropyBuffer: string
53
+ }>
54
+ }
55
+
56
+ /**
57
+ * Type guard to check if HRPC instance has extended methods
58
+ */
59
+ export function isExtendedHRPC(hrpc: HRPC): hrpc is ExtendedHRPC {
60
+ return (
61
+ typeof (hrpc as unknown as Record<string, unknown>).initializeWDK === 'function' &&
62
+ typeof (hrpc as unknown as Record<string, unknown>).generateEntropyAndEncrypt === 'function' &&
63
+ typeof (hrpc as unknown as Record<string, unknown>).getMnemonicFromEntropy === 'function' &&
64
+ typeof (hrpc as unknown as Record<string, unknown>).getSeedAndEntropyFromMnemonic === 'function'
65
+ )
66
+ }
67
+
68
+ /**
69
+ * Safely cast HRPC to ExtendedHRPC
70
+ * Throws if the HRPC instance doesn't have the required methods
71
+ */
72
+ export function asExtendedHRPC(hrpc: HRPC): ExtendedHRPC {
73
+ if (!isExtendedHRPC(hrpc)) {
74
+ throw new Error('HRPC instance does not have required extended methods')
75
+ }
76
+ return hrpc
77
+ }
78
+
package/src/types.ts ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Core Type Definitions
3
+ *
4
+ * All network, token, and wallet type definitions for the WDK React Native Core library.
5
+ */
6
+
7
+ /**
8
+ * Network Configuration
9
+ *
10
+ * Defines the configuration for a blockchain network.
11
+ */
12
+ export interface NetworkConfig {
13
+ /** Chain ID for the network */
14
+ chainId: number
15
+ /** Blockchain name (e.g., "ethereum", "polygon") */
16
+ blockchain: string
17
+ /** Optional RPC provider URL */
18
+ provider?: string
19
+ /** Optional bundler URL for account abstraction */
20
+ bundlerUrl?: string
21
+ /** Optional paymaster URL for account abstraction */
22
+ paymasterUrl?: string
23
+ /** Optional paymaster contract address */
24
+ paymasterAddress?: string
25
+ /** Optional entry point contract address */
26
+ entryPointAddress?: string
27
+ /** Optional maximum fee for transfers */
28
+ transferMaxFee?: number
29
+ }
30
+
31
+ /**
32
+ * Network Configurations
33
+ *
34
+ * Maps network names to their configurations.
35
+ */
36
+ export type NetworkConfigs = Record<string, NetworkConfig>
37
+
38
+ /**
39
+ * Token Configuration
40
+ *
41
+ * Defines the configuration for a token (native or ERC20).
42
+ */
43
+ export interface TokenConfig {
44
+ /** Token symbol (e.g., "ETH", "USDT") */
45
+ symbol: string
46
+ /** Token name (e.g., "Ethereum", "Tether") */
47
+ name: string
48
+ /** Number of decimals (0-18) */
49
+ decimals: number
50
+ /** Token contract address (null for native tokens) */
51
+ address: string | null
52
+ }
53
+
54
+ /**
55
+ * Network Tokens
56
+ *
57
+ * Defines the tokens available for a network (native + ERC20 tokens).
58
+ */
59
+ export interface NetworkTokens {
60
+ /** Native token configuration */
61
+ native: TokenConfig
62
+ /** Array of ERC20 token configurations */
63
+ tokens: TokenConfig[]
64
+ }
65
+
66
+ /**
67
+ * Token Configurations
68
+ *
69
+ * Maps network names to their token configurations.
70
+ */
71
+ export type TokenConfigs = Record<string, NetworkTokens>
72
+
73
+ /**
74
+ * Wallet
75
+ *
76
+ * Represents a wallet instance with metadata.
77
+ */
78
+ export interface Wallet {
79
+ /** Account index (0-based) */
80
+ accountIndex: number
81
+ /** Unique wallet identifier */
82
+ identifier: string
83
+ /** Wallet display name */
84
+ name: string
85
+ /** Timestamp when wallet was created */
86
+ createdAt: number
87
+ /** Timestamp when wallet was last updated */
88
+ updatedAt: number
89
+ }
90
+
91
+ /**
92
+ * Wallet Addresses
93
+ *
94
+ * Maps network -> accountIndex -> address
95
+ * Structure: { [network]: { [accountIndex]: address } }
96
+ */
97
+ export type WalletAddresses = Record<string, Record<number, string>>
98
+
99
+ /**
100
+ * Wallet Addresses by Wallet Identifier
101
+ *
102
+ * Maps walletId -> network -> accountIndex -> address
103
+ * Structure: { [walletId]: { [network]: { [accountIndex]: address } } }
104
+ */
105
+ export type WalletAddressesByWallet = Record<string, WalletAddresses>
106
+
107
+ /**
108
+ * Wallet Balances
109
+ *
110
+ * Maps network -> accountIndex -> tokenAddress -> balance
111
+ * Structure: { [network]: { [accountIndex]: { [tokenAddress]: balance } } }
112
+ * Note: balance is stored as a string to handle BigInt values
113
+ */
114
+ export type WalletBalances = Record<string, Record<number, Record<string, string>>>
115
+
116
+ /**
117
+ * Wallet Balances by Wallet Identifier
118
+ *
119
+ * Maps walletId -> network -> accountIndex -> tokenAddress -> balance
120
+ * Structure: { [walletId]: { [network]: { [accountIndex]: { [tokenAddress]: balance } } } }
121
+ */
122
+ export type WalletBalancesByWallet = Record<string, WalletBalances>
123
+
124
+ /**
125
+ * Balance Loading States
126
+ *
127
+ * Maps "network-accountIndex-tokenAddress" -> boolean
128
+ * Used to track which balances are currently being fetched.
129
+ */
130
+ export type BalanceLoadingStates = Record<string, boolean>
131
+
132
+ /**
133
+ * Balance Fetch Result
134
+ *
135
+ * Result of a balance fetch operation.
136
+ */
137
+ export interface BalanceFetchResult {
138
+ /** Whether the fetch was successful */
139
+ success: boolean
140
+ /** Network name */
141
+ network: string
142
+ /** Account index */
143
+ accountIndex: number
144
+ /** Token address (null for native tokens) */
145
+ tokenAddress: string | null
146
+ /** Balance as a string (null if fetch failed) */
147
+ balance: string | null
148
+ /** Error message (only present if success is false) */
149
+ error?: string
150
+ }
151
+
152
+ /**
153
+ * Token Config Provider
154
+ *
155
+ * Either a TokenConfigs object or a function that returns TokenConfigs.
156
+ * Allows for dynamic token configuration.
157
+ */
158
+ export type TokenConfigProvider = TokenConfigs | (() => TokenConfigs)
159
+
160
+ /**
161
+ * Token Helpers
162
+ *
163
+ * Helper functions for working with token configurations.
164
+ */
165
+ export interface TokenHelpers {
166
+ /** Get all tokens (native + ERC20) for a network */
167
+ getTokensForNetwork: (network: string) => TokenConfig[]
168
+ /** Get all supported network names */
169
+ getSupportedNetworks: () => string[]
170
+ }
171
+
172
+ /**
173
+ * Wallet Store Interface
174
+ *
175
+ * Interface for wallet store implementations that provide account methods
176
+ * and wallet initialization status.
177
+ */
178
+ export interface WalletStore {
179
+ /** Call a method on a wallet account */
180
+ callAccountMethod: <T = unknown>(
181
+ network: string,
182
+ accountIndex: number,
183
+ methodName: string,
184
+ args?: unknown
185
+ ) => Promise<T>
186
+ /** Check if the wallet is initialized */
187
+ isWalletInitialized: () => boolean
188
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Balance utility functions
3
+ */
4
+
5
+ import { logError } from './logger'
6
+
7
+ /**
8
+ * Convert a value to string, handling BigInt values
9
+ */
10
+ export function convertBalanceToString(value: unknown): string {
11
+ if (typeof value === 'bigint') {
12
+ return value.toString()
13
+ }
14
+ if (typeof value === 'string') {
15
+ return value
16
+ }
17
+ if (typeof value === 'number') {
18
+ return value.toString()
19
+ }
20
+ // Fallback: try to convert to string
21
+ return String(value)
22
+ }
23
+
24
+ /**
25
+ * Recursively convert BigInt values to strings in objects/arrays
26
+ * Prevents serialization errors when BigInt values are present
27
+ *
28
+ * @param value - Value that may contain BigInt values
29
+ * @returns Value with all BigInt values converted to strings
30
+ */
31
+ export function convertBigIntToString(value: unknown): unknown {
32
+ if (typeof value === 'bigint') {
33
+ return value.toString()
34
+ }
35
+ if (Array.isArray(value)) {
36
+ return value.map(convertBigIntToString)
37
+ }
38
+ if (value && typeof value === 'object') {
39
+ return Object.fromEntries(
40
+ Object.entries(value).map(([key, val]) => [key, convertBigIntToString(val)])
41
+ )
42
+ }
43
+ return value
44
+ }
45
+
46
+ /**
47
+ * Format a balance from wei/smallest unit to readable format
48
+ *
49
+ * @param balance - Balance as string (from wei/smallest unit)
50
+ * @param decimals - Number of decimals for the token (e.g., 18 for ETH, 6 for USDT)
51
+ * @returns Formatted balance string (e.g., "1.5" or "1000")
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * formatBalance("1500000000000000000", 18) // "1.5"
56
+ * formatBalance("1000000", 6) // "1"
57
+ * formatBalance("1000001", 6) // "1.000001"
58
+ * ```
59
+ */
60
+ export function formatBalance(balance: string | null, decimals: number): string {
61
+ if (!balance || balance === '0' || balance === 'null') {
62
+ return '0'
63
+ }
64
+
65
+ // Validate that balance is a valid numeric string before attempting BigInt conversion
66
+ // BigInt accepts: digits only, or digits with optional leading minus sign
67
+ if (!/^-?\d+$/.test(balance.trim())) {
68
+ // Invalid format - return as-is (for backwards compatibility with test expectations)
69
+ return balance
70
+ }
71
+
72
+ try {
73
+ const balanceBigInt = BigInt(balance)
74
+ const divisor = BigInt(10 ** decimals)
75
+ const wholePart = balanceBigInt / divisor
76
+ const fractionalPart = balanceBigInt % divisor
77
+
78
+ if (fractionalPart === BigInt(0)) {
79
+ return wholePart.toString()
80
+ }
81
+
82
+ // Format fractional part with leading zeros if needed
83
+ const fractionalStr = fractionalPart.toString().padStart(decimals, '0')
84
+ // Remove trailing zeros
85
+ const fractionalTrimmed = fractionalStr.replace(/0+$/, '')
86
+
87
+ if (fractionalTrimmed === '') {
88
+ return wholePart.toString()
89
+ }
90
+
91
+ return `${wholePart}.${fractionalTrimmed}`
92
+ } catch (error) {
93
+ logError('Error formatting balance:', error)
94
+ return balance
95
+ }
96
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Application constants
3
+ *
4
+ * Centralized location for magic numbers and configuration values
5
+ * to improve maintainability and documentation.
6
+ */
7
+
8
+ /**
9
+ * Default balance refresh interval in milliseconds
10
+ *
11
+ * How often to automatically refresh wallet balances when auto-fetch is enabled.
12
+ * 30 seconds provides a good balance between freshness and performance.
13
+ */
14
+ export const DEFAULT_BALANCE_REFRESH_INTERVAL_MS = 30000
15
+
16
+ /**
17
+ * Valid mnemonic word counts
18
+ *
19
+ * BIP-39 standard supports 12-word (128 bits) and 24-word (256 bits) mnemonics.
20
+ */
21
+ export const MNEMONIC_WORD_COUNTS = {
22
+ /** 12-word mnemonic (128 bits of entropy) */
23
+ TWELVE: 12,
24
+ /** 24-word mnemonic (256 bits of entropy) */
25
+ TWENTY_FOUR: 24,
26
+ } as const
27
+
28
+ /**
29
+ * Default mnemonic word count
30
+ *
31
+ * 12 words is the most common choice, providing 128 bits of entropy
32
+ * which is sufficient for most use cases.
33
+ */
34
+ export const DEFAULT_MNEMONIC_WORD_COUNT = MNEMONIC_WORD_COUNTS.TWELVE
35
+
36
+ /**
37
+ * Account method names for balance operations
38
+ */
39
+ export const ACCOUNT_METHOD_GET_BALANCE = 'getBalance'
40
+ export const ACCOUNT_METHOD_GET_TOKEN_BALANCE = 'getTokenBalance'
41
+
42
+ /**
43
+ * Wallet identifier constants
44
+ */
45
+ export const WALLET_IDENTIFIER_PREFIX = 'wallet-'
46
+ export const MAIN_WALLET_NAME = 'Main Wallet'
47
+ export const WALLET_NAME_PREFIX = 'Wallet '
48
+
49
+ /**
50
+ * Token key for native tokens in balance storage
51
+ */
52
+ export const NATIVE_TOKEN_KEY = 'native'
53
+
54
+ /**
55
+ * Default query stale time in milliseconds
56
+ *
57
+ * How long data is considered fresh before TanStack Query refetches it.
58
+ * 30 seconds provides a good balance between freshness and performance.
59
+ */
60
+ export const DEFAULT_QUERY_STALE_TIME_MS = 30 * 1000
61
+
62
+ /**
63
+ * Default query garbage collection time in milliseconds
64
+ *
65
+ * How long unused query data is kept in cache before being garbage collected.
66
+ * 5 minutes provides a good balance between cache efficiency and memory usage.
67
+ */
68
+ export const DEFAULT_QUERY_GC_TIME_MS = 5 * 60 * 1000
69
+
70
+ /**
71
+ * Allowed account methods whitelist
72
+ * Only these methods can be called through AccountService for security
73
+ */
74
+ export const ALLOWED_ACCOUNT_METHODS = [
75
+ 'getAddress',
76
+ 'getBalance',
77
+ 'getTokenBalance',
78
+ 'signMessage',
79
+ 'signTransaction',
80
+ 'sendTransaction',
81
+ ] as const
82
+
83
+ export type AllowedAccountMethod = typeof ALLOWED_ACCOUNT_METHODS[number]
84
+
@@ -0,0 +1,163 @@
1
+ # Error Handling Guidelines
2
+
3
+ This document outlines the standardized error handling patterns used across the wdk-react-native-core module.
4
+
5
+ ## Principles
6
+
7
+ 1. **Always normalize errors**: Use `normalizeError()` to convert any error-like value to a proper Error instance
8
+ 2. **Sanitize in production**: Always sanitize error messages in production to prevent information leakage
9
+ 3. **Provide context**: Include component and operation context when normalizing errors
10
+ 4. **Log before throwing**: Log errors before re-throwing them for debugging
11
+ 5. **Handle gracefully**: Don't crash the app - handle errors gracefully with user-friendly messages
12
+
13
+ ## Standard Pattern
14
+
15
+ ```typescript
16
+ import { normalizeError } from '../utils/errorUtils'
17
+ import { logError } from '../utils/logger'
18
+
19
+ try {
20
+ // Operation that might fail
21
+ await someOperation()
22
+ } catch (error) {
23
+ const normalizedError = normalizeError(error, true, {
24
+ component: 'ServiceName',
25
+ operation: 'operationName'
26
+ })
27
+ logError('[ServiceName] Failed to perform operation:', normalizedError)
28
+ throw normalizedError
29
+ }
30
+ ```
31
+
32
+ ## Error Recovery Strategies
33
+
34
+ ### 1. Retryable Operations
35
+ For operations that might fail due to transient issues (network, temporary unavailability):
36
+
37
+ ```typescript
38
+ try {
39
+ await operation()
40
+ } catch (error) {
41
+ // Log error
42
+ const normalizedError = normalizeError(error, true, { component: 'Service', operation: 'operation' })
43
+ logError('[Service] Operation failed:', normalizedError)
44
+
45
+ // Store error for UI to display retry option
46
+ setError(normalizedError)
47
+ // Don't throw - allow user to retry
48
+ }
49
+ ```
50
+
51
+ ### 2. Critical Operations
52
+ For operations that must succeed (initialization, critical state changes):
53
+
54
+ ```typescript
55
+ try {
56
+ await criticalOperation()
57
+ } catch (error) {
58
+ const normalizedError = normalizeError(error, true, { component: 'Service', operation: 'criticalOperation' })
59
+ logError('[Service] Critical operation failed:', normalizedError)
60
+ // Throw to prevent proceeding with invalid state
61
+ throw normalizedError
62
+ }
63
+ ```
64
+
65
+ ### 3. Non-Critical Operations
66
+ For operations that can fail without breaking the app (caching, optional features):
67
+
68
+ ```typescript
69
+ try {
70
+ await optionalOperation()
71
+ } catch (error) {
72
+ // Log but don't throw - operation is optional
73
+ logWarn('[Service] Optional operation failed:', error)
74
+ // Continue execution
75
+ }
76
+ ```
77
+
78
+ ## Error Context
79
+
80
+ Always provide context when normalizing errors:
81
+
82
+ ```typescript
83
+ normalizeError(error, true, {
84
+ component: 'ServiceName', // Which component/service
85
+ operation: 'operationName', // What operation was being performed
86
+ network?: string, // Optional: which network
87
+ accountIndex?: number // Optional: which account
88
+ })
89
+ ```
90
+
91
+ ## Error Sanitization
92
+
93
+ Error sanitization is handled automatically by `normalizeError()` when `sanitize` is `true` (default in production). This:
94
+ - Removes sensitive data (keys, seeds, mnemonics)
95
+ - Masks file paths
96
+ - Preserves error type information
97
+ - Allows detailed errors in development mode
98
+
99
+ ## Async Operations
100
+
101
+ For async operations, always:
102
+ 1. Check abort signals if provided
103
+ 2. Handle cancellation gracefully
104
+ 3. Clean up resources on error
105
+
106
+ ```typescript
107
+ async function operation(signal?: AbortSignal): Promise<void> {
108
+ if (signal?.aborted) {
109
+ throw new Error('Operation cancelled')
110
+ }
111
+
112
+ try {
113
+ await doWork()
114
+
115
+ // Check again after async operation
116
+ if (signal?.aborted) {
117
+ throw new Error('Operation cancelled')
118
+ }
119
+ } catch (error) {
120
+ if (signal?.aborted) {
121
+ // Don't log cancellation errors
122
+ throw error
123
+ }
124
+
125
+ const normalizedError = normalizeError(error, true, { component: 'Service', operation: 'operation' })
126
+ logError('[Service] Operation failed:', normalizedError)
127
+ throw normalizedError
128
+ }
129
+ }
130
+ ```
131
+
132
+ ## Service-Specific Patterns
133
+
134
+ ### AddressService
135
+ - Always validate inputs before operations
136
+ - Throw errors for invalid addresses
137
+ - Log all failures with network and account context
138
+
139
+ ### BalanceService
140
+ - Non-critical operations can fail silently
141
+ - Log warnings for balance fetch failures
142
+ - Store errors in state for UI display
143
+
144
+ ### WorkletLifecycleService
145
+ - Critical operations must throw
146
+ - Log all failures with full context
147
+ - Clean up resources on error
148
+
149
+ ### WalletSetupService
150
+ - Require biometric authentication
151
+ - Throw errors for authentication failures
152
+ - Log all setup operations
153
+
154
+ ## Testing Error Handling
155
+
156
+ When testing error handling:
157
+ 1. Test error normalization
158
+ 2. Test error sanitization
159
+ 3. Test error recovery
160
+ 4. Test error context preservation
161
+ 5. Test abort signal handling
162
+
163
+
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Error handling utilities for services
3
+ *
4
+ * Provides consistent error handling patterns across all services
5
+ * to reduce code duplication and improve maintainability.
6
+ *
7
+ * ## Usage Guidelines
8
+ *
9
+ * **For Services**: Use `handleServiceError()` - this provides consistent normalization
10
+ * and logging for service-layer errors. Errors are NOT sanitized (sanitizeLevel: false)
11
+ * because services log internally and need full error details for debugging.
12
+ *
13
+ * **For Hooks/UI**: Use `normalizeError()` directly with appropriate sanitization level.
14
+ * Hooks should sanitize errors before exposing them to UI components.
15
+ *
16
+ * @example Service usage:
17
+ * ```typescript
18
+ * try {
19
+ * await someOperation()
20
+ * } catch (error) {
21
+ * handleServiceError(error, 'AddressService', 'getAddress', { network, accountIndex })
22
+ * }
23
+ * ```
24
+ *
25
+ * @example Hook/UI usage:
26
+ * ```typescript
27
+ * try {
28
+ * await someOperation()
29
+ * } catch (error) {
30
+ * const normalized = normalizeError(error, true, { component: 'MyHook', operation: 'fetchData' })
31
+ * setError(normalized.message)
32
+ * }
33
+ * ```
34
+ */
35
+
36
+ import { normalizeError } from './errorUtils'
37
+ import { logError } from './logger'
38
+
39
+ /**
40
+ * Handle service errors with consistent normalization and logging
41
+ *
42
+ * **Use this in services** - provides consistent error handling with full error details
43
+ * (no sanitization) for internal logging and debugging.
44
+ *
45
+ * @param error - Error to handle
46
+ * @param component - Component/service name where error occurred
47
+ * @param operation - Operation name that failed
48
+ * @param context - Additional context for error
49
+ * @throws Normalized error
50
+ */
51
+ export function handleServiceError(
52
+ error: unknown,
53
+ component: string,
54
+ operation: string,
55
+ context?: Record<string, unknown>
56
+ ): never {
57
+ const normalized = normalizeError(error, false, { component, operation, ...context })
58
+ logError(`[${component}] ${operation} failed:`, normalized)
59
+ throw normalized
60
+ }
61
+