-
Notifications
You must be signed in to change notification settings - Fork 504
/
sagas.js
executable file
·329 lines (311 loc) · 10.9 KB
/
sagas.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import * as A from './actions'
import * as AT from './actionTypes'
import * as Exchange from '../../../exchange'
import * as kvStoreSelectors from '../../kvStore/eth/selectors'
import * as S from './selectors'
import * as selectors from '../../selectors'
import * as transactions from '../../../transactions'
import { call, put, select, take } from 'redux-saga/effects'
import {
concat,
dissoc,
filter,
head,
isNil,
join,
length,
map,
mapObjIndexed,
path,
prop,
sum,
takeLast,
toUpper,
values
} from 'ramda'
import { getLockboxEthContext } from '../../kvStore/lockbox/selectors'
import moment from 'moment'
const { calculateEthTxFee, transformTx, transformErc20Tx } = transactions.eth
const TX_PER_PAGE = 40
const CONTEXT_FAILURE = 'Could not get ETH context.'
export default ({ api }) => {
//
// ETH
//
const fetchData = function * () {
try {
yield put(A.fetchDataLoading())
const context = yield select(S.getContext)
const data = yield call(api.getEthData, context)
const latestBlock = yield call(api.getEthLatestBlock)
// account treatments
const finalBalance = sum(values(data).map(obj => obj.balance))
const totalReceived = sum(values(data).map(obj => obj.totalReceived))
const totalSent = sum(values(data).map(obj => obj.totalSent))
const nTx = sum(values(data).map(obj => obj.txn_count))
const addresses = mapObjIndexed(num => dissoc('txns', num), data)
const ethData = {
addresses,
info: {
eth: {
n_tx: nTx,
total_received: totalReceived,
total_sent: totalSent,
final_balance: finalBalance
}
},
latest_block: latestBlock
}
yield put(A.fetchDataSuccess(ethData))
yield call(checkForLowEthBalance)
} catch (e) {
yield put(A.fetchDataFailure(e.message))
}
}
const fetchLatestBlock = function * () {
try {
yield put(A.fetchLatestBlockLoading())
const data = yield call(api.getEthLatestBlock)
yield put(A.fetchLatestBlockSuccess(data))
} catch (e) {
yield put(A.fetchLatestBlockFailure(e.message))
}
}
const fetchRates = function * () {
try {
yield put(A.fetchRatesLoading())
const data = yield call(api.getEthTicker)
yield put(A.fetchRatesSuccess(data))
} catch (e) {
yield put(A.fetchRatesFailure(e.message))
}
}
const watchTransactions = function * () {
while (true) {
const action = yield take(AT.FETCH_ETH_TRANSACTIONS)
yield call(fetchTransactions, action)
}
}
const fetchTransactions = function * (action) {
try {
const { payload } = action
const { address, reset } = payload
const defaultAccountR = yield select(selectors.kvStore.eth.getContext)
const ethAddress = address || defaultAccountR.getOrFail(CONTEXT_FAILURE)
const pages = yield select(S.getTransactions)
const nextPage = reset ? 0 : length(pages)
const transactionsAtBound = yield select(S.getTransactionsAtBound)
if (transactionsAtBound && !reset) return
yield put(A.fetchTransactionsLoading(reset))
const data = yield call(api.getEthTransactions, ethAddress, nextPage)
const txs = path([ethAddress, 'txns'], data)
if (isNil(txs)) return
const atBounds = length(txs) < TX_PER_PAGE
yield put(A.transactionsAtBound(atBounds))
const page = yield call(__processTxs, txs)
yield put(A.fetchTransactionsSuccess(page, reset))
} catch (e) {
yield put(A.fetchTransactionsFailure(e.message))
}
}
const fetchTransactionHistory = function * (action) {
const { payload } = action
const { address, endDate, startDate } = payload
try {
yield put(A.fetchTransactionHistoryLoading())
const defaultAccountR = yield select(selectors.kvStore.eth.getContext)
const ethAddress = address || defaultAccountR.getOrFail(CONTEXT_FAILURE)
// TODO: loop and ensure all transactions are fetched
const data = yield call(api.getEthTransactions, ethAddress, 0)
const rawTxs = path([ethAddress, 'txns'], data)
const txs = yield call(__processReportTxs, rawTxs, startDate, endDate)
yield put(A.fetchTransactionHistorySuccess(txs))
} catch (e) {
yield put(A.fetchTransactionHistoryFailure(e.message))
}
}
const __processReportTxs = function * (rawTxList, startDate, endDate) {
const fullTxList = yield call(__processTxs, rawTxList)
// remove txs that are ERC20 or not within date range
let prunedTxs = filter(
tx => !tx.erc20 && moment.unix(tx.time).isBetween(startDate, endDate),
fullTxList
)
// build model for report
return map(
tx => ({
amount: Exchange.convertEtherToEther({
value: tx.amount,
fromUnit: 'WEI',
toUnit: 'ETH'
}).value,
date: moment.unix(tx.time).format('YYYY-MM-DD'),
description: tx.description,
hash: tx.hash,
time: join(
' ',
takeLast(
2,
moment
.unix(tx.time)
.toString()
.split(' ')
)
),
type: tx.type,
value_then: '?',
value_now: '?',
exchange_rate_then: '?'
}),
prunedTxs
)
}
const __processTxs = function * (txs) {
const accountsR = yield select(kvStoreSelectors.getAccounts)
const erc20ContractsR = yield select(kvStoreSelectors.getErc20ContractAddrs)
const addresses = accountsR.getOrElse([]).map(prop('addr'))
const erc20Contracts = erc20ContractsR.getOrElse([])
const lockboxContextR = yield select(getLockboxEthContext)
const lockboxContext = lockboxContextR.getOrElse([])
const state = yield select()
const ethAddresses = concat(addresses, lockboxContext)
return map(transformTx(ethAddresses, erc20Contracts, state), txs)
}
const fetchLegacyBalance = function * () {
try {
yield put(A.fetchLegacyBalanceLoading())
const addrR = yield select(kvStoreSelectors.getLegacyAccountAddress)
const addr = addrR.getOrElse('')
const balances = yield call(api.getEthBalances, addr)
const balance = path([addr, 'balance'], balances)
yield put(A.fetchLegacyBalanceSuccess(balance))
} catch (e) {
yield put(A.fetchLegacyBalanceFailure())
}
}
const checkForLowEthBalance = function * () {
// TODO: ERC20 check for any erc20 balance in future
const erc20Balance = (yield select(S.getErc20Balance, 'pax')).getOrElse(0)
const weiBalance = (yield select(S.getBalance)).getOrFail()
const ethRates = (yield select(S.getRates)).getOrFail()
const ethBalance = Exchange.convertEthToFiat({
value: weiBalance,
fromUnit: 'WEI',
toCurrency: 'USD',
rates: ethRates
}).value
// less than $1 eth and has PAX, set warning flag to true
const showWarning = parseInt(ethBalance) < 1 && erc20Balance > 0
yield put(A.checkLowEthBalanceSuccess(showWarning))
}
//
// ERC20
//
const fetchErc20Data = function * (action) {
const { token } = action.payload
try {
yield put(A.fetchErc20DataLoading(token))
yield put(A.fetchErc20Rates(token))
const ethAddrs = yield select(S.getContext)
const contractAddr = (yield select(
selectors.kvStore.eth.getErc20ContractAddr,
token
)).getOrFail()
const data = yield call(api.getErc20Data, head(ethAddrs), contractAddr)
// account treatments similar to eth info plus the token account_hash
const tokenData = {
account_hash: prop('accountHash', data),
n_tx: parseInt(prop('transferCount', data)),
total_received: parseInt(prop('totalReceived', data)),
total_sent: parseInt(prop('totalSent', data)),
final_balance: parseInt(prop('balance', data))
}
yield put(A.fetchErc20DataSuccess(token, tokenData))
} catch (e) {
yield put(A.fetchErc20DataFailure(token, prop('message', e)))
}
}
const fetchErc20Rates = function * (action) {
const { token } = action.payload
try {
yield put(A.fetchErc20RatesLoading(token))
const data = yield call(api.getErc20Ticker, toUpper(token))
yield put(A.fetchErc20RatesSuccess(token, data))
} catch (e) {
yield put(A.fetchErc20RatesFailure(token, e.message))
}
}
const watchErc20Transactions = function * () {
while (true) {
const action = yield take(AT.FETCH_ERC20_TOKEN_TRANSACTIONS)
yield call(fetchErc20Transactions, action)
}
}
const fetchErc20Transactions = function * (action) {
const { token, reset } = action.payload
try {
const defaultAccountR = yield select(selectors.kvStore.eth.getContext)
const ethAddress = defaultAccountR.getOrFail(CONTEXT_FAILURE)
const pages = yield select(S.getErc20Transactions, token)
const nextPage = reset ? 0 : length(pages)
const txsAtBound = yield select(S.getErc20TransactionsAtBound, token)
const contractAddress = (yield select(
selectors.kvStore.eth.getErc20ContractAddr,
token
)).getOrFail()
if (txsAtBound && !reset) return
yield put(A.fetchErc20TransactionsLoading(token, ethAddress, reset))
const data = yield call(
api.getErc20Transactions,
ethAddress,
contractAddress,
nextPage
)
const txs = prop('transfers', data)
if (isNil(txs)) return
const atBounds = length(txs) < TX_PER_PAGE
yield put(A.erc20TransactionsAtBound(token, atBounds))
const page = yield call(__processErc20Txs, txs, token)
yield put(A.fetchErc20TransactionsSuccess(token, page, reset))
} catch (e) {
yield put(A.fetchErc20TransactionsFailure(token, e.message))
}
}
const fetchErc20TransactionFee = function * (action) {
const { hash, token } = action.payload
try {
yield put(A.fetchErc20TxFeeLoading(hash, token))
const txData = yield call(api.getEthTransactionV2, hash)
const fee = calculateEthTxFee(txData)
yield put(A.fetchErc20TxFeeSuccess(fee, hash, token))
} catch (e) {
yield put(A.fetchErc20TxFeeFailure(hash, token, e.message))
}
}
const __processErc20Txs = function * (txs, token) {
const accountsR = yield select(kvStoreSelectors.getAccounts)
const addresses = accountsR.getOrElse([]).map(prop('addr'))
const lockboxContextR = yield select(getLockboxEthContext)
const lockboxContext = lockboxContextR.getOrElse([])
const state = yield select()
const ethAddresses = concat(addresses, lockboxContext)
return map(transformErc20Tx(ethAddresses, state, token), txs)
}
return {
checkForLowEthBalance,
fetchData,
fetchErc20Data,
fetchLegacyBalance,
fetchRates,
fetchErc20Rates,
fetchLatestBlock,
fetchTransactions,
fetchTransactionHistory,
fetchErc20Transactions,
fetchErc20TransactionFee,
watchTransactions,
watchErc20Transactions,
__processTxs,
__processErc20Txs
}
}