@exodus/fiat-balances 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +184 -0
  2. package/package.json +38 -0
package/index.js ADDED
@@ -0,0 +1,184 @@
1
+ import { conversionByRate } from '@exodus/currency'
2
+ import currencyFiat from '@exodus/fiat-currencies'
3
+ import ExodusModule from '@exodus/module'
4
+ import { difference, set } from 'lodash'
5
+
6
+ class FiatBalances extends ExodusModule {
7
+ #assetsModule
8
+ #balanceFields
9
+ #ratesMonitor
10
+ #fiatCurrency
11
+ #cachedRates
12
+ #enabledAssetsData
13
+ #latestAssetBalances = null
14
+ #initialized = false
15
+ #balances = {
16
+ // totals: Object,
17
+ // byWalletAccount: Object,
18
+ // byAssetSource: Object,
19
+ // byBaseAssetSource: Object,
20
+ }
21
+
22
+ constructor({ assetsModule, logger, balances, balanceFields, ratesMonitor, enabledAssets }) {
23
+ super({ name: 'FiatBalances', logger })
24
+
25
+ this.#assetsModule = assetsModule
26
+ this.#balanceFields = balanceFields
27
+
28
+ balances.on('balances', this.#setBalances)
29
+ ratesMonitor.on('rates', ({ rates, currency }) => {
30
+ this._logger.log('recomputing based on new rates and/or fiat currency')
31
+ this.#fiatCurrency = currencyFiat[currency]
32
+ this.#cachedRates = rates
33
+ this.#maybeRecompute()
34
+ })
35
+ enabledAssets.on('enabled-assets', (data) => {
36
+ this.#enabledAssetsData = data
37
+ this.#maybeRecompute()
38
+ })
39
+ }
40
+
41
+ #isReady = () => {
42
+ return Boolean(this.#cachedRates && this.#fiatCurrency && this.#latestAssetBalances)
43
+ }
44
+
45
+ // seems cheap, worth memoizing?
46
+ #getCreateConversion = ({ assetName }) => {
47
+ const fiatCurrency = this.#fiatCurrency
48
+ const asset = this.#assetsModule.getAsset(assetName)
49
+ let fiatRate
50
+ // HACK: Super hacky, terrible, the rates state object should have the prices split up by sub-objects per fiat
51
+ if (fiatCurrency.defaultUnit.unitName === 'USD') {
52
+ fiatRate = this.#cachedRates?.[asset.ticker]?.priceUSD || 0
53
+ } else {
54
+ fiatRate = this.#cachedRates?.[asset.ticker]?.price || 0
55
+ }
56
+
57
+ return conversionByRate(asset.currency, fiatCurrency, fiatRate)
58
+ }
59
+
60
+ #convertToFiat = ({ assetName, value }) => {
61
+ return this.#getCreateConversion({ assetName })(value)
62
+ }
63
+
64
+ #maybeRecompute = () => {
65
+ if (this.#isReady()) this.recompute()
66
+ }
67
+
68
+ recompute = async () => {
69
+ this.#reset()
70
+
71
+ const balances = this.#latestAssetBalances
72
+ const { byAssetSource, byBaseAssetSource, byWalletAccount } = this.#balances
73
+ const { enabledAssets = {} } = this.#enabledAssetsData || {}
74
+ Object.keys(balances).forEach((walletAccount) => {
75
+ const walletAccountBalances = balances[walletAccount]
76
+ this.#balanceFields.forEach((field) => {
77
+ let fieldTotal = this.#fiatCurrency.ZERO
78
+ const entries = Object.entries(walletAccountBalances).filter(
79
+ ([assetName, balances]) => enabledAssets[assetName] && balances
80
+ )
81
+
82
+ entries.forEach(([assetName, assetBalances]) => {
83
+ const balance = assetBalances?.[field]
84
+ if (!balance) return
85
+
86
+ if (!byAssetSource?.[walletAccount]?.[assetName]?.[field]) {
87
+ set(byAssetSource, [walletAccount, assetName, field], this.#fiatCurrency.ZERO)
88
+ }
89
+
90
+ const baseAssetName = this.#assetsModule.getAsset(assetName).baseAsset.name
91
+ if (!byBaseAssetSource?.[walletAccount]?.[baseAssetName]?.[field]) {
92
+ set(byBaseAssetSource, [walletAccount, baseAssetName, field], this.#fiatCurrency.ZERO)
93
+ }
94
+
95
+ const fiatValue = this.#convertToFiat({ assetName, value: balance })
96
+ // eslint-disable-next-line standard/computed-property-even-spacing
97
+ byAssetSource[walletAccount][assetName][field] =
98
+ byAssetSource[walletAccount][assetName][field].add(fiatValue)
99
+
100
+ // eslint-disable-next-line standard/computed-property-even-spacing
101
+ byBaseAssetSource[walletAccount][baseAssetName][field] =
102
+ byBaseAssetSource[walletAccount][baseAssetName][field].add(fiatValue)
103
+
104
+ fieldTotal = fieldTotal.add(fiatValue)
105
+ })
106
+
107
+ set(byWalletAccount, [walletAccount, field], fieldTotal)
108
+ })
109
+ })
110
+
111
+ this.#recomputeWalletTotals()
112
+ }
113
+
114
+ #setBalances = ({ balances, oldBalances, changes }) => {
115
+ const needsRecompute = !changes || this.#latestAssetBalances !== oldBalances
116
+ this.#latestAssetBalances = balances
117
+ if (!this.#isReady()) return
118
+
119
+ if (needsRecompute) return this.recompute()
120
+
121
+ this._logger.log('recomputing based on new balances')
122
+ const walletAccountsRemoved = difference(
123
+ Object.keys(balances),
124
+ Object.keys(oldBalances || balances)
125
+ )
126
+
127
+ walletAccountsRemoved.forEach((walletAccount) => {
128
+ delete this.#balances.byWalletAccount[walletAccount]
129
+ })
130
+
131
+ Object.entries(changes).forEach(([walletAccount, walletAccountBalancesChanges]) => {
132
+ const walletAccountBalances = this.#balances.byWalletAccount[walletAccount]
133
+ Object.entries(walletAccountBalancesChanges).forEach(
134
+ ([assetName, assetSourceBalancesChanges]) => {
135
+ this.#balanceFields.forEach((field) => {
136
+ const { from, to } = assetSourceBalancesChanges[field]
137
+ walletAccountBalances[field] = walletAccountBalances[field] || this.#fiatCurrency.ZERO
138
+ walletAccountBalances[field] = walletAccountBalances[field]
139
+ .sub(this.#convertToFiat({ assetName, value: from }))
140
+ .add(this.#convertToFiat({ assetName, value: to }))
141
+ })
142
+ }
143
+ )
144
+ })
145
+
146
+ this.#recomputeWalletTotals()
147
+ }
148
+
149
+ #recomputeWalletTotals = () => {
150
+ this.#balanceFields.forEach((field) => {
151
+ this.#balances.totals[field] = Object.entries(this.#balances.byWalletAccount).reduce(
152
+ (total, [walletAccount, walletAccountBalances]) =>
153
+ walletAccountBalances[field] ? total.add(walletAccountBalances[field]) : total,
154
+ this.#fiatCurrency.ZERO
155
+ )
156
+ })
157
+
158
+ this.#initialized = true
159
+ this.sync()
160
+ }
161
+
162
+ #reset = () => {
163
+ this.#initialized = false
164
+
165
+ const byWalletAccount = {}
166
+ const byAssetSource = {}
167
+ const byBaseAssetSource = {}
168
+ this.#balances = {
169
+ totals: {},
170
+ byWalletAccount,
171
+ byAssetSource,
172
+ byBaseAssetSource,
173
+ }
174
+ }
175
+
176
+ sync = () => {
177
+ this._logger.log('fiat balances updated')
178
+ this.emit('fiat-balances', { balances: this.#balances })
179
+ }
180
+ }
181
+
182
+ const createFiatBalances = (...args) => new FiatBalances(...args)
183
+
184
+ export default createFiatBalances
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@exodus/fiat-balances",
3
+ "version": "1.0.0",
4
+ "description": "module to track fiat balances based on changes in crypto balances and fiat currency",
5
+ "author": "Exodus Movement Inc",
6
+ "license": "UNLICENSED",
7
+ "scripts": {
8
+ "test": "jest",
9
+ "lint": "eslint .",
10
+ "lint:fix": "yarn lint --fix"
11
+ },
12
+ "files": [
13
+ "index.js"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/ExodusMovement/exodus-hydra.git"
18
+ },
19
+ "homepage": "https://github.com/ExodusMovement/exodus-hydra/tree/master/modules/fiat-balances",
20
+ "bugs": {
21
+ "url": "https://github.com/ExodusMovement/exodus-hydra/issues?q=is%3Aissue+is%3Aopen+label%3Afiat-balances"
22
+ },
23
+ "dependencies": {
24
+ "@exodus/currency": "^2.1.2",
25
+ "@exodus/fiat-currencies": "^1.0.0",
26
+ "@exodus/module": "^1.0.0",
27
+ "lodash": "^4.17.21"
28
+ },
29
+ "devDependencies": {
30
+ "@exodus/atoms": "^1.0.0",
31
+ "@exodus/balances": "^1.0.1",
32
+ "@exodus/basic-utils": "^0.7.0",
33
+ "@exodus/blockchain-metadata": "^2.2.0",
34
+ "@exodus/enabled-assets": "^1.0.0",
35
+ "@exodus/models": "^8.9.0",
36
+ "@exodus/storage-memory": "^1.0.0"
37
+ }
38
+ }