@metamask-previews/wallet-cli 0.0.0-preview-8bfa290fb → 0.0.0-preview-e8a256c39

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 (264) hide show
  1. package/CHANGELOG.md +8 -4
  2. package/dist/commands/daemon/{call.d.mts → call.d.ts} +2 -2
  3. package/dist/commands/daemon/call.d.ts.map +1 -0
  4. package/dist/commands/daemon/{call.mjs → call.js} +30 -31
  5. package/dist/commands/daemon/call.js.map +1 -0
  6. package/dist/commands/daemon/{list.d.cts → list.d.ts} +2 -2
  7. package/dist/commands/daemon/list.d.ts.map +1 -0
  8. package/dist/commands/daemon/{list.mjs → list.js} +9 -10
  9. package/dist/commands/daemon/list.js.map +1 -0
  10. package/dist/commands/daemon/{purge.d.cts → purge.d.ts} +2 -2
  11. package/dist/commands/daemon/purge.d.ts.map +1 -0
  12. package/dist/commands/daemon/{purge.mjs → purge.js} +19 -20
  13. package/dist/commands/daemon/purge.js.map +1 -0
  14. package/dist/commands/daemon/{start.d.cts → start.d.ts} +2 -2
  15. package/dist/commands/daemon/start.d.ts.map +1 -0
  16. package/dist/commands/daemon/start.js +49 -0
  17. package/dist/commands/daemon/{start.cjs.map → start.js.map} +1 -1
  18. package/dist/commands/daemon/{status.d.cts → status.d.ts} +2 -2
  19. package/dist/commands/daemon/status.d.ts.map +1 -0
  20. package/dist/commands/daemon/{status.mjs → status.js} +10 -11
  21. package/dist/commands/daemon/status.js.map +1 -0
  22. package/dist/commands/daemon/{stop.d.cts → stop.d.ts} +2 -2
  23. package/dist/commands/daemon/stop.d.ts.map +1 -0
  24. package/dist/commands/daemon/{stop.mjs → stop.js} +9 -10
  25. package/dist/commands/daemon/stop.js.map +1 -0
  26. package/dist/commands/wallet/{send.d.cts → send.d.ts} +3 -3
  27. package/dist/commands/wallet/send.d.ts.map +1 -0
  28. package/dist/commands/wallet/{send.mjs → send.js} +111 -123
  29. package/dist/commands/wallet/send.js.map +1 -0
  30. package/dist/commands/wallet/{unlock.d.cts → unlock.d.ts} +2 -2
  31. package/dist/commands/wallet/unlock.d.ts.map +1 -0
  32. package/dist/commands/wallet/{unlock.mjs → unlock.js} +29 -30
  33. package/dist/commands/wallet/unlock.js.map +1 -0
  34. package/dist/daemon/{auto-approval.d.mts → auto-approval.d.ts} +3 -3
  35. package/dist/daemon/auto-approval.d.ts.map +1 -0
  36. package/dist/daemon/{auto-approval.mjs → auto-approval.js} +1 -1
  37. package/dist/daemon/auto-approval.js.map +1 -0
  38. package/dist/daemon/{daemon-client.d.mts → daemon-client.d.ts} +2 -2
  39. package/dist/daemon/daemon-client.d.ts.map +1 -0
  40. package/dist/daemon/{daemon-client.mjs → daemon-client.js} +8 -8
  41. package/dist/daemon/daemon-client.js.map +1 -0
  42. package/dist/daemon/daemon-entry.d.ts +2 -0
  43. package/dist/daemon/daemon-entry.d.ts.map +1 -0
  44. package/dist/daemon/{daemon-entry.mjs → daemon-entry.js} +12 -12
  45. package/dist/daemon/daemon-entry.js.map +1 -0
  46. package/dist/daemon/{daemon-spawn.d.mts → daemon-spawn.d.ts} +2 -2
  47. package/dist/daemon/daemon-spawn.d.ts.map +1 -0
  48. package/dist/daemon/{daemon-spawn.mjs → daemon-spawn.js} +7 -7
  49. package/dist/daemon/daemon-spawn.js.map +1 -0
  50. package/dist/daemon/{data-dir.d.cts → data-dir.d.ts} +1 -1
  51. package/dist/daemon/data-dir.d.ts.map +1 -0
  52. package/dist/daemon/{data-dir.mjs → data-dir.js} +3 -3
  53. package/dist/daemon/data-dir.js.map +1 -0
  54. package/dist/daemon/{paths.d.mts → paths.d.ts} +2 -2
  55. package/dist/daemon/paths.d.ts.map +1 -0
  56. package/dist/daemon/{paths.mjs → paths.js} +2 -2
  57. package/dist/daemon/paths.js.map +1 -0
  58. package/dist/daemon/{prompts.d.cts → prompts.d.ts} +1 -1
  59. package/dist/daemon/prompts.d.ts.map +1 -0
  60. package/dist/daemon/{prompts.mjs → prompts.js} +4 -4
  61. package/dist/daemon/prompts.js.map +1 -0
  62. package/dist/daemon/{rpc-socket-server.d.cts → rpc-socket-server.d.ts} +2 -2
  63. package/dist/daemon/rpc-socket-server.d.ts.map +1 -0
  64. package/dist/daemon/{rpc-socket-server.mjs → rpc-socket-server.js} +8 -8
  65. package/dist/daemon/rpc-socket-server.js.map +1 -0
  66. package/dist/daemon/{secrets.d.cts → secrets.d.ts} +1 -1
  67. package/dist/daemon/secrets.d.ts.map +1 -0
  68. package/dist/daemon/{secrets.mjs → secrets.js} +11 -23
  69. package/dist/daemon/secrets.js.map +1 -0
  70. package/dist/daemon/{send-transaction.d.cts → send-transaction.d.ts} +9 -9
  71. package/dist/daemon/send-transaction.d.ts.map +1 -0
  72. package/dist/daemon/{send-transaction.mjs → send-transaction.js} +3 -3
  73. package/dist/daemon/send-transaction.js.map +1 -0
  74. package/dist/daemon/{socket-line.d.cts → socket-line.d.ts} +2 -5
  75. package/dist/daemon/socket-line.d.ts.map +1 -0
  76. package/dist/daemon/{socket-line.mjs → socket-line.js} +1 -1
  77. package/dist/daemon/socket-line.js.map +1 -0
  78. package/dist/daemon/{stop-daemon.d.cts → stop-daemon.d.ts} +1 -1
  79. package/dist/daemon/stop-daemon.d.ts.map +1 -0
  80. package/dist/daemon/{stop-daemon.mjs → stop-daemon.js} +7 -7
  81. package/dist/daemon/stop-daemon.js.map +1 -0
  82. package/dist/daemon/{types.d.cts → types.d.ts} +4 -4
  83. package/dist/daemon/types.d.ts.map +1 -0
  84. package/dist/daemon/{types.mjs → types.js} +1 -1
  85. package/dist/daemon/types.js.map +1 -0
  86. package/dist/daemon/{utils.d.cts → utils.d.ts} +2 -3
  87. package/dist/daemon/utils.d.ts.map +1 -0
  88. package/dist/daemon/{utils.mjs → utils.js} +3 -3
  89. package/dist/daemon/utils.js.map +1 -0
  90. package/dist/daemon/{wallet-factory.d.cts → wallet-factory.d.ts} +4 -4
  91. package/dist/daemon/wallet-factory.d.ts.map +1 -0
  92. package/dist/daemon/{wallet-factory.mjs → wallet-factory.js} +12 -12
  93. package/dist/daemon/wallet-factory.js.map +1 -0
  94. package/dist/persistence/{KeyValueStore.d.cts → KeyValueStore.d.ts} +2 -2
  95. package/dist/persistence/KeyValueStore.d.ts.map +1 -0
  96. package/dist/persistence/KeyValueStore.js +59 -0
  97. package/dist/persistence/KeyValueStore.js.map +1 -0
  98. package/dist/persistence/{persistence.d.cts → persistence.d.ts} +5 -5
  99. package/dist/persistence/persistence.d.ts.map +1 -0
  100. package/dist/persistence/{persistence.mjs → persistence.js} +2 -2
  101. package/dist/persistence/persistence.js.map +1 -0
  102. package/dist/test/{run-command.d.cts → run-command.d.ts} +4 -4
  103. package/dist/test/run-command.d.ts.map +1 -0
  104. package/dist/test/{run-command.mjs → run-command.js} +3 -3
  105. package/dist/test/run-command.js.map +1 -0
  106. package/package.json +19 -15
  107. package/dist/commands/daemon/call.cjs +0 -79
  108. package/dist/commands/daemon/call.cjs.map +0 -1
  109. package/dist/commands/daemon/call.d.cts +0 -14
  110. package/dist/commands/daemon/call.d.cts.map +0 -1
  111. package/dist/commands/daemon/call.d.mts.map +0 -1
  112. package/dist/commands/daemon/call.mjs.map +0 -1
  113. package/dist/commands/daemon/list.cjs +0 -48
  114. package/dist/commands/daemon/list.cjs.map +0 -1
  115. package/dist/commands/daemon/list.d.cts.map +0 -1
  116. package/dist/commands/daemon/list.d.mts +0 -7
  117. package/dist/commands/daemon/list.d.mts.map +0 -1
  118. package/dist/commands/daemon/list.mjs.map +0 -1
  119. package/dist/commands/daemon/purge.cjs +0 -58
  120. package/dist/commands/daemon/purge.cjs.map +0 -1
  121. package/dist/commands/daemon/purge.d.cts.map +0 -1
  122. package/dist/commands/daemon/purge.d.mts +0 -10
  123. package/dist/commands/daemon/purge.d.mts.map +0 -1
  124. package/dist/commands/daemon/purge.mjs.map +0 -1
  125. package/dist/commands/daemon/start.cjs +0 -52
  126. package/dist/commands/daemon/start.d.cts.map +0 -1
  127. package/dist/commands/daemon/start.d.mts +0 -12
  128. package/dist/commands/daemon/start.d.mts.map +0 -1
  129. package/dist/commands/daemon/start.mjs +0 -50
  130. package/dist/commands/daemon/start.mjs.map +0 -1
  131. package/dist/commands/daemon/status.cjs +0 -59
  132. package/dist/commands/daemon/status.cjs.map +0 -1
  133. package/dist/commands/daemon/status.d.cts.map +0 -1
  134. package/dist/commands/daemon/status.d.mts +0 -7
  135. package/dist/commands/daemon/status.d.mts.map +0 -1
  136. package/dist/commands/daemon/status.mjs.map +0 -1
  137. package/dist/commands/daemon/stop.cjs +0 -26
  138. package/dist/commands/daemon/stop.cjs.map +0 -1
  139. package/dist/commands/daemon/stop.d.cts.map +0 -1
  140. package/dist/commands/daemon/stop.d.mts +0 -7
  141. package/dist/commands/daemon/stop.d.mts.map +0 -1
  142. package/dist/commands/daemon/stop.mjs.map +0 -1
  143. package/dist/commands/wallet/send.cjs +0 -332
  144. package/dist/commands/wallet/send.cjs.map +0 -1
  145. package/dist/commands/wallet/send.d.cts.map +0 -1
  146. package/dist/commands/wallet/send.d.mts +0 -42
  147. package/dist/commands/wallet/send.d.mts.map +0 -1
  148. package/dist/commands/wallet/send.mjs.map +0 -1
  149. package/dist/commands/wallet/unlock.cjs +0 -75
  150. package/dist/commands/wallet/unlock.cjs.map +0 -1
  151. package/dist/commands/wallet/unlock.d.cts.map +0 -1
  152. package/dist/commands/wallet/unlock.d.mts +0 -11
  153. package/dist/commands/wallet/unlock.d.mts.map +0 -1
  154. package/dist/commands/wallet/unlock.mjs.map +0 -1
  155. package/dist/daemon/auto-approval.cjs +0 -86
  156. package/dist/daemon/auto-approval.cjs.map +0 -1
  157. package/dist/daemon/auto-approval.d.cts +0 -22
  158. package/dist/daemon/auto-approval.d.cts.map +0 -1
  159. package/dist/daemon/auto-approval.d.mts.map +0 -1
  160. package/dist/daemon/auto-approval.mjs.map +0 -1
  161. package/dist/daemon/daemon-client.cjs +0 -149
  162. package/dist/daemon/daemon-client.cjs.map +0 -1
  163. package/dist/daemon/daemon-client.d.cts +0 -84
  164. package/dist/daemon/daemon-client.d.cts.map +0 -1
  165. package/dist/daemon/daemon-client.d.mts.map +0 -1
  166. package/dist/daemon/daemon-client.mjs.map +0 -1
  167. package/dist/daemon/daemon-entry.cjs +0 -278
  168. package/dist/daemon/daemon-entry.cjs.map +0 -1
  169. package/dist/daemon/daemon-entry.d.cts +0 -2
  170. package/dist/daemon/daemon-entry.d.cts.map +0 -1
  171. package/dist/daemon/daemon-entry.d.mts +0 -2
  172. package/dist/daemon/daemon-entry.d.mts.map +0 -1
  173. package/dist/daemon/daemon-entry.mjs.map +0 -1
  174. package/dist/daemon/daemon-spawn.cjs +0 -138
  175. package/dist/daemon/daemon-spawn.cjs.map +0 -1
  176. package/dist/daemon/daemon-spawn.d.cts +0 -28
  177. package/dist/daemon/daemon-spawn.d.cts.map +0 -1
  178. package/dist/daemon/daemon-spawn.d.mts.map +0 -1
  179. package/dist/daemon/daemon-spawn.mjs.map +0 -1
  180. package/dist/daemon/data-dir.cjs +0 -23
  181. package/dist/daemon/data-dir.cjs.map +0 -1
  182. package/dist/daemon/data-dir.d.cts.map +0 -1
  183. package/dist/daemon/data-dir.d.mts +0 -14
  184. package/dist/daemon/data-dir.d.mts.map +0 -1
  185. package/dist/daemon/data-dir.mjs.map +0 -1
  186. package/dist/daemon/paths.cjs +0 -20
  187. package/dist/daemon/paths.cjs.map +0 -1
  188. package/dist/daemon/paths.d.cts +0 -9
  189. package/dist/daemon/paths.d.cts.map +0 -1
  190. package/dist/daemon/paths.d.mts.map +0 -1
  191. package/dist/daemon/paths.mjs.map +0 -1
  192. package/dist/daemon/prompts.cjs +0 -55
  193. package/dist/daemon/prompts.cjs.map +0 -1
  194. package/dist/daemon/prompts.d.cts.map +0 -1
  195. package/dist/daemon/prompts.d.mts +0 -31
  196. package/dist/daemon/prompts.d.mts.map +0 -1
  197. package/dist/daemon/prompts.mjs.map +0 -1
  198. package/dist/daemon/rpc-socket-server.cjs +0 -284
  199. package/dist/daemon/rpc-socket-server.cjs.map +0 -1
  200. package/dist/daemon/rpc-socket-server.d.cts.map +0 -1
  201. package/dist/daemon/rpc-socket-server.d.mts +0 -44
  202. package/dist/daemon/rpc-socket-server.d.mts.map +0 -1
  203. package/dist/daemon/rpc-socket-server.mjs.map +0 -1
  204. package/dist/daemon/secrets.cjs +0 -137
  205. package/dist/daemon/secrets.cjs.map +0 -1
  206. package/dist/daemon/secrets.d.cts.map +0 -1
  207. package/dist/daemon/secrets.d.mts +0 -72
  208. package/dist/daemon/secrets.d.mts.map +0 -1
  209. package/dist/daemon/secrets.mjs.map +0 -1
  210. package/dist/daemon/send-transaction.cjs +0 -147
  211. package/dist/daemon/send-transaction.cjs.map +0 -1
  212. package/dist/daemon/send-transaction.d.cts.map +0 -1
  213. package/dist/daemon/send-transaction.d.mts +0 -102
  214. package/dist/daemon/send-transaction.d.mts.map +0 -1
  215. package/dist/daemon/send-transaction.mjs.map +0 -1
  216. package/dist/daemon/socket-line.cjs +0 -93
  217. package/dist/daemon/socket-line.cjs.map +0 -1
  218. package/dist/daemon/socket-line.d.cts.map +0 -1
  219. package/dist/daemon/socket-line.d.mts +0 -21
  220. package/dist/daemon/socket-line.d.mts.map +0 -1
  221. package/dist/daemon/socket-line.mjs.map +0 -1
  222. package/dist/daemon/stop-daemon.cjs +0 -117
  223. package/dist/daemon/stop-daemon.cjs.map +0 -1
  224. package/dist/daemon/stop-daemon.d.cts.map +0 -1
  225. package/dist/daemon/stop-daemon.d.mts +0 -28
  226. package/dist/daemon/stop-daemon.d.mts.map +0 -1
  227. package/dist/daemon/stop-daemon.mjs.map +0 -1
  228. package/dist/daemon/types.cjs +0 -20
  229. package/dist/daemon/types.cjs.map +0 -1
  230. package/dist/daemon/types.d.cts.map +0 -1
  231. package/dist/daemon/types.d.mts +0 -94
  232. package/dist/daemon/types.d.mts.map +0 -1
  233. package/dist/daemon/types.mjs.map +0 -1
  234. package/dist/daemon/utils.cjs +0 -172
  235. package/dist/daemon/utils.cjs.map +0 -1
  236. package/dist/daemon/utils.d.cts.map +0 -1
  237. package/dist/daemon/utils.d.mts +0 -87
  238. package/dist/daemon/utils.d.mts.map +0 -1
  239. package/dist/daemon/utils.mjs.map +0 -1
  240. package/dist/daemon/wallet-factory.cjs +0 -341
  241. package/dist/daemon/wallet-factory.cjs.map +0 -1
  242. package/dist/daemon/wallet-factory.d.cts.map +0 -1
  243. package/dist/daemon/wallet-factory.d.mts +0 -64
  244. package/dist/daemon/wallet-factory.d.mts.map +0 -1
  245. package/dist/daemon/wallet-factory.mjs.map +0 -1
  246. package/dist/persistence/KeyValueStore.cjs +0 -79
  247. package/dist/persistence/KeyValueStore.cjs.map +0 -1
  248. package/dist/persistence/KeyValueStore.d.cts.map +0 -1
  249. package/dist/persistence/KeyValueStore.d.mts +0 -18
  250. package/dist/persistence/KeyValueStore.d.mts.map +0 -1
  251. package/dist/persistence/KeyValueStore.mjs +0 -79
  252. package/dist/persistence/KeyValueStore.mjs.map +0 -1
  253. package/dist/persistence/persistence.cjs +0 -204
  254. package/dist/persistence/persistence.cjs.map +0 -1
  255. package/dist/persistence/persistence.d.cts.map +0 -1
  256. package/dist/persistence/persistence.d.mts +0 -45
  257. package/dist/persistence/persistence.d.mts.map +0 -1
  258. package/dist/persistence/persistence.mjs.map +0 -1
  259. package/dist/test/run-command.cjs +0 -73
  260. package/dist/test/run-command.cjs.map +0 -1
  261. package/dist/test/run-command.d.cts.map +0 -1
  262. package/dist/test/run-command.d.mts +0 -27
  263. package/dist/test/run-command.d.mts.map +0 -1
  264. package/dist/test/run-command.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-factory.cjs","sourceRoot":"","sources":["../../src/daemon/wallet-factory.ts"],"names":[],"mappings":";;;AAAA,yEAAoF;AAKpF,qFAA4E;AAC5E,mDAAgD;AAChD,6FAKkD;AAClD,+DAAmE;AAEnE,6CAI0B;AAO1B,+CAAsC;AAEtC,uEAAgE;AAChE,mEAA8E;AAC9E,0DAA6D;AAI7D,MAAM,uBAAuB,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AAC,EAAE,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IACD,IAAI,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,yCAAyC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,mBAAmB,CAC1B,KAA8C;IAE9C,OAAO,OAAO,KAAK,CAAC,iBAAiB,EAAE,KAAK,KAAK,QAAQ,CAAC;AAC5D,CAAC","sourcesContent":["import { getDefaultAnalyticsControllerState } from '@metamask/analytics-controller';\nimport type {\n AnalyticsControllerGetStateAction,\n AnalyticsControllerTrackEventAction,\n} from '@metamask/analytics-controller';\nimport { ConfigRegistryApiEnv } from '@metamask/config-registry-controller';\nimport { Messenger } from '@metamask/messenger';\nimport {\n ClientConfigApiService,\n ClientType,\n DistributionType,\n EnvironmentType,\n} from '@metamask/remote-feature-flag-controller';\nimport { InMemoryStorageAdapter } from '@metamask/storage-service';\nimport type { Json } from '@metamask/utils';\nimport {\n AlwaysOnlineAdapter,\n importSecretRecoveryPhrase,\n Wallet,\n} from '@metamask/wallet';\nimport type {\n DefaultActions,\n DefaultEvents,\n RootMessenger,\n WalletOptions,\n} from '@metamask/wallet';\nimport { rm } from 'node:fs/promises';\n\nimport { KeyValueStore } from '../persistence/KeyValueStore.js';\nimport { loadState, subscribeToChanges } from '../persistence/persistence.js';\nimport { subscribeToAutoApproval } from './auto-approval.js';\nimport type { Password, Srp } from './secrets.js';\nimport type { Logger } from './types.js';\n\nconst IN_MEMORY_DATABASE_PATH = ':memory:';\n\nexport type CreateWalletConfig = {\n databasePath: string;\n password?: Password;\n srp: Srp;\n infuraProjectId: string;\n log?: Logger;\n};\n\nexport type CreateWalletResult = {\n wallet: Wallet;\n /**\n * Tear down everything `createWallet` set up, in the order that keeps\n * in-flight persistence writes valid: stop the state-change subscription,\n * destroy the wallet, then close the store (closing first would cause a\n * teardown-time persistence write to fail). Resilient — a failure in any\n * step is logged and the remaining steps still run — and idempotent (repeat\n * calls coalesce onto the same teardown).\n */\n dispose: () => Promise<void>;\n};\n\n/**\n * Build the per-instance options the daemon's `Wallet` is constructed with.\n *\n * Returns a fresh set on every call so the metadata probe and the real wallet\n * never share adapter/service instances (the probe is destroyed, which may\n * tear those instances down).\n *\n * Only the slots wired on `@metamask/wallet` today are populated:\n * - `storageService` — backed by an in-memory adapter. This is the wallet's\n * large-blob store (snap source, caches), distinct from the SQLite\n * `KeyValueStore` that persists controller state; no wired controller\n * offloads durable data to it yet, so in-memory suffices.\n * - `connectivityController` — the `AlwaysOnlineAdapter` exported for\n * node-like hosts that have no platform connectivity signal.\n * - `networkController` — the Infura project ID used to reach Infura RPC\n * endpoints.\n * - `remoteFeatureFlagController` — a `ClientConfigApiService` fetching real\n * flags over the network.\n * - `approvalController` — a no-op `showApprovalRequest` (the daemon is\n * headless); pending requests are accepted separately by the auto-approval\n * subscription `createWallet` installs, not by this hook.\n * - `gasFeeController` — only `clientId: 'cli'` (sent as `X-Client-Id` to the\n * gas API); the API endpoints, poll interval, and compatibility callbacks are\n * left at the wallet package's platform-agnostic defaults (the default\n * `EIP1559APIEndpoint` is already the production URL, so the daemon does not\n * re-specify it).\n * - `transactionController` — swaps processing disabled and no client hooks;\n * see the slot's inline comment for why the daemon relies on the\n * controller's defaults for everything else.\n *\n * The optional `keyringController` slot is intentionally omitted so the\n * controller's built-in defaults (e.g. the PBKDF2 encryptor) apply.\n *\n * @param infuraProjectId - The Infura project ID for the `NetworkController`.\n * @returns The `instanceOptions` for the `Wallet` constructor.\n */\nfunction buildInstanceOptions(\n infuraProjectId: string,\n): WalletOptions['instanceOptions'] {\n return {\n configRegistryApiService: {\n env: ConfigRegistryApiEnv.PRD,\n },\n approvalController: {\n // The daemon is headless, so there is no UI to open: requests are\n // resolved by the auto-approval subscription (see `subscribeToAutoApproval`)\n // rather than by this hook, which stays a no-op.\n // TODO: surface approval requests over the daemon transport.\n showApprovalRequest: (): undefined => undefined,\n },\n connectivityController: {\n connectivityAdapter: new AlwaysOnlineAdapter(),\n },\n gasFeeController: {\n // Identifies the CLI to the gas estimation API via the `X-Client-Id`\n // header.\n clientId: 'cli',\n },\n networkController: {\n infuraProjectId,\n },\n remoteFeatureFlagController: {\n clientConfigApiService: new ClientConfigApiService({\n fetch: globalThis.fetch,\n config: {\n // TODO: switch to a CLI-specific `ClientType` once one exists; until\n // then `Extension` buckets feature flags as an extension client.\n client: ClientType.Extension,\n distribution: DistributionType.Main,\n environment: EnvironmentType.Production,\n },\n }),\n getMetaMetricsId: (): string => 'cli',\n clientVersion: '0.0.0',\n },\n storageService: {\n storage: new InMemoryStorageAdapter(),\n },\n transactionController: {\n // The CLI exposes no swaps surface, so skip the swaps-specific\n // post-processing a full wallet client runs (mobile makes the same\n // choice; the extension keeps swaps enabled).\n disableSwaps: true,\n // No CLI-specific transaction hooks: the controller's built-in publish\n // path broadcasts through the wired `NetworkController` provider, and the\n // remaining hooks (metrics, notifications, gas-fee tokens) are client-UI\n // concerns the headless daemon has no equivalent for. Every other option\n // (`getPermittedAccounts`, `isSimulationEnabled`, `trace`, …) is left at\n // the controller's default.\n hooks: {},\n },\n };\n}\n\n/**\n * Register handlers for the `AnalyticsController` actions that\n * `NetworkController` calls to emit RPC service analytics. The daemon does not\n * report analytics, so these do nothing: `getState` returns an empty analytics\n * ID, which stops the controller before it tracks anything, and `trackEvent` is\n * a no-op. Registering them keeps those messenger calls from throwing.\n *\n * @param messenger - The wallet's root messenger.\n */\nfunction registerAnalyticsStubHandlers(messenger: Wallet['messenger']): void {\n // Register on an `AnalyticsController`-namespaced messenger, not the root: a\n // messenger can only register handlers for its own namespace, and doing so\n // delegates them up to the root, where `NetworkController` can reach them.\n const analyticsMessenger = new Messenger<\n 'AnalyticsController',\n AnalyticsControllerGetStateAction | AnalyticsControllerTrackEventAction,\n never,\n RootMessenger<DefaultActions, DefaultEvents>\n >({\n namespace: 'AnalyticsController',\n parent: messenger as RootMessenger<DefaultActions, DefaultEvents>,\n });\n analyticsMessenger.registerActionHandler(\n 'AnalyticsController:getState',\n () => ({\n ...getDefaultAnalyticsControllerState(),\n analyticsId: '',\n }),\n );\n analyticsMessenger.registerActionHandler(\n 'AnalyticsController:trackEvent',\n () => undefined,\n );\n}\n\n/**\n * Create a configured `Wallet` for daemon use, backed by a SQLite key-value\n * store for controller-state persistence.\n *\n * Loads any previously-persisted controller state from the store, seeds the\n * wallet with it, then subscribes the store to subsequent state changes so all\n * persist-flagged properties are written through.\n *\n * If the store does not yet contain a keyring vault (first run), the supplied\n * secret recovery phrase is imported using the supplied password. On\n * subsequent runs, the persisted vault is reused: when a password is\n * supplied, the wallet is unlocked via `KeyringController:submitPassword` so\n * keyring-bound messenger actions work immediately; when no password is\n * supplied, the wallet starts locked and the caller is expected to invoke\n * `mm wallet unlock` before any keyring-bound operation. First-run startup\n * without a password is rejected (the SRP cannot be imported without one).\n * On a subsequent run, a wrong password rejects startup with a `Failed to\n * unlock the persisted vault` error that wraps the `submitPassword` rejection.\n *\n * On any failure after the store is opened, the store is closed (and the wallet\n * destroyed, if constructed). On a first-run failure, the on-disk database is\n * also removed so a retry does not latch onto an orphaned partial vault — this\n * covers in-process failures only; a hard crash (SIGKILL/power loss) mid-import\n * can still leave a vault on disk.\n *\n * @param config - Wallet configuration.\n * @param config.databasePath - Path to the SQLite database file (or\n * `':memory:'` for ephemeral use).\n * @param config.password - The wallet password. Optional on subsequent runs;\n * when omitted, the daemon starts with a locked keyring. Required on first\n * run (to import the SRP).\n * @param config.srp - The secret recovery phrase (BIP-39 mnemonic). Used\n * only on first run.\n * @param config.infuraProjectId - The Infura project ID for the\n * `NetworkController`.\n * @param config.log - Optional logger for persistence-write and teardown\n * failures. Without it, failures fall back to `console.error` (which a detached\n * daemon's `stdio: 'ignore'` discards).\n * @returns The `Wallet` and a `dispose` handle that tears it down.\n */\nexport async function createWallet({\n databasePath,\n password,\n srp,\n infuraProjectId,\n log,\n}: CreateWalletConfig): Promise<CreateWalletResult> {\n const logFn = log ?? ((message: string): void => console.error(message));\n const store = new KeyValueStore(databasePath);\n let wallet: Wallet | undefined;\n let persistenceUnsubscribe: (() => void) | undefined;\n let autoApprovalUnsubscribe: (() => void) | undefined;\n let wasFirstRun = false;\n\n try {\n const state = await loadPersistedState(store, infuraProjectId, logFn);\n wasFirstRun = !hasPersistedKeyring(state);\n\n // Validate the first-run precondition BEFORE constructing the wallet,\n // so a doomed startup doesn't build a Wallet (and wire persistence\n // handlers) just to tear it down.\n if (wasFirstRun && password === undefined) {\n throw new Error(\n 'A password is required on first run to import the secret recovery phrase. ' +\n 'Pass `--password` (or `MM_WALLET_PASSWORD`) on `mm daemon start`.',\n );\n }\n\n wallet = new Wallet({\n state,\n instanceOptions: buildInstanceOptions(infuraProjectId),\n });\n registerAnalyticsStubHandlers(wallet.messenger);\n persistenceUnsubscribe = subscribeToChanges(\n wallet.messenger,\n wallet.controllerMetadata,\n store,\n logFn,\n );\n\n // Installed before `init` so any approval raised during initialization is covered.\n autoApprovalUnsubscribe = subscribeToAutoApproval(wallet.messenger, logFn);\n\n // Complete post-construction controller setup before serving requests —\n // e.g. `NetworkController.init` applies the selected network so a provider\n // is available. `init` settles every step independently; a rejected step\n // leaves the wallet only partially usable, so abort startup (the catch\n // below tears down and, on first run, removes the partial database) rather\n // than serving a degraded daemon.\n const initResults = await wallet.init();\n const initFailures = initResults.filter(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n );\n for (const failure of initFailures) {\n logFn(`Wallet init step failed: ${String(failure.reason)}`);\n }\n if (initFailures.length > 0) {\n const firstReason = String(initFailures[0].reason);\n throw new Error(\n `Wallet initialization failed (${initFailures.length} step(s)); refusing to serve a partially initialized wallet. First failure: ${firstReason}`,\n );\n }\n\n if (wasFirstRun) {\n // The precondition check above throws when `wasFirstRun && password ===\n // undefined`, so `password` is defined here. TS does not correlate the\n // two separate variables, so it cannot narrow `password` from\n // `wasFirstRun` alone — hence the assertion.\n await importSecretRecoveryPhrase(\n wallet,\n (password as Password).unwrap(),\n srp.unwrap(),\n );\n } else if (password !== undefined) {\n try {\n await wallet.messenger.call(\n 'KeyringController:submitPassword',\n password.unwrap(),\n );\n } catch (error) {\n throw new Error(\n `Failed to unlock the persisted vault: ${String(error)}`,\n );\n }\n }\n\n let disposePromise: Promise<void> | undefined;\n return {\n wallet,\n dispose: async () =>\n (disposePromise ??= teardown(\n persistenceUnsubscribe,\n autoApprovalUnsubscribe,\n wallet,\n store,\n logFn,\n )),\n };\n } catch (error) {\n await teardown(\n persistenceUnsubscribe,\n autoApprovalUnsubscribe,\n wallet,\n store,\n logFn,\n );\n\n if (wasFirstRun && databasePath !== IN_MEMORY_DATABASE_PATH) {\n // Best-effort cleanup of the on-disk SQLite files (main, WAL, SHM) so a\n // partially-persisted KeyringController vault cannot mislead the next run\n // into skipping SRP import. Covers in-process failures only — a crash\n // (SIGKILL/power loss) mid-import leaves the vault on disk.\n await Promise.all(\n [databasePath, `${databasePath}-wal`, `${databasePath}-shm`].map(\n (path) =>\n rm(path, { force: true }).catch((rmError: unknown) => {\n logFn(\n `Failed to remove ${path} during first-run cleanup: ${String(rmError)}`,\n );\n }),\n ),\n );\n }\n\n throw error;\n }\n}\n\n/**\n * Load persisted controller state, filtered to currently persist-flagged\n * properties.\n *\n * `loadState` filters against the live controller metadata, but that metadata\n * is only knowable from a constructed `Wallet` — and its output is what seeds\n * the real wallet. So this constructs a short-lived probe purely to read the\n * metadata, then tears it down.\n *\n * TODO: drop the probe once `@metamask/wallet` exposes controller metadata\n * without constructing a `Wallet`.\n *\n * @param store - The key-value store to read from.\n * @param infuraProjectId - The Infura project ID for the probe's\n * `NetworkController`.\n * @param logFn - Logger for a probe-teardown failure.\n * @returns The filtered persisted state, suitable for the `Wallet` `state`\n * option.\n */\nasync function loadPersistedState(\n store: KeyValueStore,\n infuraProjectId: string,\n logFn: Logger,\n): Promise<Record<string, Record<string, Json>>> {\n const probe = new Wallet({\n instanceOptions: buildInstanceOptions(infuraProjectId),\n });\n registerAnalyticsStubHandlers(probe.messenger);\n try {\n return loadState(store, probe.controllerMetadata);\n } finally {\n await probe.destroy().catch((error: unknown) => {\n logFn(`Metadata probe destroy failed: ${String(error)}`);\n });\n }\n}\n\n/**\n * Best-effort unsubscribe: run the function if present, logging (and\n * swallowing) any error so a later teardown step still runs.\n *\n * @param unsubscribe - The unsubscribe function, if one was registered.\n * @param label - Human-readable subscription name for the failure log.\n * @param logFn - Logger for a failure.\n */\nfunction runUnsubscribe(\n unsubscribe: (() => void) | undefined,\n label: string,\n logFn: Logger,\n): void {\n if (!unsubscribe) {\n return;\n }\n try {\n unsubscribe();\n } catch (error) {\n logFn(\n `${label} unsubscribe failed during teardown — subscription may remain ` +\n `live until the process exits: ${String(error)}`,\n );\n }\n}\n\n/**\n * Persistence-safe teardown of a wallet and its store; see {@link\n * CreateWalletResult.dispose} for the ordering rationale. Each step is\n * best-effort, so a failure is logged and the remaining steps still run.\n *\n * @param persistenceUnsubscribe - The persistence-subscription unsubscribe\n * function, if one was registered.\n * @param autoApprovalUnsubscribe - The auto-approval-subscription unsubscribe\n * function, if one was registered.\n * @param wallet - The wallet to destroy, if one was constructed.\n * @param store - The store to close.\n * @param logFn - Logger for step failures.\n */\nasync function teardown(\n persistenceUnsubscribe: (() => void) | undefined,\n autoApprovalUnsubscribe: (() => void) | undefined,\n wallet: Wallet | undefined,\n store: KeyValueStore,\n logFn: Logger,\n): Promise<void> {\n runUnsubscribe(persistenceUnsubscribe, 'Persistence', logFn);\n runUnsubscribe(autoApprovalUnsubscribe, 'Auto-approval', logFn);\n if (wallet) {\n try {\n await wallet.destroy();\n } catch (error) {\n logFn(`wallet.destroy() failed during teardown: ${String(error)}`);\n }\n }\n try {\n store.close();\n } catch (error) {\n logFn(`store.close() failed during teardown: ${String(error)}`);\n }\n}\n\n/**\n * Determine whether the loaded state already contains a keyring vault.\n *\n * The KeyringController persists its `vault` once an SRP has been imported, so\n * its presence indicates that first-run setup completed before.\n *\n * @param state - The state loaded from the key-value store.\n * @returns True if a KeyringController vault string is present.\n */\nfunction hasPersistedKeyring(\n state: Record<string, Record<string, unknown>>,\n): boolean {\n return typeof state.KeyringController?.vault === 'string';\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-factory.d.cts","sourceRoot":"","sources":["../../src/daemon/wallet-factory.ts"],"names":[],"mappings":"AAeA,OAAO,EAGL,MAAM,EACP,yBAAyB;AAY1B,OAAO,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,sBAAqB;AAClD,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAmB;AAIzC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,GAAG,EAAE,GAAG,CAAC;IACT,eAAe,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf;;;;;;;OAOG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B,CAAC;AAmIF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAsB,YAAY,CAAC,EACjC,YAAY,EACZ,QAAQ,EACR,GAAG,EACH,eAAe,EACf,GAAG,GACJ,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAwHlD"}
@@ -1,64 +0,0 @@
1
- import { Wallet } from "@metamask/wallet";
2
- import type { Password, Srp } from "./secrets.mjs";
3
- import type { Logger } from "./types.mjs";
4
- export type CreateWalletConfig = {
5
- databasePath: string;
6
- password?: Password;
7
- srp: Srp;
8
- infuraProjectId: string;
9
- log?: Logger;
10
- };
11
- export type CreateWalletResult = {
12
- wallet: Wallet;
13
- /**
14
- * Tear down everything `createWallet` set up, in the order that keeps
15
- * in-flight persistence writes valid: stop the state-change subscription,
16
- * destroy the wallet, then close the store (closing first would cause a
17
- * teardown-time persistence write to fail). Resilient — a failure in any
18
- * step is logged and the remaining steps still run — and idempotent (repeat
19
- * calls coalesce onto the same teardown).
20
- */
21
- dispose: () => Promise<void>;
22
- };
23
- /**
24
- * Create a configured `Wallet` for daemon use, backed by a SQLite key-value
25
- * store for controller-state persistence.
26
- *
27
- * Loads any previously-persisted controller state from the store, seeds the
28
- * wallet with it, then subscribes the store to subsequent state changes so all
29
- * persist-flagged properties are written through.
30
- *
31
- * If the store does not yet contain a keyring vault (first run), the supplied
32
- * secret recovery phrase is imported using the supplied password. On
33
- * subsequent runs, the persisted vault is reused: when a password is
34
- * supplied, the wallet is unlocked via `KeyringController:submitPassword` so
35
- * keyring-bound messenger actions work immediately; when no password is
36
- * supplied, the wallet starts locked and the caller is expected to invoke
37
- * `mm wallet unlock` before any keyring-bound operation. First-run startup
38
- * without a password is rejected (the SRP cannot be imported without one).
39
- * On a subsequent run, a wrong password rejects startup with a `Failed to
40
- * unlock the persisted vault` error that wraps the `submitPassword` rejection.
41
- *
42
- * On any failure after the store is opened, the store is closed (and the wallet
43
- * destroyed, if constructed). On a first-run failure, the on-disk database is
44
- * also removed so a retry does not latch onto an orphaned partial vault — this
45
- * covers in-process failures only; a hard crash (SIGKILL/power loss) mid-import
46
- * can still leave a vault on disk.
47
- *
48
- * @param config - Wallet configuration.
49
- * @param config.databasePath - Path to the SQLite database file (or
50
- * `':memory:'` for ephemeral use).
51
- * @param config.password - The wallet password. Optional on subsequent runs;
52
- * when omitted, the daemon starts with a locked keyring. Required on first
53
- * run (to import the SRP).
54
- * @param config.srp - The secret recovery phrase (BIP-39 mnemonic). Used
55
- * only on first run.
56
- * @param config.infuraProjectId - The Infura project ID for the
57
- * `NetworkController`.
58
- * @param config.log - Optional logger for persistence-write and teardown
59
- * failures. Without it, failures fall back to `console.error` (which a detached
60
- * daemon's `stdio: 'ignore'` discards).
61
- * @returns The `Wallet` and a `dispose` handle that tears it down.
62
- */
63
- export declare function createWallet({ databasePath, password, srp, infuraProjectId, log, }: CreateWalletConfig): Promise<CreateWalletResult>;
64
- //# sourceMappingURL=wallet-factory.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-factory.d.mts","sourceRoot":"","sources":["../../src/daemon/wallet-factory.ts"],"names":[],"mappings":"AAeA,OAAO,EAGL,MAAM,EACP,yBAAyB;AAY1B,OAAO,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,sBAAqB;AAClD,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAmB;AAIzC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,GAAG,EAAE,GAAG,CAAC;IACT,eAAe,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf;;;;;;;OAOG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B,CAAC;AAmIF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAsB,YAAY,CAAC,EACjC,YAAY,EACZ,QAAQ,EACR,GAAG,EACH,eAAe,EACf,GAAG,GACJ,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAwHlD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-factory.mjs","sourceRoot":"","sources":["../../src/daemon/wallet-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,uCAAuC;AAKpF,OAAO,EAAE,oBAAoB,EAAE,6CAA6C;AAC5E,OAAO,EAAE,SAAS,EAAE,4BAA4B;AAChD,OAAO,EACL,sBAAsB,EACtB,UAAU,EACV,gBAAgB,EAChB,eAAe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EAAE,aAAa,EAAE,KAAK,CAAC,CAAC;IAC7D,cAAc,CAAC,uBAAuB,EAAE,eAAe,EAAE,KAAK,CAAC,CAAC;IAChE,IAAI,MAAM,EAAE,CAAC;QACX,IAAI,CAAC;YACH,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;QACzB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,KAAK,CAAC,4CAA4C,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IACD,IAAI,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,yCAAyC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,mBAAmB,CAC1B,KAA8C;IAE9C,OAAO,OAAO,KAAK,CAAC,iBAAiB,EAAE,KAAK,KAAK,QAAQ,CAAC;AAC5D,CAAC","sourcesContent":["import { getDefaultAnalyticsControllerState } from '@metamask/analytics-controller';\nimport type {\n AnalyticsControllerGetStateAction,\n AnalyticsControllerTrackEventAction,\n} from '@metamask/analytics-controller';\nimport { ConfigRegistryApiEnv } from '@metamask/config-registry-controller';\nimport { Messenger } from '@metamask/messenger';\nimport {\n ClientConfigApiService,\n ClientType,\n DistributionType,\n EnvironmentType,\n} from '@metamask/remote-feature-flag-controller';\nimport { InMemoryStorageAdapter } from '@metamask/storage-service';\nimport type { Json } from '@metamask/utils';\nimport {\n AlwaysOnlineAdapter,\n importSecretRecoveryPhrase,\n Wallet,\n} from '@metamask/wallet';\nimport type {\n DefaultActions,\n DefaultEvents,\n RootMessenger,\n WalletOptions,\n} from '@metamask/wallet';\nimport { rm } from 'node:fs/promises';\n\nimport { KeyValueStore } from '../persistence/KeyValueStore.js';\nimport { loadState, subscribeToChanges } from '../persistence/persistence.js';\nimport { subscribeToAutoApproval } from './auto-approval.js';\nimport type { Password, Srp } from './secrets.js';\nimport type { Logger } from './types.js';\n\nconst IN_MEMORY_DATABASE_PATH = ':memory:';\n\nexport type CreateWalletConfig = {\n databasePath: string;\n password?: Password;\n srp: Srp;\n infuraProjectId: string;\n log?: Logger;\n};\n\nexport type CreateWalletResult = {\n wallet: Wallet;\n /**\n * Tear down everything `createWallet` set up, in the order that keeps\n * in-flight persistence writes valid: stop the state-change subscription,\n * destroy the wallet, then close the store (closing first would cause a\n * teardown-time persistence write to fail). Resilient — a failure in any\n * step is logged and the remaining steps still run — and idempotent (repeat\n * calls coalesce onto the same teardown).\n */\n dispose: () => Promise<void>;\n};\n\n/**\n * Build the per-instance options the daemon's `Wallet` is constructed with.\n *\n * Returns a fresh set on every call so the metadata probe and the real wallet\n * never share adapter/service instances (the probe is destroyed, which may\n * tear those instances down).\n *\n * Only the slots wired on `@metamask/wallet` today are populated:\n * - `storageService` — backed by an in-memory adapter. This is the wallet's\n * large-blob store (snap source, caches), distinct from the SQLite\n * `KeyValueStore` that persists controller state; no wired controller\n * offloads durable data to it yet, so in-memory suffices.\n * - `connectivityController` — the `AlwaysOnlineAdapter` exported for\n * node-like hosts that have no platform connectivity signal.\n * - `networkController` — the Infura project ID used to reach Infura RPC\n * endpoints.\n * - `remoteFeatureFlagController` — a `ClientConfigApiService` fetching real\n * flags over the network.\n * - `approvalController` — a no-op `showApprovalRequest` (the daemon is\n * headless); pending requests are accepted separately by the auto-approval\n * subscription `createWallet` installs, not by this hook.\n * - `gasFeeController` — only `clientId: 'cli'` (sent as `X-Client-Id` to the\n * gas API); the API endpoints, poll interval, and compatibility callbacks are\n * left at the wallet package's platform-agnostic defaults (the default\n * `EIP1559APIEndpoint` is already the production URL, so the daemon does not\n * re-specify it).\n * - `transactionController` — swaps processing disabled and no client hooks;\n * see the slot's inline comment for why the daemon relies on the\n * controller's defaults for everything else.\n *\n * The optional `keyringController` slot is intentionally omitted so the\n * controller's built-in defaults (e.g. the PBKDF2 encryptor) apply.\n *\n * @param infuraProjectId - The Infura project ID for the `NetworkController`.\n * @returns The `instanceOptions` for the `Wallet` constructor.\n */\nfunction buildInstanceOptions(\n infuraProjectId: string,\n): WalletOptions['instanceOptions'] {\n return {\n configRegistryApiService: {\n env: ConfigRegistryApiEnv.PRD,\n },\n approvalController: {\n // The daemon is headless, so there is no UI to open: requests are\n // resolved by the auto-approval subscription (see `subscribeToAutoApproval`)\n // rather than by this hook, which stays a no-op.\n // TODO: surface approval requests over the daemon transport.\n showApprovalRequest: (): undefined => undefined,\n },\n connectivityController: {\n connectivityAdapter: new AlwaysOnlineAdapter(),\n },\n gasFeeController: {\n // Identifies the CLI to the gas estimation API via the `X-Client-Id`\n // header.\n clientId: 'cli',\n },\n networkController: {\n infuraProjectId,\n },\n remoteFeatureFlagController: {\n clientConfigApiService: new ClientConfigApiService({\n fetch: globalThis.fetch,\n config: {\n // TODO: switch to a CLI-specific `ClientType` once one exists; until\n // then `Extension` buckets feature flags as an extension client.\n client: ClientType.Extension,\n distribution: DistributionType.Main,\n environment: EnvironmentType.Production,\n },\n }),\n getMetaMetricsId: (): string => 'cli',\n clientVersion: '0.0.0',\n },\n storageService: {\n storage: new InMemoryStorageAdapter(),\n },\n transactionController: {\n // The CLI exposes no swaps surface, so skip the swaps-specific\n // post-processing a full wallet client runs (mobile makes the same\n // choice; the extension keeps swaps enabled).\n disableSwaps: true,\n // No CLI-specific transaction hooks: the controller's built-in publish\n // path broadcasts through the wired `NetworkController` provider, and the\n // remaining hooks (metrics, notifications, gas-fee tokens) are client-UI\n // concerns the headless daemon has no equivalent for. Every other option\n // (`getPermittedAccounts`, `isSimulationEnabled`, `trace`, …) is left at\n // the controller's default.\n hooks: {},\n },\n };\n}\n\n/**\n * Register handlers for the `AnalyticsController` actions that\n * `NetworkController` calls to emit RPC service analytics. The daemon does not\n * report analytics, so these do nothing: `getState` returns an empty analytics\n * ID, which stops the controller before it tracks anything, and `trackEvent` is\n * a no-op. Registering them keeps those messenger calls from throwing.\n *\n * @param messenger - The wallet's root messenger.\n */\nfunction registerAnalyticsStubHandlers(messenger: Wallet['messenger']): void {\n // Register on an `AnalyticsController`-namespaced messenger, not the root: a\n // messenger can only register handlers for its own namespace, and doing so\n // delegates them up to the root, where `NetworkController` can reach them.\n const analyticsMessenger = new Messenger<\n 'AnalyticsController',\n AnalyticsControllerGetStateAction | AnalyticsControllerTrackEventAction,\n never,\n RootMessenger<DefaultActions, DefaultEvents>\n >({\n namespace: 'AnalyticsController',\n parent: messenger as RootMessenger<DefaultActions, DefaultEvents>,\n });\n analyticsMessenger.registerActionHandler(\n 'AnalyticsController:getState',\n () => ({\n ...getDefaultAnalyticsControllerState(),\n analyticsId: '',\n }),\n );\n analyticsMessenger.registerActionHandler(\n 'AnalyticsController:trackEvent',\n () => undefined,\n );\n}\n\n/**\n * Create a configured `Wallet` for daemon use, backed by a SQLite key-value\n * store for controller-state persistence.\n *\n * Loads any previously-persisted controller state from the store, seeds the\n * wallet with it, then subscribes the store to subsequent state changes so all\n * persist-flagged properties are written through.\n *\n * If the store does not yet contain a keyring vault (first run), the supplied\n * secret recovery phrase is imported using the supplied password. On\n * subsequent runs, the persisted vault is reused: when a password is\n * supplied, the wallet is unlocked via `KeyringController:submitPassword` so\n * keyring-bound messenger actions work immediately; when no password is\n * supplied, the wallet starts locked and the caller is expected to invoke\n * `mm wallet unlock` before any keyring-bound operation. First-run startup\n * without a password is rejected (the SRP cannot be imported without one).\n * On a subsequent run, a wrong password rejects startup with a `Failed to\n * unlock the persisted vault` error that wraps the `submitPassword` rejection.\n *\n * On any failure after the store is opened, the store is closed (and the wallet\n * destroyed, if constructed). On a first-run failure, the on-disk database is\n * also removed so a retry does not latch onto an orphaned partial vault — this\n * covers in-process failures only; a hard crash (SIGKILL/power loss) mid-import\n * can still leave a vault on disk.\n *\n * @param config - Wallet configuration.\n * @param config.databasePath - Path to the SQLite database file (or\n * `':memory:'` for ephemeral use).\n * @param config.password - The wallet password. Optional on subsequent runs;\n * when omitted, the daemon starts with a locked keyring. Required on first\n * run (to import the SRP).\n * @param config.srp - The secret recovery phrase (BIP-39 mnemonic). Used\n * only on first run.\n * @param config.infuraProjectId - The Infura project ID for the\n * `NetworkController`.\n * @param config.log - Optional logger for persistence-write and teardown\n * failures. Without it, failures fall back to `console.error` (which a detached\n * daemon's `stdio: 'ignore'` discards).\n * @returns The `Wallet` and a `dispose` handle that tears it down.\n */\nexport async function createWallet({\n databasePath,\n password,\n srp,\n infuraProjectId,\n log,\n}: CreateWalletConfig): Promise<CreateWalletResult> {\n const logFn = log ?? ((message: string): void => console.error(message));\n const store = new KeyValueStore(databasePath);\n let wallet: Wallet | undefined;\n let persistenceUnsubscribe: (() => void) | undefined;\n let autoApprovalUnsubscribe: (() => void) | undefined;\n let wasFirstRun = false;\n\n try {\n const state = await loadPersistedState(store, infuraProjectId, logFn);\n wasFirstRun = !hasPersistedKeyring(state);\n\n // Validate the first-run precondition BEFORE constructing the wallet,\n // so a doomed startup doesn't build a Wallet (and wire persistence\n // handlers) just to tear it down.\n if (wasFirstRun && password === undefined) {\n throw new Error(\n 'A password is required on first run to import the secret recovery phrase. ' +\n 'Pass `--password` (or `MM_WALLET_PASSWORD`) on `mm daemon start`.',\n );\n }\n\n wallet = new Wallet({\n state,\n instanceOptions: buildInstanceOptions(infuraProjectId),\n });\n registerAnalyticsStubHandlers(wallet.messenger);\n persistenceUnsubscribe = subscribeToChanges(\n wallet.messenger,\n wallet.controllerMetadata,\n store,\n logFn,\n );\n\n // Installed before `init` so any approval raised during initialization is covered.\n autoApprovalUnsubscribe = subscribeToAutoApproval(wallet.messenger, logFn);\n\n // Complete post-construction controller setup before serving requests —\n // e.g. `NetworkController.init` applies the selected network so a provider\n // is available. `init` settles every step independently; a rejected step\n // leaves the wallet only partially usable, so abort startup (the catch\n // below tears down and, on first run, removes the partial database) rather\n // than serving a degraded daemon.\n const initResults = await wallet.init();\n const initFailures = initResults.filter(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n );\n for (const failure of initFailures) {\n logFn(`Wallet init step failed: ${String(failure.reason)}`);\n }\n if (initFailures.length > 0) {\n const firstReason = String(initFailures[0].reason);\n throw new Error(\n `Wallet initialization failed (${initFailures.length} step(s)); refusing to serve a partially initialized wallet. First failure: ${firstReason}`,\n );\n }\n\n if (wasFirstRun) {\n // The precondition check above throws when `wasFirstRun && password ===\n // undefined`, so `password` is defined here. TS does not correlate the\n // two separate variables, so it cannot narrow `password` from\n // `wasFirstRun` alone — hence the assertion.\n await importSecretRecoveryPhrase(\n wallet,\n (password as Password).unwrap(),\n srp.unwrap(),\n );\n } else if (password !== undefined) {\n try {\n await wallet.messenger.call(\n 'KeyringController:submitPassword',\n password.unwrap(),\n );\n } catch (error) {\n throw new Error(\n `Failed to unlock the persisted vault: ${String(error)}`,\n );\n }\n }\n\n let disposePromise: Promise<void> | undefined;\n return {\n wallet,\n dispose: async () =>\n (disposePromise ??= teardown(\n persistenceUnsubscribe,\n autoApprovalUnsubscribe,\n wallet,\n store,\n logFn,\n )),\n };\n } catch (error) {\n await teardown(\n persistenceUnsubscribe,\n autoApprovalUnsubscribe,\n wallet,\n store,\n logFn,\n );\n\n if (wasFirstRun && databasePath !== IN_MEMORY_DATABASE_PATH) {\n // Best-effort cleanup of the on-disk SQLite files (main, WAL, SHM) so a\n // partially-persisted KeyringController vault cannot mislead the next run\n // into skipping SRP import. Covers in-process failures only — a crash\n // (SIGKILL/power loss) mid-import leaves the vault on disk.\n await Promise.all(\n [databasePath, `${databasePath}-wal`, `${databasePath}-shm`].map(\n (path) =>\n rm(path, { force: true }).catch((rmError: unknown) => {\n logFn(\n `Failed to remove ${path} during first-run cleanup: ${String(rmError)}`,\n );\n }),\n ),\n );\n }\n\n throw error;\n }\n}\n\n/**\n * Load persisted controller state, filtered to currently persist-flagged\n * properties.\n *\n * `loadState` filters against the live controller metadata, but that metadata\n * is only knowable from a constructed `Wallet` — and its output is what seeds\n * the real wallet. So this constructs a short-lived probe purely to read the\n * metadata, then tears it down.\n *\n * TODO: drop the probe once `@metamask/wallet` exposes controller metadata\n * without constructing a `Wallet`.\n *\n * @param store - The key-value store to read from.\n * @param infuraProjectId - The Infura project ID for the probe's\n * `NetworkController`.\n * @param logFn - Logger for a probe-teardown failure.\n * @returns The filtered persisted state, suitable for the `Wallet` `state`\n * option.\n */\nasync function loadPersistedState(\n store: KeyValueStore,\n infuraProjectId: string,\n logFn: Logger,\n): Promise<Record<string, Record<string, Json>>> {\n const probe = new Wallet({\n instanceOptions: buildInstanceOptions(infuraProjectId),\n });\n registerAnalyticsStubHandlers(probe.messenger);\n try {\n return loadState(store, probe.controllerMetadata);\n } finally {\n await probe.destroy().catch((error: unknown) => {\n logFn(`Metadata probe destroy failed: ${String(error)}`);\n });\n }\n}\n\n/**\n * Best-effort unsubscribe: run the function if present, logging (and\n * swallowing) any error so a later teardown step still runs.\n *\n * @param unsubscribe - The unsubscribe function, if one was registered.\n * @param label - Human-readable subscription name for the failure log.\n * @param logFn - Logger for a failure.\n */\nfunction runUnsubscribe(\n unsubscribe: (() => void) | undefined,\n label: string,\n logFn: Logger,\n): void {\n if (!unsubscribe) {\n return;\n }\n try {\n unsubscribe();\n } catch (error) {\n logFn(\n `${label} unsubscribe failed during teardown — subscription may remain ` +\n `live until the process exits: ${String(error)}`,\n );\n }\n}\n\n/**\n * Persistence-safe teardown of a wallet and its store; see {@link\n * CreateWalletResult.dispose} for the ordering rationale. Each step is\n * best-effort, so a failure is logged and the remaining steps still run.\n *\n * @param persistenceUnsubscribe - The persistence-subscription unsubscribe\n * function, if one was registered.\n * @param autoApprovalUnsubscribe - The auto-approval-subscription unsubscribe\n * function, if one was registered.\n * @param wallet - The wallet to destroy, if one was constructed.\n * @param store - The store to close.\n * @param logFn - Logger for step failures.\n */\nasync function teardown(\n persistenceUnsubscribe: (() => void) | undefined,\n autoApprovalUnsubscribe: (() => void) | undefined,\n wallet: Wallet | undefined,\n store: KeyValueStore,\n logFn: Logger,\n): Promise<void> {\n runUnsubscribe(persistenceUnsubscribe, 'Persistence', logFn);\n runUnsubscribe(autoApprovalUnsubscribe, 'Auto-approval', logFn);\n if (wallet) {\n try {\n await wallet.destroy();\n } catch (error) {\n logFn(`wallet.destroy() failed during teardown: ${String(error)}`);\n }\n }\n try {\n store.close();\n } catch (error) {\n logFn(`store.close() failed during teardown: ${String(error)}`);\n }\n}\n\n/**\n * Determine whether the loaded state already contains a keyring vault.\n *\n * The KeyringController persists its `vault` once an SRP has been imported, so\n * its presence indicates that first-run setup completed before.\n *\n * @param state - The state loaded from the key-value store.\n * @returns True if a KeyringController vault string is present.\n */\nfunction hasPersistedKeyring(\n state: Record<string, Record<string, unknown>>,\n): boolean {\n return typeof state.KeyringController?.vault === 'string';\n}\n"]}
@@ -1,79 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- var _KeyValueStore_db, _KeyValueStore_getStmt, _KeyValueStore_setStmt, _KeyValueStore_deleteStmt, _KeyValueStore_getAllStmt;
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.KeyValueStore = void 0;
19
- const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
20
- /**
21
- * A synchronous key-value store backed by better-sqlite3.
22
- *
23
- * Uses a single `kv` table with TEXT key (primary key) and TEXT value
24
- * (JSON-serialized). Intended as the persistence backend for wallet
25
- * controller state.
26
- */
27
- class KeyValueStore {
28
- constructor(databasePath) {
29
- _KeyValueStore_db.set(this, void 0);
30
- _KeyValueStore_getStmt.set(this, void 0);
31
- _KeyValueStore_setStmt.set(this, void 0);
32
- _KeyValueStore_deleteStmt.set(this, void 0);
33
- _KeyValueStore_getAllStmt.set(this, void 0);
34
- __classPrivateFieldSet(this, _KeyValueStore_db, new better_sqlite3_1.default(databasePath), "f");
35
- __classPrivateFieldGet(this, _KeyValueStore_db, "f").pragma('journal_mode = WAL');
36
- __classPrivateFieldGet(this, _KeyValueStore_db, "f").exec('CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
37
- __classPrivateFieldSet(this, _KeyValueStore_getStmt, __classPrivateFieldGet(this, _KeyValueStore_db, "f").prepare('SELECT value FROM kv WHERE key = ?'), "f");
38
- __classPrivateFieldSet(this, _KeyValueStore_setStmt, __classPrivateFieldGet(this, _KeyValueStore_db, "f").prepare('INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)'), "f");
39
- __classPrivateFieldSet(this, _KeyValueStore_deleteStmt, __classPrivateFieldGet(this, _KeyValueStore_db, "f").prepare('DELETE FROM kv WHERE key = ?'), "f");
40
- __classPrivateFieldSet(this, _KeyValueStore_getAllStmt, __classPrivateFieldGet(this, _KeyValueStore_db, "f").prepare('SELECT key, value FROM kv'), "f");
41
- }
42
- get(key) {
43
- const row = __classPrivateFieldGet(this, _KeyValueStore_getStmt, "f").get(key);
44
- if (!row) {
45
- return undefined;
46
- }
47
- try {
48
- return JSON.parse(row.value);
49
- }
50
- catch {
51
- throw new Error(`Failed to parse stored value for key '${key}'`);
52
- }
53
- }
54
- set(key, value) {
55
- __classPrivateFieldGet(this, _KeyValueStore_setStmt, "f").run(key, JSON.stringify(value));
56
- }
57
- getAll() {
58
- const rows = __classPrivateFieldGet(this, _KeyValueStore_getAllStmt, "f").all();
59
- const result = {};
60
- for (const row of rows) {
61
- try {
62
- result[row.key] = JSON.parse(row.value);
63
- }
64
- catch {
65
- throw new Error(`Failed to parse stored value for key '${row.key}'`);
66
- }
67
- }
68
- return result;
69
- }
70
- delete(key) {
71
- __classPrivateFieldGet(this, _KeyValueStore_deleteStmt, "f").run(key);
72
- }
73
- close() {
74
- __classPrivateFieldGet(this, _KeyValueStore_db, "f").close();
75
- }
76
- }
77
- exports.KeyValueStore = KeyValueStore;
78
- _KeyValueStore_db = new WeakMap(), _KeyValueStore_getStmt = new WeakMap(), _KeyValueStore_setStmt = new WeakMap(), _KeyValueStore_deleteStmt = new WeakMap(), _KeyValueStore_getAllStmt = new WeakMap();
79
- //# sourceMappingURL=KeyValueStore.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"KeyValueStore.cjs","sourceRoot":"","sources":["../../src/persistence/KeyValueStore.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA,oEAAoC;AAEpC;;;;;;GAMG;AACH,MAAa,aAAa;IAWxB,YAAY,YAAoB;QAVvB,oCAAqB;QAErB,yCAAoE;QAEpE,yCAAmD;QAEnD,4CAA8C;QAE9C,4CAAkE;QAGzE,uBAAA,IAAI,qBAAO,IAAI,wBAAM,CAAC,YAAY,CAAC,MAAA,CAAC;QACpC,uBAAA,IAAI,yBAAI,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;QACtC,uBAAA,IAAI,yBAAI,CAAC,IAAI,CACX,2EAA2E,CAC5E,CAAC;QAEF,uBAAA,IAAI,0BAAY,uBAAA,IAAI,yBAAI,CAAC,OAAO,CAAC,oCAAoC,CAAC,MAAA,CAAC;QACvE,uBAAA,IAAI,0BAAY,uBAAA,IAAI,yBAAI,CAAC,OAAO,CAC9B,sDAAsD,CACvD,MAAA,CAAC;QACF,uBAAA,IAAI,6BAAe,uBA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AC;IAED,KAAK;QACH,uBAAA,IAAI,yBAAI,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;CACF;AA9DD,sCA8DC","sourcesContent":["import type { Json } from '@metamask/utils';\nimport Sqlite from 'better-sqlite3';\n\n/**\n * A synchronous key-value store backed by better-sqlite3.\n *\n * Uses a single `kv` table with TEXT key (primary key) and TEXT value\n * (JSON-serialized). Intended as the persistence backend for wallet\n * controller state.\n */\nexport class KeyValueStore {\n readonly #db: Sqlite.Database;\n\n readonly #getStmt: Sqlite.Statement<[string], { value: string } | undefined>;\n\n readonly #setStmt: Sqlite.Statement<[string, string], void>;\n\n readonly #deleteStmt: Sqlite.Statement<[string], void>;\n\n readonly #getAllStmt: Sqlite.Statement<[], { key: string; value: string }>;\n\n constructor(databasePath: string) {\n this.#db = new Sqlite(databasePath);\n this.#db.pragma('journal_mode = WAL');\n this.#db.exec(\n 'CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)',\n );\n\n this.#getStmt = this.#db.prepare('SELECT value FROM kv WHERE key = ?');\n this.#setStmt = this.#db.prepare(\n 'INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)',\n );\n this.#deleteStmt = this.#db.prepare('DELETE FROM kv WHERE key = ?');\n this.#getAllStmt = this.#db.prepare('SELECT key, value FROM kv');\n }\n\n get(key: string): Json | undefined {\n const row = this.#getStmt.get(key);\n if (!row) {\n return undefined;\n }\n try {\n return JSON.parse(row.value);\n } catch {\n throw new Error(`Failed to parse stored value for key '${key}'`);\n }\n }\n\n set(key: string, value: Json): void {\n this.#setStmt.run(key, JSON.stringify(value));\n }\n\n getAll(): Record<string, Json> {\n const rows = this.#getAllStmt.all();\n const result: Record<string, Json> = {};\n for (const row of rows) {\n try {\n result[row.key] = JSON.parse(row.value);\n } catch {\n throw new Error(`Failed to parse stored value for key '${row.key}'`);\n }\n }\n return result;\n }\n\n delete(key: string): void {\n this.#deleteStmt.run(key);\n }\n\n close(): void {\n this.#db.close();\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"KeyValueStore.d.cts","sourceRoot":"","sources":["../../src/persistence/KeyValueStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAG5C;;;;;;GAMG;AACH,qBAAa,aAAa;;gBAWZ,YAAY,EAAE,MAAM;IAehC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IAYlC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,IAAI;IAInC,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC;IAa9B,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIzB,KAAK,IAAI,IAAI;CAGd"}
@@ -1,18 +0,0 @@
1
- import type { Json } from "@metamask/utils";
2
- /**
3
- * A synchronous key-value store backed by better-sqlite3.
4
- *
5
- * Uses a single `kv` table with TEXT key (primary key) and TEXT value
6
- * (JSON-serialized). Intended as the persistence backend for wallet
7
- * controller state.
8
- */
9
- export declare class KeyValueStore {
10
- #private;
11
- constructor(databasePath: string);
12
- get(key: string): Json | undefined;
13
- set(key: string, value: Json): void;
14
- getAll(): Record<string, Json>;
15
- delete(key: string): void;
16
- close(): void;
17
- }
18
- //# sourceMappingURL=KeyValueStore.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"KeyValueStore.d.mts","sourceRoot":"","sources":["../../src/persistence/KeyValueStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAG5C;;;;;;GAMG;AACH,qBAAa,aAAa;;gBAWZ,YAAY,EAAE,MAAM;IAehC,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IAYlC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,IAAI;IAInC,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC;IAa9B,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAIzB,KAAK,IAAI,IAAI;CAGd"}
@@ -1,79 +0,0 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _KeyValueStore_db, _KeyValueStore_getStmt, _KeyValueStore_setStmt, _KeyValueStore_deleteStmt, _KeyValueStore_getAllStmt;
13
- function $importDefault(module) {
14
- if (module?.__esModule) {
15
- return module.default;
16
- }
17
- return module;
18
- }
19
- import $Sqlite from "better-sqlite3";
20
- const Sqlite = $importDefault($Sqlite);
21
- /**
22
- * A synchronous key-value store backed by better-sqlite3.
23
- *
24
- * Uses a single `kv` table with TEXT key (primary key) and TEXT value
25
- * (JSON-serialized). Intended as the persistence backend for wallet
26
- * controller state.
27
- */
28
- export class KeyValueStore {
29
- constructor(databasePath) {
30
- _KeyValueStore_db.set(this, void 0);
31
- _KeyValueStore_getStmt.set(this, void 0);
32
- _KeyValueStore_setStmt.set(this, void 0);
33
- _KeyValueStore_deleteStmt.set(this, void 0);
34
- _KeyValueStore_getAllStmt.set(this, void 0);
35
- __classPrivateFieldSet(this, _KeyValueStore_db, new Sqlite(databasePath), "f");
36
- __classPrivateFieldGet(this, _KeyValueStore_db, "f").pragma('journal_mode = WAL');
37
- __classPrivateFieldGet(this, _KeyValueStore_db, "f").exec('CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
38
- __classPrivateFieldSet(this, _KeyValueStore_getStmt, __classPrivateFieldGet(this, _KeyValueStore_db, "f").prepare('SELECT value FROM kv WHERE key = ?'), "f");
39
- __classPrivateFieldSet(this, _KeyValueStore_setStmt, __classPrivateFieldGet(this, _KeyValueStore_db, "f").prepare('INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)'), "f");
40
- __classPrivateFieldSet(this, _KeyValueStore_deleteStmt, __classPrivateFieldGet(this, _KeyValueStore_db, "f").prepare('DELETE FROM kv WHERE key = ?'), "f");
41
- __classPrivateFieldSet(this, _KeyValueStore_getAllStmt, __classPrivateFieldGet(this, _KeyValueStore_db, "f").prepare('SELECT key, value FROM kv'), "f");
42
- }
43
- get(key) {
44
- const row = __classPrivateFieldGet(this, _KeyValueStore_getStmt, "f").get(key);
45
- if (!row) {
46
- return undefined;
47
- }
48
- try {
49
- return JSON.parse(row.value);
50
- }
51
- catch {
52
- throw new Error(`Failed to parse stored value for key '${key}'`);
53
- }
54
- }
55
- set(key, value) {
56
- __classPrivateFieldGet(this, _KeyValueStore_setStmt, "f").run(key, JSON.stringify(value));
57
- }
58
- getAll() {
59
- const rows = __classPrivateFieldGet(this, _KeyValueStore_getAllStmt, "f").all();
60
- const result = {};
61
- for (const row of rows) {
62
- try {
63
- result[row.key] = JSON.parse(row.value);
64
- }
65
- catch {
66
- throw new Error(`Failed to parse stored value for key '${row.key}'`);
67
- }
68
- }
69
- return result;
70
- }
71
- delete(key) {
72
- __classPrivateFieldGet(this, _KeyValueStore_deleteStmt, "f").run(key);
73
- }
74
- close() {
75
- __classPrivateFieldGet(this, _KeyValueStore_db, "f").close();
76
- }
77
- }
78
- _KeyValueStore_db = new WeakMap(), _KeyValueStore_getStmt = new WeakMap(), _KeyValueStore_setStmt = new WeakMap(), _KeyValueStore_deleteStmt = new WeakMap(), _KeyValueStore_getAllStmt = new WeakMap();
79
- //# sourceMappingURL=KeyValueStore.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"KeyValueStore.mjs","sourceRoot":"","sources":["../../src/persistence/KeyValueStore.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA,OAAO,OAAM,uBAAuB;;AAEpC;;;;;;GAMG;AACH,MAAM,OAAO,aAAa;IAWxB,YAAY,YAAoB;QAVvB,oCAAqB;QAErB,yCAAoE;QAEpE,yCAAmD;QAEnD,4CAA8C;QAE9C,4CAAkE;QAGzE,uBAAA,IAAI,qBAAO,IAAI,MAAM,CAAC,YAAY,CAAC,MAAA,CAAC;QACpC,uBAAA,IAAI,yBAAI,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;QACtC,uBAAA,IAAI,yBAAI,CAAC,IAAI,CACX,2EAA2E,CAC5E,CAAC;QAEF,uBAAA,IAAI,0BAAY,uBAAA,IAAI,yBAAI,CAAC,OAAO,CAAC,oCAAoC,CAAC,MAAA,CAAC;QACvE,uBAAA,IAAI,0BAAY,uBAAA,IAAI,yBAAI,CAAC,OAAO,CAC9B,sDAAsD,CACvD,MAAA,CAAC;QACF,uBAAA,IAAI,6BAAe,uBAAA,IAAI,yBAAI,CAAC,OAAO,CAAC,8BAA8B,CAAC,MAAA,CAAC;QACpE,uBAAA,IAAI,6BAAe,uBAAA,IAAI,yBAAI,CAAC,OAAO,CAAC,2BAA2B,CAAC,MAAA,CAAC;IACnE,CAAC;IAED,GAAG,CAAC,GAAW;QACb,MAAM,GAAG,GAAG,uBAAA,IAAI,8BAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACnC,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,yCAAyC,GAAG,GAAG,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;IAED,GAAG,CAAC,GAAW,EAAE,KAAW;QAC1B,uBAAA,IAAI,8BAAS,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,MAAM;QACJ,MAAM,IAAI,GAAG,uBAAA,IAAI,iCAAY,CAAC,GAAG,EAAE,CAAC;QACpC,MAAM,MAAM,GAAyB,EAAE,CAAC;QACxC,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC;gBACH,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAC1C,CAAC;YAAC,MAAM,CAAC;gBACP,MAAM,IAAI,KAAK,CAAC,yCAAyC,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC;YACvE,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,GAAW;QAChB,uBAAA,IAAI,iCAAY,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC5B,CAAC;IAED,KAAK;QACH,uBAAA,IAAI,yBAAI,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;CACF","sourcesContent":["import type { Json } from '@metamask/utils';\nimport Sqlite from 'better-sqlite3';\n\n/**\n * A synchronous key-value store backed by better-sqlite3.\n *\n * Uses a single `kv` table with TEXT key (primary key) and TEXT value\n * (JSON-serialized). Intended as the persistence backend for wallet\n * controller state.\n */\nexport class KeyValueStore {\n readonly #db: Sqlite.Database;\n\n readonly #getStmt: Sqlite.Statement<[string], { value: string } | undefined>;\n\n readonly #setStmt: Sqlite.Statement<[string, string], void>;\n\n readonly #deleteStmt: Sqlite.Statement<[string], void>;\n\n readonly #getAllStmt: Sqlite.Statement<[], { key: string; value: string }>;\n\n constructor(databasePath: string) {\n this.#db = new Sqlite(databasePath);\n this.#db.pragma('journal_mode = WAL');\n this.#db.exec(\n 'CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)',\n );\n\n this.#getStmt = this.#db.prepare('SELECT value FROM kv WHERE key = ?');\n this.#setStmt = this.#db.prepare(\n 'INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)',\n );\n this.#deleteStmt = this.#db.prepare('DELETE FROM kv WHERE key = ?');\n this.#getAllStmt = this.#db.prepare('SELECT key, value FROM kv');\n }\n\n get(key: string): Json | undefined {\n const row = this.#getStmt.get(key);\n if (!row) {\n return undefined;\n }\n try {\n return JSON.parse(row.value);\n } catch {\n throw new Error(`Failed to parse stored value for key '${key}'`);\n }\n }\n\n set(key: string, value: Json): void {\n this.#setStmt.run(key, JSON.stringify(value));\n }\n\n getAll(): Record<string, Json> {\n const rows = this.#getAllStmt.all();\n const result: Record<string, Json> = {};\n for (const row of rows) {\n try {\n result[row.key] = JSON.parse(row.value);\n } catch {\n throw new Error(`Failed to parse stored value for key '${row.key}'`);\n }\n }\n return result;\n }\n\n delete(key: string): void {\n this.#deleteStmt.run(key);\n }\n\n close(): void {\n this.#db.close();\n }\n}\n"]}
@@ -1,204 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.subscribeToChanges = exports.loadState = void 0;
4
- const utils_1 = require("@metamask/utils");
5
- /**
6
- * Construct a store key from a controller name and property name.
7
- *
8
- * @param controllerName - The controller name.
9
- * @param propertyName - The property name.
10
- * @returns The store key in the format `ControllerName.propertyName`.
11
- */
12
- function storeKey(controllerName, propertyName) {
13
- return `${controllerName}.${propertyName}`;
14
- }
15
- /**
16
- * Load persisted state from the key-value store and reconstruct it as
17
- * a record keyed by controller name.
18
- *
19
- * Keys in the store follow the format `ControllerName.propertyName`.
20
- * This function groups them into `{ [controllerName]: { [propertyName]: value } }`.
21
- *
22
- * Only properties that are currently persist-flagged in `controllerMetadata`
23
- * are rehydrated. Rows for controllers or properties that no longer exist — or
24
- * whose `persist` flag has since been disabled — are ignored. This keeps
25
- * loading symmetric with {@link subscribeToChanges}, which only ever writes
26
- * persist-flagged properties: without the filter, a migration that stops
27
- * persisting a property would leave its stale row on disk to be resurrected
28
- * into the `Wallet` constructor state on the next restart.
29
- *
30
- * @param store - The key-value store to read from.
31
- * @param controllerMetadata - A map from controller name to its state metadata,
32
- * used to filter out keys that are no longer persist-flagged.
33
- * @returns A record of controller states, keyed by controller name, suitable
34
- * for the `state` option of the `Wallet` constructor.
35
- */
36
- function loadState(store, controllerMetadata) {
37
- const allPairs = store.getAll();
38
- const state = {};
39
- for (const [key, value] of Object.entries(allPairs)) {
40
- const dotIndex = key.indexOf('.');
41
- if (dotIndex === -1) {
42
- throw new Error(`Invalid key in store: '${key}'. Expected format 'ControllerName.propertyName'.`);
43
- }
44
- const controllerName = key.slice(0, dotIndex);
45
- const propertyName = key.slice(dotIndex + 1);
46
- if (!controllerName || !propertyName) {
47
- throw new Error(`Invalid key in store: '${key}'. Both controller name and property name must be non-empty.`);
48
- }
49
- if (!isPersisted(controllerMetadata[controllerName], propertyName)) {
50
- continue;
51
- }
52
- if (!state[controllerName]) {
53
- state[controllerName] = {};
54
- }
55
- state[controllerName][propertyName] = value;
56
- }
57
- return state;
58
- }
59
- exports.loadState = loadState;
60
- /**
61
- * Subscribe to all controller `stateChanged` events and persist changes
62
- * to the key-value store.
63
- *
64
- * For each controller's metadata, this function determines which state
65
- * properties are persist-flagged. When a `stateChanged` event fires, it uses
66
- * the Immer patches to identify which top-level properties changed, filters
67
- * to only persist-flagged properties, and writes them to the store.
68
- *
69
- * @param messenger - The root messenger to subscribe on.
70
- * @param controllerMetadata - A map from controller name to its state metadata.
71
- * @param store - The key-value store to write to.
72
- * @param log - Optional logger for persistence-write failures. Defaults to
73
- * `console.error` when omitted. A daemon host should supply its own logger,
74
- * since a backgrounded daemon's stdio may be discarded.
75
- * @returns A function that unsubscribes all persistence handlers.
76
- */
77
- function subscribeToChanges(messenger, controllerMetadata, store, log) {
78
- const unsubscribers = [];
79
- const logFn = log ??
80
- ((message) => {
81
- console.error(message);
82
- });
83
- for (const [controllerName, metadata] of Object.entries(controllerMetadata)) {
84
- const persistedProperties = getPersistPropertyNames(metadata);
85
- if (persistedProperties.size === 0) {
86
- continue;
87
- }
88
- const eventType = `${controllerName}:stateChanged`;
89
- const handler = (state, patches) => {
90
- const changed = getChangedProperties(patches, persistedProperties);
91
- for (const prop of changed) {
92
- const key = storeKey(controllerName, prop);
93
- const removed = !(0, utils_1.hasProperty)(state, prop);
94
- // Derive the value before the try/catch so a throwing `StateDeriver`
95
- // surfaces as its own error instead of a misreported write failure.
96
- const persistFlag = metadata[prop]?.persist;
97
- const value = !removed && typeof persistFlag === 'function'
98
- ? persistFlag(state[prop])
99
- : state[prop];
100
- try {
101
- if (removed) {
102
- store.delete(key);
103
- }
104
- else {
105
- store.set(key, value);
106
- }
107
- }
108
- catch (error) {
109
- // TODO: Surface persistence-write failures up the stack so callers
110
- // can decide to halt rather than continue with diverging in-memory
111
- // and on-disk state. For now, log and continue.
112
- logFn(`Failed to persist state for ${key}: ${String(error)}`);
113
- }
114
- }
115
- };
116
- unsubscribers.push(subscribeToStateChanged(messenger, eventType, handler));
117
- }
118
- const unsubscribeAll = () => {
119
- while (unsubscribers.length > 0) {
120
- unsubscribers.pop()?.();
121
- }
122
- };
123
- return unsubscribeAll;
124
- }
125
- exports.subscribeToChanges = subscribeToChanges;
126
- /**
127
- * Subscribe a handler to a controller's `stateChanged` event.
128
- *
129
- * The event name is built from a runtime controller name, so it widens to
130
- * `string` and cannot be proven to be a literal member of the messenger's event
131
- * union at compile time. This helper localizes that single unavoidable cast
132
- * behind a typed {@link StateChangedHandler}, so the `(state, patches)` payload
133
- * shape stays compile-checked at every call site instead of being erased by a
134
- * statement-level `@ts-expect-error`.
135
- *
136
- * @param messenger - The root messenger to subscribe on.
137
- * @param eventType - The `${controllerName}:stateChanged` event name.
138
- * @param handler - The state-change handler to register.
139
- * @returns A function that unsubscribes the handler.
140
- */
141
- function subscribeToStateChanged(messenger, eventType, handler) {
142
- const subscriber = messenger;
143
- subscriber.subscribe(eventType, handler);
144
- return () => {
145
- subscriber.unsubscribe(eventType, handler);
146
- };
147
- }
148
- /**
149
- * Determine whether a property is currently persist-flagged.
150
- *
151
- * The `persist` flag is truthy when it is `true` or a `StateDeriver` function,
152
- * and falsy when it is `false` or when the controller or property is absent
153
- * from the metadata. `loadState` and `subscribeToChanges` share this predicate
154
- * so the read and write paths can never disagree on what counts as persisted.
155
- *
156
- * @param metadata - The controller's state metadata, or `undefined` when the
157
- * controller is absent from the metadata map.
158
- * @param propertyName - The property name to check.
159
- * @returns `true` if the property should be persisted.
160
- */
161
- function isPersisted(metadata, propertyName) {
162
- return Boolean(metadata?.[propertyName]?.persist);
163
- }
164
- /**
165
- * Get the set of property names whose `persist` metadata is truthy
166
- * (either `true` or a `StateDeriver` function).
167
- *
168
- * @param metadata - The controller's state metadata.
169
- * @returns A set of property names that should be persisted.
170
- */
171
- function getPersistPropertyNames(metadata) {
172
- const names = new Set();
173
- for (const key of Object.keys(metadata)) {
174
- if (isPersisted(metadata, key)) {
175
- names.add(key);
176
- }
177
- }
178
- return names;
179
- }
180
- /**
181
- * Extracts the set of persist-flagged top-level property names that changed
182
- * from an array of Immer patches.
183
- *
184
- * If any patch has an empty path (indicating a root state replacement),
185
- * all persist-flagged properties are returned.
186
- *
187
- * @param patches - Immer patches from a state update.
188
- * @param persistedProperties - The set of persist-flagged property names.
189
- * @returns A set of top-level property names that were modified.
190
- */
191
- function getChangedProperties(patches, persistedProperties) {
192
- const changed = new Set();
193
- for (const patch of patches) {
194
- if (patch.path.length === 0) {
195
- return persistedProperties;
196
- }
197
- const prop = String(patch.path[0]);
198
- if (persistedProperties.has(prop)) {
199
- changed.add(prop);
200
- }
201
- }
202
- return changed;
203
- }
204
- //# sourceMappingURL=persistence.cjs.map