@exodus/headless 2.0.0-alpha.12 → 2.0.0-alpha.121

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.
@@ -2,10 +2,6 @@ export const wrapConstant = ({ id, type, value }) => ({
2
2
  definition: { id, type, factory: () => value },
3
3
  })
4
4
 
5
- export const insertIf = (module, enabled) => {
6
- return enabled ? [module] : []
7
- }
8
-
9
5
  export const withType =
10
6
  (type) =>
11
7
  ({ definition, ...rest }) => ({
package/src/index.js CHANGED
@@ -1,110 +1,117 @@
1
- import { pick } from '@exodus/basic-utils'
2
- import createIOC from './ioc'
3
- import createApi from './api'
4
- import {
5
- createAccountStatesUpdateHandler,
6
- createLoadWalletAccountsHandler,
7
- } from './utils/blockchain-metadata'
1
+ import addressProvider from '@exodus/address-provider'
2
+ import availableAssets from '@exodus/available-assets'
3
+ import balances from '@exodus/balances'
4
+ import blockchainMetadata from '@exodus/blockchain-metadata'
5
+ import enabledAssets from '@exodus/enabled-assets'
6
+ import featureFlags from '@exodus/feature-flags'
7
+ import fees from '@exodus/fee-monitors'
8
+ import geolocation from '@exodus/geolocation'
9
+ import keychain from '@exodus/keychain'
10
+ import locale from '@exodus/locale'
11
+ import pricing from '@exodus/pricing'
12
+ import rates from '@exodus/rates-monitor'
13
+ import remoteConfig from '@exodus/remote-config'
14
+ import restoreProgressTracker from '@exodus/restore-progress-tracker'
15
+ import wallet from '@exodus/wallet'
16
+ import walletAccounts from '@exodus/wallet-accounts'
8
17
 
18
+ import createApi from './api'
19
+ import createIOC from './ioc'
20
+ import attachMigrations from './migrations/attach'
9
21
  import attachPlugins from './plugins/attach'
10
- import attachAtoms from './atoms/attach'
11
- import { atomsToAttach } from './constants'
12
22
 
13
23
  const createExodus = ({ adapters, config, port }) => {
14
24
  const ioc = createIOC({ adapters, config })
15
- const { headless: headlessConfig } = config
25
+
26
+ ioc.use(addressProvider({ config: config.addressProvider }))
27
+ ioc.use(availableAssets())
28
+ ioc.use(balances(config.balances))
29
+ ioc.use(blockchainMetadata())
30
+ ioc.use(enabledAssets())
31
+ ioc.use(featureFlags())
32
+ ioc.use(fees())
33
+ ioc.use(geolocation())
34
+ ioc.use(keychain(config.keychain))
35
+ ioc.use(locale())
36
+ ioc.use(pricing())
37
+ ioc.use(rates())
38
+ ioc.use(remoteConfig())
39
+ ioc.use(restoreProgressTracker())
40
+ ioc.use(wallet())
41
+ ioc.use(walletAccounts())
42
+
43
+ ioc.register({ definition: { id: 'port', type: 'port', factory: () => port } })
16
44
 
17
45
  const resolve = () => {
18
46
  ioc.resolve()
19
47
 
20
- const { assetsModule, storage } = ioc.getByType('adapter')
48
+ const { assetsModule, storage, fusion } = ioc.getByType('adapter')
21
49
 
22
- const {
23
- application,
24
- blockchainMetadata,
25
- enabledAssets,
26
- remoteConfig,
27
- unlockEncryptedStorage,
28
- walletAccounts,
29
- } = ioc.getByType('module')
30
-
31
- const { marketHistory } = ioc.getByType('monitor')
32
-
33
- const handleLoadWalletAccounts = createLoadWalletAccountsHandler({
34
- blockchainMetadata,
35
- port,
36
- config,
37
- })
50
+ const { lockedAtom } = ioc.getByType('atom')
38
51
 
39
- const handleAccountStatesUpdate = createAccountStatesUpdateHandler({
40
- blockchainMetadata,
41
- port,
42
- config,
43
- })
52
+ const { application, wallet, unlockEncryptedStorage } = ioc.getByType('module')
44
53
 
45
- blockchainMetadata.on('load-wallet-accounts', handleLoadWalletAccounts)
46
- blockchainMetadata.on('tx-logs-update', (payload) => port.emit('tx-logs-update', payload))
47
- blockchainMetadata.on('account-states-update', handleAccountStatesUpdate)
54
+ const { migrations } = ioc.getAll()
48
55
 
49
- remoteConfig.on('sync', ({ current }) => port.emit('remote-config', current))
56
+ application.on('start', (payload) => port.emit('start', payload))
50
57
 
51
- // TODO: migrate to marketHistoryAtom. Will be easier once it's on headless
52
- marketHistory.on('market-history', (payload) => port.emit('market-history', payload))
58
+ application.on('load', (args) => port.emit('load', args))
53
59
 
54
- application.hook('start', () => {
55
- remoteConfig.load()
60
+ application.on('create', async ({ hasPassphraseSet }) => {
61
+ const isLocked = await wallet.isLocked()
56
62
 
57
- port.emit('start')
63
+ port.emit('create', {
64
+ walletExists: true,
65
+ hasPassphraseSet,
66
+ isLocked,
67
+ isBackedUp: false,
68
+ isRestoring: false,
69
+ })
58
70
  })
59
71
 
60
- application.hook('unlock', async () => {
61
- if (typeof storage.unlock === 'function') unlockEncryptedStorage(storage)
72
+ application.on('unlock', () => port.emit('unlock'))
73
+
74
+ application.on('lock', () => port.emit('lock'))
62
75
 
63
- remoteConfig.sync()
64
- marketHistory.start()
76
+ application.on('backup', () => port.emit('backup'))
65
77
 
66
- await assetsModule.load()
67
- await walletAccounts.load()
68
- await Promise.all([
69
- //
70
- blockchainMetadata.load(),
71
- enabledAssets.load(),
72
- ])
78
+ application.on('restore', () => port.emit('restore'))
79
+
80
+ application.on('restore-completed', () => {
81
+ port.emit('restore-completed')
73
82
  })
74
83
 
75
- application.on('unlock', () => {
76
- port.emit('unlock')
84
+ application.on('change-passphrase', () => port.emit('passphrase-changed'))
85
+
86
+ application.on('import', () => port.emit('import', { walletExists: true }))
87
+
88
+ application.hook('unlock', async () => {
89
+ if (typeof storage.unlock === 'function') unlockEncryptedStorage(storage)
77
90
  })
78
91
 
79
92
  application.hook('clear', async () => {
80
- await Promise.all([
81
- //
82
- assetsModule.clear(),
83
- walletAccounts.clear(),
84
- blockchainMetadata.clear(),
85
- enabledAssets.clear(),
86
- ])
87
-
88
- port.emit('clear')
93
+ await Promise.all([assetsModule.clear(), fusion.clearStorage()])
89
94
  })
90
95
 
91
- application.on('restart', (payload) => {
92
- port.emit('restart', payload)
93
- })
96
+ application.on('clear', () => port.emit('clear'))
97
+
98
+ application.on('restart', (payload) => port.emit('restart', payload))
94
99
 
95
- attachAtoms({
96
- port,
100
+ attachMigrations({
101
+ migrations,
102
+ adapters,
97
103
  application,
98
- logger: ioc.get('createLogger')('attachAtoms'),
99
- atoms: pick(ioc.getByType('atom'), atomsToAttach),
100
- lifecycleEvents: headlessConfig?.attachAtomsLifecycleEvents,
104
+ atoms: ioc.getByType('atom'),
105
+ modules: ioc.getByType('module'),
101
106
  })
102
107
 
103
- attachPlugins({ application, plugins: ioc.getByType('plugin') })
104
-
105
- application.start()
108
+ attachPlugins({
109
+ application,
110
+ plugins: ioc.getByType('plugin'),
111
+ logger: ioc.get('createLogger')('attachPlugins'),
112
+ })
106
113
 
107
- return createApi({ ioc, port })
114
+ return createApi({ ioc, port, lockedAtom })
108
115
  }
109
116
 
110
117
  return { ...ioc, resolve }
package/src/ioc.js CHANGED
@@ -1,30 +1,72 @@
1
1
  import createIocContainer from '@exodus/dependency-injection'
2
2
  import preprocess from '@exodus/dependency-preprocessors'
3
3
  import alias from '@exodus/dependency-preprocessors/src/preprocessors/alias'
4
+ import configPreprocessor from '@exodus/dependency-preprocessors/src/preprocessors/config'
5
+ import devModeAtoms from '@exodus/dependency-preprocessors/src/preprocessors/dev-mode-atoms'
4
6
  import logify from '@exodus/dependency-preprocessors/src/preprocessors/logify'
5
- import namespaceConfig from '@exodus/dependency-preprocessors/src/preprocessors/namespace-config'
6
7
  import namespaceStorage from '@exodus/dependency-preprocessors/src/preprocessors/namespace-storage'
8
+ import optional from '@exodus/dependency-preprocessors/src/preprocessors/optional'
9
+ import performanceMonitor from '@exodus/dependency-preprocessors/src/preprocessors/performance-monitor'
10
+ import readOnlyAtoms from '@exodus/dependency-preprocessors/src/preprocessors/read-only-atoms'
11
+ import assert from 'minimalistic-assert'
7
12
 
8
13
  import createDependencies from './dependencies'
9
14
 
10
15
  const createIOC = ({ adapters, config }) => {
11
- const { createLogger } = adapters
16
+ const { createLogger, performance = {} } = adapters
17
+ const {
18
+ readOnlyAtoms: readOnlyAtomsConfig,
19
+ devModeAtoms: devModeAtomsConfig,
20
+ performanceMonitor: performanceMonitorConfig,
21
+ } = config.ioc ?? {}
22
+
23
+ const ioc = createIocContainer({ logger: createLogger('exodus:ioc') })
24
+
25
+ const performanceLogger = createLogger('exodus:performance')
12
26
 
13
- const logger = createLogger('exodus:ioc')
14
- const dependencies = createDependencies({ adapters, config })
15
27
  const preprocessors = [
16
28
  logify({ createLogger }),
17
- namespaceConfig(),
29
+ performanceMonitorConfig?.enabled &&
30
+ performanceMonitor({
31
+ now: performance.now,
32
+ onAboveThreshold:
33
+ performance.onAboveThreshold ??
34
+ (({ id, method, duration }) =>
35
+ performanceLogger.log(`${id}.${method} took ${duration}ms`)),
36
+ config: performanceMonitorConfig,
37
+ }),
38
+ configPreprocessor(),
18
39
  alias(),
19
40
  // NOTE: order matters, this should come after `alias`
20
41
  namespaceStorage(),
21
- ]
22
- const definitions = preprocess({ dependencies, preprocessors })
23
- const ioc = createIocContainer({ logger })
42
+ readOnlyAtoms({
43
+ logger: createLogger('exodus:read-only-atoms'),
44
+ warn: true,
45
+ ...readOnlyAtomsConfig,
46
+ }),
47
+ optional(),
48
+ devModeAtomsConfig && devModeAtoms(devModeAtomsConfig),
49
+ ].filter(Boolean)
50
+
51
+ const registerMultiple = (dependencies) => {
52
+ ioc.registerMultiple(preprocess({ dependencies, preprocessors }))
53
+ }
54
+
55
+ const register = (dependency) => {
56
+ registerMultiple([dependency])
57
+ }
58
+
59
+ const use = (module) => {
60
+ for (const { definition } of module.definitions) {
61
+ assert(definition.type, `ioc.use: "${definition.id}" is missing type field`)
62
+ }
63
+
64
+ registerMultiple(module.definitions)
65
+ }
24
66
 
25
- ioc.registerMultiple(definitions)
67
+ registerMultiple(createDependencies({ adapters, config }))
26
68
 
27
- return ioc
69
+ return { ...ioc, register, registerMultiple, use }
28
70
  }
29
71
 
30
72
  export default createIOC
@@ -0,0 +1,60 @@
1
+ import { deriveSyncKeys } from '../utils/fusion'
2
+
3
+ const attachMigrations = ({ migrations = [], application, modules, adapters, ...deps }) => {
4
+ const { analytics, unlockEncryptedStorage, wallet } = modules
5
+ const { unsafeStorage, migrateableStorage, fusionKeysDeferred, migrateableFusion } = adapters
6
+
7
+ // Override encrypted storage with migrations own instance to make sure no modules reads from it before migrations ran
8
+ const migrationFlagsStorage = unsafeStorage.namespace('migrations')
9
+ const migrationAdapters = { ...adapters, storage: migrateableStorage, fusion: migrateableFusion }
10
+
11
+ const attachMigration = async (migration) => {
12
+ const { name, factory } = migration
13
+ const logger = adapters.createLogger(`exodus:migration:${name}`)
14
+
15
+ logger.log('running migration')
16
+
17
+ let success = false
18
+
19
+ try {
20
+ const start = performance.now()
21
+
22
+ await factory({ ...deps, adapters: migrationAdapters, modules, logger })
23
+
24
+ const time = performance.now() - start
25
+
26
+ logger.log(`migration successful in ${time.toFixed(2)}ms`)
27
+
28
+ await migrationFlagsStorage.set(name, true)
29
+
30
+ success = true
31
+ } catch (error) {
32
+ logger.log(`migration failed: ${error.stack}`)
33
+ } finally {
34
+ analytics.track({
35
+ event: 'ClientMigrationRun',
36
+ properties: { migrationId: name, success },
37
+ force: true,
38
+ })
39
+ }
40
+ }
41
+
42
+ application.hook('migrate', async () => {
43
+ await unlockEncryptedStorage(migrateableStorage)
44
+ if (fusionKeysDeferred) await deriveSyncKeys(wallet.seed).then(fusionKeysDeferred.resolve)
45
+
46
+ const migrationNames = migrations.map((migration) => migration.name)
47
+ const migrationFlags = await migrationFlagsStorage.batchGet(migrationNames)
48
+ const migrationsDiff = migrations.filter((v, k) => !migrationFlags[k])
49
+
50
+ for (const migration of migrationsDiff) {
51
+ await attachMigration(migration)
52
+ }
53
+ })
54
+
55
+ application.hook('clear', async () => {
56
+ await migrationFlagsStorage.clear()
57
+ })
58
+ }
59
+
60
+ export default attachMigrations
@@ -1,17 +1,38 @@
1
- import { kebabCase, memoize } from 'lodash'
1
+ import { LifecycleHook } from '../constants'
2
2
 
3
- // e.g. onUnlock -> unlock -> onUnlock, onChangePassphrase -> change-passphrase
4
- const getApplicationHookName = memoize((lifecycleMethod) =>
5
- kebabCase(lifecycleMethod.replace(/^on/, ''))
3
+ const LIFECYCLE_METHOD_TO_HOOK_NAME = Object.fromEntries(
4
+ Object.entries(LifecycleHook).map(([pascalCaseName, hookName]) => [
5
+ `on${pascalCaseName}`,
6
+ hookName,
7
+ ])
6
8
  )
7
9
 
8
- const attachPlugins = ({ plugins, application }) => {
10
+ const attachPlugins = ({ plugins, application, logger }) => {
11
+ const timeFn = (fn, name) => {
12
+ const pluginWrapper = async (...args) => {
13
+ const start = Date.now()
14
+ try {
15
+ return await fn(...args)
16
+ } finally {
17
+ logger.debug(name, `${Date.now() - start}ms`)
18
+ }
19
+ }
20
+
21
+ Object.defineProperty(pluginWrapper, 'name', { value: name, writable: false })
22
+
23
+ return pluginWrapper
24
+ }
25
+
9
26
  Object.entries(plugins).forEach(([name, lifecycleMethods]) => {
10
27
  const entries = Object.entries(lifecycleMethods || {})
11
28
 
12
29
  for (const [lifecycleMethod, fn] of entries) {
13
- const hookName = getApplicationHookName(lifecycleMethod)
14
- application.hook(hookName, fn)
30
+ const hookName = LIFECYCLE_METHOD_TO_HOOK_NAME[lifecycleMethod]
31
+ if (hookName) {
32
+ application.hook(hookName, timeFn(fn, `plugin ${name}.${lifecycleMethod}`))
33
+ } else {
34
+ logger.error(`plugin "${name}" declares unsupported lifecycle method "${lifecycleMethod}"`)
35
+ }
15
36
  }
16
37
  })
17
38
  }
@@ -1,3 +1,5 @@
1
+ import autoEnableAssetsPlugin from '@exodus/auto-enable-assets-plugin'
2
+
1
3
  import logLifecyclePlugin from './log-lifecycle'
2
4
 
3
- export default [logLifecyclePlugin]
5
+ export default [logLifecyclePlugin, autoEnableAssetsPlugin]
@@ -9,6 +9,7 @@ const logLifecycle = {
9
9
  onImport: () => logger.debug('onImport'),
10
10
  onMigrate: () => logger.debug('onMigrate'),
11
11
  onStart: () => logger.debug('onStart'),
12
+ onRestart: () => logger.debug('onRestart'),
12
13
  onLoad: () => logger.debug('onLoad'),
13
14
  onUnload: () => logger.debug('onUnload'),
14
15
  onCreate: () => logger.debug('onCreate'),
@@ -0,0 +1,27 @@
1
+ import { zipObject } from 'lodash'
2
+
3
+ const createReporting = ({ ioc, lockedAtom }) => {
4
+ const getReports = async () => {
5
+ if (await lockedAtom.get()) throw new Error('Unable to export when locked')
6
+
7
+ const nodes = ioc.getByType('report')
8
+ const reports = Object.values(nodes)
9
+
10
+ const resolvedReports = await Promise.allSettled(reports.map((report) => report.export()))
11
+
12
+ const namespaces = reports.map((report) => report.namespace)
13
+ const data = resolvedReports.map((outcome) =>
14
+ outcome.status === 'fulfilled' ? outcome.value : { error: outcome.reason }
15
+ )
16
+
17
+ return zipObject(namespaces, data)
18
+ }
19
+
20
+ return {
21
+ reporting: {
22
+ export: getReports,
23
+ },
24
+ }
25
+ }
26
+
27
+ export default createReporting
@@ -12,8 +12,10 @@ const createUnlockEncryptedStorage = ({ keychain }) => {
12
12
  }
13
13
  }
14
14
 
15
+ // eslint-disable-next-line @exodus/export-default/named
15
16
  export default {
16
17
  id: 'unlockEncryptedStorage',
18
+ type: 'module',
17
19
  factory: createUnlockEncryptedStorage,
18
20
  dependencies: ['keychain'],
19
21
  }
@@ -0,0 +1,17 @@
1
+ import { pick } from '@exodus/basic-utils'
2
+ import HDKeySlip10 from '@exodus/hd-key-slip-10'
3
+ import sodium from '@exodus/sodium-crypto'
4
+
5
+ const EXODUS_PURPOSE = Number.parseInt(Buffer.from('exo').toString('hex'), '16')
6
+
7
+ const EXO_2_PATH = `m/${EXODUS_PURPOSE}'/2'`
8
+
9
+ const BIP43_PURPOSE_SYNC = `${EXO_2_PATH}/0'`
10
+
11
+ export const deriveSyncKeys = async (seed) => {
12
+ const derived = HDKeySlip10.fromSeed(seed).derive(BIP43_PURPOSE_SYNC).key
13
+
14
+ const keys = await sodium.getSodiumKeysFromSeed(derived)
15
+
16
+ return pick(keys, ['box', 'sign', 'secret', 'derived'])
17
+ }
@@ -1,40 +0,0 @@
1
- const emitAtomValue = async (opts) => {
2
- const { port, atomId, atom } = opts
3
- const value = 'value' in opts ? opts.value : await atom.get()
4
- port.emit(atomId, value)
5
- }
6
-
7
- export const emitFromAtoms = ({ atoms, port }) =>
8
- Object.entries(atoms).forEach(async ([atomId, atom]) => emitAtomValue({ port, atomId, atom }))
9
-
10
- const attachAtom = ({ port, application, logger, atom, atomId, lifecycleEvents }) => {
11
- let loaded = false
12
-
13
- lifecycleEvents.forEach((event) =>
14
- application.on(event, async () => {
15
- loaded = true
16
- await emitAtomValue({ port, atomId, atom })
17
- })
18
- )
19
-
20
- application.on('clear', async () => {
21
- try {
22
- await atom?.set(undefined)
23
- } catch (error) {
24
- logger.debug('failed to clear atom', error)
25
- // noop. atom might not support set
26
- }
27
- })
28
-
29
- atom.observe((value) => {
30
- if (loaded) emitAtomValue({ port, atomId, atom, value })
31
- })
32
- }
33
-
34
- const attachAtoms = ({ port, application, logger, atoms, lifecycleEvents = ['start'] }) => {
35
- for (const [atomId, atom] of Object.entries(atoms)) {
36
- attachAtom({ port, application, logger, atom, atomId, lifecycleEvents })
37
- }
38
- }
39
-
40
- export default attachAtoms
@@ -1,31 +0,0 @@
1
- import marketHistoryMonitorDefinition from '@exodus/market-history/module'
2
-
3
- import { withType } from './utils'
4
-
5
- const createModuleDependencies = () =>
6
- [
7
- {
8
- definition: marketHistoryMonitorDefinition,
9
- storage: { namespace: 'marketHistory' },
10
- aliases: [
11
- {
12
- implementationId: 'unsafeStorage',
13
- interfaceId: 'storage',
14
- },
15
- {
16
- implementationId: 'marketHistoryClearCacheAtom',
17
- interfaceId: 'clearCacheAtom',
18
- },
19
- {
20
- implementationId: 'remoteConfigClearMarketHistoryCacheAtom',
21
- interfaceId: 'remoteConfigClearCacheAtom',
22
- },
23
- {
24
- implementationId: 'marketHistoryRefreshIntervalAtom',
25
- interfaceId: 'remoteConfigRefreshIntervalAtom',
26
- },
27
- ],
28
- },
29
- ].map(withType('monitor'))
30
-
31
- export default createModuleDependencies
@@ -1,48 +0,0 @@
1
- import { mapValues } from '@exodus/basic-utils'
2
-
3
- const createAccountStatesTransformer = ({ serializePortPayloads, blockchainMetadata }) => {
4
- return serializePortPayloads
5
- ? (payload) =>
6
- mapValues(payload, (byAsset, walletAccount) =>
7
- mapValues(
8
- byAsset,
9
- (accountState, assetName) =>
10
- blockchainMetadata.serializePayload({ walletAccount, assetName, accountState })
11
- .accountState
12
- )
13
- )
14
- : (payload) => payload
15
- }
16
-
17
- export function createAccountStatesUpdateHandler({
18
- port,
19
- blockchainMetadata,
20
- config: { serializePortPayloads = false },
21
- }) {
22
- const transform = createAccountStatesTransformer({ serializePortPayloads, blockchainMetadata })
23
-
24
- return (payload) => {
25
- port.emit('account-states-update', transform(payload))
26
- }
27
- }
28
-
29
- export function createLoadWalletAccountsHandler({
30
- port,
31
- blockchainMetadata,
32
- config: { serializePortPayloads = false },
33
- }) {
34
- const transformAccountStates = createAccountStatesTransformer({
35
- serializePortPayloads,
36
- blockchainMetadata,
37
- })
38
-
39
- return async () => {
40
- const [txLogs, accountStates] = await Promise.all([
41
- blockchainMetadata.getLoadedTxLogs(),
42
- blockchainMetadata.getLoadedAccountStates(),
43
- ])
44
-
45
- port.emit('tx-logs', txLogs)
46
- port.emit('account-states', transformAccountStates(accountStates))
47
- }
48
- }