/
fund_dividend.go
235 lines (222 loc) · 7.69 KB
/
fund_dividend.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
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
package dex
import (
"fmt"
"math/big"
"github.com/vitelabs/go-vite/v2/common/types"
"github.com/vitelabs/go-vite/v2/interfaces"
ledger "github.com/vitelabs/go-vite/v2/interfaces/core"
cabi "github.com/vitelabs/go-vite/v2/vm/contracts/abi"
)
//Note: allow dividend from specify periodId, former periods will be divided at that period
func DoFeesDividend(db interfaces.VmDb, periodId uint64) (blocks []*ledger.AccountBlock, err error) {
var (
dexFeesByPeriodMap map[uint64]*DexFeesByPeriod
vxSumFunds *VxFunds
ok bool
)
//allow divide history fees that not divided yet
if dexFeesByPeriodMap = GetNotFinishDividendDexFeesByPeriodMap(db, periodId); len(dexFeesByPeriodMap) == 0 { // no fee to divide
return
}
if vxSumFunds, ok = GetVxSumFundsWithForkCheck(db); !ok {
return
}
foundVxSumFunds, vxSumAmtBytes, needUpdateVxSum, _ := MatchVxFundsByPeriod(vxSumFunds, periodId, false)
//fmt.Printf("foundVxSumFunds %v, vxSumAmtBytes %s, needUpdateVxSum %v with periodId %d\n", foundVxSumFunds, new(big.Int).SetBytes(vxSumAmtBytes).String(), needUpdateVxSum, periodId)
if !foundVxSumFunds { // not found vxSumFunds
return
}
if needUpdateVxSum {
SaveVxSumFundsWithForkCheck(db, vxSumFunds)
}
vxSumAmt := new(big.Int).SetBytes(vxSumAmtBytes)
if vxSumAmt.Sign() <= 0 {
return
}
// sum fees from multi period not divided
feeSumMap := make(map[types.TokenTypeId]*big.Int)
for pId, fee := range dexFeesByPeriodMap {
for _, feeAccount := range fee.FeesForDividend {
if tokenId, err := types.BytesToTokenTypeId(feeAccount.Token); err != nil {
return nil, err
} else {
toDividendAmt, _ := splitDividendPool(feeAccount)
if amt, ok := feeSumMap[tokenId]; !ok {
feeSumMap[tokenId] = toDividendAmt
} else {
feeSumMap[tokenId] = amt.Add(amt, toDividendAmt)
}
}
}
MarkDexFeesFinishDividend(db, fee, pId)
}
blocks = tryBurnVite(db, feeSumMap)
var (
userVxFundKeyPrefix, userVxFundsKey, userVxFundsBytes []byte
)
if IsEarthFork(db) {
userVxFundKeyPrefix = vxLockedFundsKeyPrefix
} else {
userVxFundKeyPrefix = vxFundKeyPrefix
}
iterator, err := db.NewStorageIterator(userVxFundKeyPrefix)
if err != nil {
panic(err)
}
defer iterator.Release()
feeSumWithTokens := MapToAmountWithTokens(feeSumMap)
feeSumLeavedMap := make(map[types.TokenTypeId]*big.Int)
dividedVxAmtMap := make(map[types.TokenTypeId]*big.Int)
for {
if len(feeSumMap) == 0 {
break
}
if !iterator.Next() {
if iterator.Error() != nil {
panic(iterator.Error())
}
break
}
userVxFundsKey = iterator.Key()
userVxFundsBytes = iterator.Value()
if len(userVxFundsBytes) == 0 {
continue
}
addressBytes := userVxFundsKey[len(userVxFundKeyPrefix):]
address := types.Address{}
if err = address.SetBytes(addressBytes); err != nil {
return
}
userVxFunds := &VxFunds{}
if err = userVxFunds.DeSerialize(userVxFundsBytes); err != nil {
return
}
var userFeeDividend = make(map[types.TokenTypeId]*big.Int)
foundVxFunds, userVxAmtBytes, needUpdateVxFunds, needDeleteVxFunds := MatchVxFundsByPeriod(userVxFunds, periodId, true)
if !foundVxFunds {
continue
}
if needDeleteVxFunds {
DeleteVxFundsWithForkCheck(db, address.Bytes())
} else if needUpdateVxFunds {
SaveVxFundsWithForkCheck(db, address.Bytes(), userVxFunds)
}
userVxAmount := new(big.Int).SetBytes(userVxAmtBytes)
//fmt.Printf("address %s, userVxAmount %s, needDeleteVxFunds %v\n", string(address.Bytes()), userVxAmount.String(), needDeleteVxFunds)
if !IsValidVxAmountForDividend(userVxAmount) { //skip vxAmount not valid for dividend
continue
}
var finished bool
for _, feeSumWtTk := range feeSumWithTokens {
if feeSumWtTk.Deleted {
continue
}
if _, ok = feeSumLeavedMap[feeSumWtTk.Token]; !ok {
feeSumLeavedMap[feeSumWtTk.Token] = new(big.Int).Set(feeSumWtTk.Amount)
dividedVxAmtMap[feeSumWtTk.Token] = big.NewInt(0)
}
//fmt.Printf("tokenId %s, address %s, vxSumAmt %s, userVxAmount %s, dividedVxAmt %s, toDivideFeeAmt %s, toDivideLeaveAmt %s\n", tokenId.String(), address.String(), vxSumAmt.String(), userVxAmount.String(), dividedVxAmtMap[tokenId], toDivideFeeAmt.String(), toDivideLeaveAmt.String())
userFeeDividend[feeSumWtTk.Token], finished = DivideByProportion(vxSumAmt, userVxAmount, dividedVxAmtMap[feeSumWtTk.Token], feeSumWtTk.Amount, feeSumLeavedMap[feeSumWtTk.Token])
if finished {
feeSumWtTk.Deleted = true
delete(feeSumMap, feeSumWtTk.Token)
}
AddFeeDividendEvent(db, address, feeSumWtTk.Token, userVxAmount, userFeeDividend[feeSumWtTk.Token])
}
if err = BatchUpdateFund(db, address, userFeeDividend); err != nil {
return
}
}
return
}
func DoOperatorFeesDividend(db interfaces.VmDb, periodId uint64) error {
iterator, err := db.NewStorageIterator(append(operatorFeesKeyPrefix, Uint64ToBytes(periodId)...))
if err != nil {
panic(err)
}
defer iterator.Release()
for {
var operatorFeesKey, operatorFeesBytes []byte
if !iterator.Next() {
if iterator.Error() != nil {
panic(iterator.Error())
}
break
}
operatorFeesKey = iterator.Key() //3+8+21
operatorFeesBytes = iterator.Value()
if len(operatorFeesBytes) == 0 {
continue
}
if len(operatorFeesKey) != 32 {
panic(fmt.Errorf("invalid opearator fees key type"))
}
DeleteOperatorFeesByKey(db, operatorFeesKey)
operatorFeesByPeriod := &OperatorFeesByPeriod{}
if err = operatorFeesByPeriod.DeSerialize(operatorFeesBytes); err != nil {
panic(err)
}
addr, err := types.BytesToAddress(operatorFeesKey[11:])
if err != nil {
panic(err)
}
userFund := make(map[types.TokenTypeId]*big.Int)
for _, feeAcc := range operatorFeesByPeriod.OperatorFees {
tokenId, err := types.BytesToTokenTypeId(feeAcc.Token)
if err != nil {
panic(err)
}
for _, mkFee := range feeAcc.MarketFees {
if fd, hasToken := userFund[tokenId]; hasToken {
userFund[tokenId] = new(big.Int).Add(fd, new(big.Int).SetBytes(mkFee.Amount))
} else {
userFund[tokenId] = new(big.Int).SetBytes(mkFee.Amount)
}
AddOperatorFeeDividendEvent(db, addr, mkFee)
}
}
BatchUpdateFund(db, addr, userFund)
}
return nil
}
func DivideByProportion(totalReferAmt, partReferAmt, dividedReferAmt, toDivideTotalAmt, toDivideLeaveAmt *big.Int) (proportionAmt *big.Int, finished bool) {
dividedReferAmt.Add(dividedReferAmt, partReferAmt)
proportion := new(big.Float).SetPrec(bigFloatPrec).Quo(new(big.Float).SetPrec(bigFloatPrec).SetInt(partReferAmt), new(big.Float).SetPrec(bigFloatPrec).SetInt(totalReferAmt))
proportionAmt = RoundAmount(new(big.Float).SetPrec(bigFloatPrec).Mul(new(big.Float).SetPrec(bigFloatPrec).SetInt(toDivideTotalAmt), proportion))
toDivideLeaveNewAmt := new(big.Int).Sub(toDivideLeaveAmt, proportionAmt)
if toDivideLeaveNewAmt.Sign() <= 0 || dividedReferAmt.Cmp(totalReferAmt) >= 0 {
proportionAmt.Set(toDivideLeaveAmt)
finished = true
toDivideLeaveAmt.SetInt64(0)
} else {
toDivideLeaveAmt.Set(toDivideLeaveNewAmt)
}
return proportionAmt, finished
}
func tryBurnVite(db interfaces.VmDb, feeSumMap map[types.TokenTypeId]*big.Int) []*ledger.AccountBlock {
if IsEarthFork(db) {
for token, amt := range feeSumMap {
if token == ledger.ViteTokenId {
if amt.Sign() == 0 {
return nil
}
delete(feeSumMap, token)
if burnData, err := cabi.ABIAsset.PackMethod(cabi.MethodNameBurn); err != nil {
panic(err)
} else {
burnBlock := &ledger.AccountBlock{
AccountAddress: types.AddressDexFund,
ToAddress: types.AddressAsset,
BlockType: ledger.BlockTypeSendCall,
TokenId: ledger.ViteTokenId,
Amount: amt,
Data: burnData,
}
AddBurnViteEvent(db, BurnForDexViteFee, amt)
return []*ledger.AccountBlock{burnBlock}
}
}
}
}
return nil
}