/
ChainIndex.hs
52 lines (47 loc) · 1.65 KB
/
ChainIndex.hs
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
module Plutus.Streaming.ChainIndex (
utxoState,
utxoState',
UtxoState,
TxUtxoBalance
) where
import Plutus.ChainIndex (TxUtxoBalance)
import Plutus.ChainIndex.Compatibility qualified as CI
import Plutus.ChainIndex.TxUtxoBalance qualified as TxUtxoBalance
import Plutus.ChainIndex.UtxoState (UtxoIndex, UtxoState)
import Plutus.ChainIndex.UtxoState qualified as UtxoState
import Plutus.Streaming
import Streaming
import Streaming.Prelude qualified as S
utxoState ::
Monad m =>
Stream (Of SimpleChainSyncEvent) m r ->
Stream (Of (UtxoState TxUtxoBalance)) m r
utxoState =
S.map snd . utxoState'
utxoState' ::
Monad m =>
Stream (Of SimpleChainSyncEvent) m r ->
Stream (Of (SimpleChainSyncEvent, UtxoState TxUtxoBalance)) m r
utxoState' =
S.scanned step initial projection
where
step index (RollForward block _) =
case CI.fromCardanoBlock block of
Left err -> error ("FromCardanoError: " <> show err)
Right txs ->
let tip = CI.tipFromCardanoBlock block
balance = TxUtxoBalance.fromBlock tip txs
in case UtxoState.insert balance index of
Left err ->
error (show err)
Right (UtxoState.InsertUtxoSuccess newIndex _insertPosition) ->
newIndex
step index (RollBackward cardanoPoint _) =
let point = CI.fromCardanoPoint cardanoPoint
in case TxUtxoBalance.rollback point index of
Left err -> error (show err)
Right (UtxoState.RollbackResult _newTip rolledBackIndex) ->
rolledBackIndex
initial :: UtxoIndex TxUtxoBalance
initial = mempty
projection = UtxoState.utxoState