forked from envadiv/mainnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.go
93 lines (79 loc) · 1.89 KB
/
merge.go
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
package main
import (
"fmt"
"sort"
"time"
)
func MergeAccounts(accounts []Account) (map[string]Account, error) {
accMap := make(map[string]Account)
for _, acc := range accounts {
// if len(acc.Distributions) == 0 {
// return nil, fmt.Errorf("account must have atleast one distribution: %v", acc)
// }
addrStr := acc.Address.String()
existing, ok := accMap[addrStr]
var newAcc Account
if ok {
var err error
newAcc, err = mergeTwoAccounts(acc, existing)
if err != nil {
return nil, err
}
err = newAcc.Validate()
if err != nil {
return nil, fmt.Errorf("error merging two accounts: %w, %s", err, acc.Address.String())
}
} else {
newAcc = acc
}
accMap[addrStr] = newAcc
}
return accMap, nil
}
func mergeTwoAccounts(acc1, acc2 Account) (Account, error) {
if !acc1.Address.Equals(acc2.Address) {
return Account{}, fmt.Errorf("%s != %s", acc1.Address, acc2.Address)
}
fmt.Println("Merging two", acc1, acc2)
newTotal, err := acc1.TotalPassage.Add(acc2.TotalPassage)
if err != nil {
return Account{}, err
}
distMap := make(map[time.Time]Distribution)
for _, dist := range acc1.Distributions {
distMap[dist.Time] = dist
}
for _, dist := range acc2.Distributions {
t := dist.Time
amount := dist.Passage
existing, ok := distMap[t]
if ok {
amount, err = amount.Add(existing.Passage)
if err != nil {
return Account{}, err
}
}
distMap[t] = Distribution{
Time: t,
Passage: amount,
}
}
// sort times
var times []time.Time
for t := range distMap {
times = append(times, t)
}
sort.Slice(times, func(i, j int) bool {
return times[i].Before(times[j])
})
// put distributions in sorted order
var distributions []Distribution
for _, t := range times {
distributions = append(distributions, distMap[t])
}
return Account{
Address: acc1.Address,
TotalPassage: newTotal,
Distributions: distributions,
}, nil
}