@exodus/headless 2.0.0-alpha.109 → 2.0.0-alpha.11

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.
@@ -0,0 +1,31 @@
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
@@ -2,6 +2,10 @@ 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
+
5
9
  export const withType =
6
10
  (type) =>
7
11
  ({ definition, ...rest }) => ({
package/src/index.js CHANGED
@@ -1,128 +1,110 @@
1
- import addressProvider from '@exodus/address-provider'
2
- import availableAssets from '@exodus/available-assets'
3
- import balances from '@exodus/balances'
4
1
  import { pick } from '@exodus/basic-utils'
5
- import blockchainMetadata from '@exodus/blockchain-metadata'
6
- import enabledAssets from '@exodus/enabled-assets'
7
- import featureFlags from '@exodus/feature-flags'
8
- import fees from '@exodus/fee-monitors'
9
- import geolocation from '@exodus/geolocation'
10
- import keychain from '@exodus/keychain'
11
- import locale from '@exodus/locale'
12
- import pricing from '@exodus/pricing'
13
- import rates from '@exodus/rates-monitor'
14
- import remoteConfig from '@exodus/remote-config'
15
- import restoreProgressTracker from '@exodus/restore-progress-tracker'
16
- import wallet from '@exodus/wallet'
17
- import walletAccounts from '@exodus/wallet-accounts'
18
-
2
+ import createIOC from './ioc'
19
3
  import createApi from './api'
4
+ import {
5
+ createAccountStatesUpdateHandler,
6
+ createLoadWalletAccountsHandler,
7
+ } from './utils/blockchain-metadata'
8
+
9
+ import attachPlugins from './plugins/attach'
20
10
  import attachAtoms from './atoms/attach'
21
11
  import { atomsToAttach } from './constants'
22
- import createIOC from './ioc'
23
- import attachMigrations from './migrations/attach'
24
- import attachPlugins from './plugins/attach'
25
12
 
26
13
  const createExodus = ({ adapters, config, port }) => {
27
14
  const ioc = createIOC({ adapters, config })
28
-
29
- ioc.use(wallet())
30
- ioc.use(keychain(config.keychain))
31
- ioc.use(walletAccounts())
32
- ioc.use(blockchainMetadata())
33
- ioc.use(availableAssets())
34
- ioc.use(enabledAssets())
35
- ioc.use(balances())
36
- ioc.use(remoteConfig())
37
- ioc.use(geolocation())
38
- ioc.use(pricing())
39
- ioc.use(fees())
40
- ioc.use(rates())
41
- ioc.use(featureFlags())
42
- ioc.use(locale())
43
- ioc.use(addressProvider({ config: config.addressProvider }))
44
- ioc.use(restoreProgressTracker())
45
-
46
- ioc.register({ definition: { id: 'port', type: 'port', factory: () => port } })
15
+ const { headless: headlessConfig } = config
47
16
 
48
17
  const resolve = () => {
49
18
  ioc.resolve()
50
19
 
51
- const { assetsModule, storage, fusion } = ioc.getByType('adapter')
20
+ const { assetsModule, storage } = ioc.getByType('adapter')
52
21
 
53
- const { lockedAtom } = ioc.getByType('atom')
54
-
55
- const { application, wallet, unlockEncryptedStorage } = ioc.getByType('module')
56
-
57
- const { migrations } = ioc.getAll()
58
-
59
- application.on('start', (payload) => port.emit('start', payload))
22
+ const {
23
+ application,
24
+ blockchainMetadata,
25
+ enabledAssets,
26
+ remoteConfig,
27
+ unlockEncryptedStorage,
28
+ walletAccounts,
29
+ } = ioc.getByType('module')
60
30
 
61
- application.on('load', (args) => port.emit('load', args))
31
+ const { marketHistory } = ioc.getByType('monitor')
62
32
 
63
- application.on('create', async ({ hasPassphraseSet }) => {
64
- const isLocked = await wallet.isLocked()
33
+ const handleLoadWalletAccounts = createLoadWalletAccountsHandler({
34
+ blockchainMetadata,
35
+ port,
36
+ config,
37
+ })
65
38
 
66
- port.emit('create', {
67
- walletExists: true,
68
- hasPassphraseSet,
69
- isLocked,
70
- isBackedUp: false,
71
- isRestoring: false,
72
- })
39
+ const handleAccountStatesUpdate = createAccountStatesUpdateHandler({
40
+ blockchainMetadata,
41
+ port,
42
+ config,
73
43
  })
74
44
 
75
- application.on('unlock', () => port.emit('unlock'))
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)
76
48
 
77
- application.on('lock', () => port.emit('lock'))
49
+ remoteConfig.on('sync', ({ current }) => port.emit('remote-config', current))
78
50
 
79
- application.on('backup', () => port.emit('backup'))
51
+ // TODO: migrate to marketHistoryAtom. Will be easier once it's on headless
52
+ marketHistory.on('market-history', (payload) => port.emit('market-history', payload))
80
53
 
81
- application.on('restore', () => port.emit('restore'))
54
+ application.hook('start', () => {
55
+ remoteConfig.load()
82
56
 
83
- application.on('restore-completed', () => {
84
- port.emit('restore-completed')
57
+ port.emit('start')
85
58
  })
86
59
 
87
- application.on('change-passphrase', () => port.emit('passphrase-changed'))
88
-
89
- application.on('import', () => port.emit('import', { walletExists: true }))
90
-
91
60
  application.hook('unlock', async () => {
92
61
  if (typeof storage.unlock === 'function') unlockEncryptedStorage(storage)
93
62
 
63
+ remoteConfig.sync()
64
+ marketHistory.start()
65
+
94
66
  await assetsModule.load()
67
+ await walletAccounts.load()
68
+ await Promise.all([
69
+ //
70
+ blockchainMetadata.load(),
71
+ enabledAssets.load(),
72
+ ])
95
73
  })
96
74
 
97
- application.hook('clear', async () => {
98
- await Promise.all([assetsModule.clear(), fusion.clearStorage()])
75
+ application.on('unlock', () => {
76
+ port.emit('unlock')
99
77
  })
100
78
 
101
- application.on('clear', () => port.emit('clear'))
102
-
103
- application.on('restart', (payload) => port.emit('restart', payload))
79
+ 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')
89
+ })
104
90
 
105
- attachMigrations({
106
- migrations,
107
- adapters,
108
- application,
109
- atoms: ioc.getByType('atom'),
110
- modules: ioc.getByType('module'),
91
+ application.on('restart', (payload) => {
92
+ port.emit('restart', payload)
111
93
  })
112
94
 
113
95
  attachAtoms({
114
96
  port,
115
97
  application,
98
+ logger: ioc.get('createLogger')('attachAtoms'),
116
99
  atoms: pick(ioc.getByType('atom'), atomsToAttach),
100
+ lifecycleEvents: headlessConfig?.attachAtomsLifecycleEvents,
117
101
  })
118
102
 
119
- attachPlugins({
120
- application,
121
- plugins: ioc.getByType('plugin'),
122
- logger: ioc.get('createLogger')('attachPlugins'),
123
- })
103
+ attachPlugins({ application, plugins: ioc.getByType('plugin') })
104
+
105
+ application.start()
124
106
 
125
- return createApi({ ioc, port, lockedAtom })
107
+ return createApi({ ioc, port })
126
108
  }
127
109
 
128
110
  return { ...ioc, resolve }
package/src/ioc.js CHANGED
@@ -1,56 +1,30 @@
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 devModeAtoms from '@exodus/dependency-preprocessors/src/preprocessors/dev-mode-atoms'
5
4
  import logify from '@exodus/dependency-preprocessors/src/preprocessors/logify'
6
5
  import namespaceConfig from '@exodus/dependency-preprocessors/src/preprocessors/namespace-config'
7
6
  import namespaceStorage from '@exodus/dependency-preprocessors/src/preprocessors/namespace-storage'
8
- import optional from '@exodus/dependency-preprocessors/src/preprocessors/optional'
9
- import readOnlyAtoms from '@exodus/dependency-preprocessors/src/preprocessors/read-only-atoms'
10
- import assert from 'minimalistic-assert'
11
7
 
12
8
  import createDependencies from './dependencies'
13
9
 
14
10
  const createIOC = ({ adapters, config }) => {
15
11
  const { createLogger } = adapters
16
- const { readOnlyAtoms: readOnlyAtomsConfig, devModeAtoms: devModeAtomsConfig } = config.ioc ?? {}
17
-
18
- const ioc = createIocContainer({ logger: createLogger('exodus:ioc') })
19
12
 
13
+ const logger = createLogger('exodus:ioc')
14
+ const dependencies = createDependencies({ adapters, config })
20
15
  const preprocessors = [
21
16
  logify({ createLogger }),
22
17
  namespaceConfig(),
23
18
  alias(),
24
19
  // NOTE: order matters, this should come after `alias`
25
20
  namespaceStorage(),
26
- readOnlyAtoms({
27
- logger: createLogger('exodus:read-only-atoms'),
28
- warn: true,
29
- ...readOnlyAtomsConfig,
30
- }),
31
- optional(),
32
- ...(devModeAtomsConfig ? [devModeAtoms(devModeAtomsConfig)] : []),
33
21
  ]
22
+ const definitions = preprocess({ dependencies, preprocessors })
23
+ const ioc = createIocContainer({ logger })
34
24
 
35
- const registerMultiple = (dependencies) => {
36
- ioc.registerMultiple(preprocess({ dependencies, preprocessors }))
37
- }
38
-
39
- const register = (dependency) => {
40
- registerMultiple([dependency])
41
- }
42
-
43
- const use = (module) => {
44
- for (const { definition } of module.definitions) {
45
- assert(definition.type, `ioc.use: "${definition.id}" is missing type field`)
46
- }
47
-
48
- registerMultiple(module.definitions)
49
- }
50
-
51
- registerMultiple(createDependencies({ adapters, config }))
25
+ ioc.registerMultiple(definitions)
52
26
 
53
- return { ...ioc, register, registerMultiple, use }
27
+ return ioc
54
28
  }
55
29
 
56
30
  export default createIOC
@@ -1,38 +1,17 @@
1
- import { LifecycleHook } from '../constants'
1
+ import { kebabCase, memoize } from 'lodash'
2
2
 
3
- const LIFECYCLE_METHOD_TO_HOOK_NAME = Object.fromEntries(
4
- Object.entries(LifecycleHook).map(([pascalCaseName, hookName]) => [
5
- `on${pascalCaseName}`,
6
- hookName,
7
- ])
3
+ // e.g. onUnlock -> unlock -> onUnlock, onChangePassphrase -> change-passphrase
4
+ const getApplicationHookName = memoize((lifecycleMethod) =>
5
+ kebabCase(lifecycleMethod.replace(/^on/, ''))
8
6
  )
9
7
 
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
-
8
+ const attachPlugins = ({ plugins, application }) => {
26
9
  Object.entries(plugins).forEach(([name, lifecycleMethods]) => {
27
10
  const entries = Object.entries(lifecycleMethods || {})
28
11
 
29
12
  for (const [lifecycleMethod, fn] of entries) {
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
- }
13
+ const hookName = getApplicationHookName(lifecycleMethod)
14
+ application.hook(hookName, fn)
36
15
  }
37
16
  })
38
17
  }
@@ -1,5 +1,3 @@
1
- import autoEnableAssetsPlugin from '@exodus/auto-enable-assets-plugin'
2
-
3
1
  import logLifecyclePlugin from './log-lifecycle'
4
2
 
5
- export default [logLifecyclePlugin, autoEnableAssetsPlugin]
3
+ export default [logLifecyclePlugin]
@@ -9,7 +9,6 @@ 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'),
13
12
  onLoad: () => logger.debug('onLoad'),
14
13
  onUnload: () => logger.debug('onUnload'),
15
14
  onCreate: () => logger.debug('onCreate'),
@@ -12,10 +12,8 @@ const createUnlockEncryptedStorage = ({ keychain }) => {
12
12
  }
13
13
  }
14
14
 
15
- // eslint-disable-next-line @exodus/export-default/named
16
15
  export default {
17
16
  id: 'unlockEncryptedStorage',
18
- type: 'module',
19
17
  factory: createUnlockEncryptedStorage,
20
18
  dependencies: ['keychain'],
21
19
  }
@@ -0,0 +1,48 @@
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
+ }
@@ -1,38 +0,0 @@
1
- import { combine, compute } from '@exodus/atoms'
2
- import { uniq } from 'lodash'
3
-
4
- const getNetworks = (assetNames, assets) =>
5
- uniq(
6
- assetNames
7
- .map((assetName) => assets[assetName]?.baseAsset.name)
8
- .filter((assetName) => !!assetName && !assets[assetName].isCombined)
9
- )
10
-
11
- const createBaseAssetNamesToMonitorAtom = ({
12
- assetsModule,
13
- enabledAssetsAtom,
14
- restoreAtom,
15
- availableAssetNamesAtom,
16
- }) => {
17
- const selector = ({ isRestore, enabledAssets, availableAssetNames }) => {
18
- const assetNames = isRestore ? availableAssetNames : Object.keys(enabledAssets)
19
- return getNetworks(assetNames, assetsModule.getAssets())
20
- }
21
-
22
- return compute({
23
- atom: combine({
24
- isRestore: restoreAtom,
25
- enabledAssets: enabledAssetsAtom,
26
- availableAssetNames: availableAssetNamesAtom,
27
- }),
28
- selector,
29
- })
30
- }
31
-
32
- // eslint-disable-next-line @exodus/export-default/named
33
- export default {
34
- id: 'baseAssetNamesToMonitorAtom',
35
- type: 'atom',
36
- factory: createBaseAssetNamesToMonitorAtom,
37
- dependencies: ['assetsModule', 'availableAssetNamesAtom', 'enabledAssetsAtom', 'restoreAtom'],
38
- }
@@ -1,60 +0,0 @@
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
package/src/reporting.js DELETED
@@ -1,27 +0,0 @@
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
@@ -1,17 +0,0 @@
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
- }