This repository has been archived by the owner on Oct 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Erc20TransactionSyncer.swift
68 lines (57 loc) · 2.18 KB
/
Erc20TransactionSyncer.swift
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
import RxSwift
import BigInt
import EthereumKit
class Erc20TransactionSyncer {
private let provider: ITransactionProvider
private let storage: Eip20Storage
init(provider: ITransactionProvider, storage: Eip20Storage) {
self.provider = provider
self.storage = storage
}
private func handle(transactions: [ProviderTokenTransaction]) {
guard !transactions.isEmpty else {
return
}
let events = transactions.map { tx in
Event(
hash: tx.hash,
blockNumber: tx.blockNumber,
contractAddress: tx.contractAddress,
from: tx.from,
to: tx.to,
value: tx.value,
tokenName: tx.tokenName,
tokenSymbol: tx.tokenSymbol,
tokenDecimal: tx.tokenDecimal
)
}
storage.save(events: events)
}
}
extension Erc20TransactionSyncer: ITransactionSyncer {
public func transactionsSingle() -> Single<([Transaction], Bool)> {
let lastBlockNumber = storage.lastEvent()?.blockNumber ?? 0
let initial = lastBlockNumber == 0
return provider.tokenTransactionsSingle(startBlock: lastBlockNumber + 1)
.do(onSuccess: { [weak self] transactions in
self?.handle(transactions: transactions)
})
.map { transactions in
let array = transactions.map { tx in
Transaction(
hash: tx.hash,
timestamp: tx.timestamp,
isFailed: false,
blockNumber: tx.blockNumber,
transactionIndex: tx.transactionIndex,
nonce: tx.nonce,
gasPrice: tx.gasPrice,
gasLimit: tx.gasLimit,
gasUsed: tx.gasUsed
)
}
return (array, initial)
}
.catchErrorJustReturn(([], initial))
}
}