-
Notifications
You must be signed in to change notification settings - Fork 6
/
distribution.go
301 lines (268 loc) · 11.3 KB
/
distribution.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
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
package keeper
import (
"github.com/armon/go-metrics"
"github.com/chain4energy/c4e-chain/x/cfedistributor/types"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func calculatePercentage(sharePercent sdk.Dec, coinsToDistributeDec sdk.DecCoins) sdk.DecCoins {
if !coinsToDistributeDec.IsAllPositive() {
return sdk.NewDecCoins()
}
return coinsToDistributeDec.MulDecTruncate(sharePercent)
}
func findBurnState(states *[]types.State) int {
for pos, state := range *states {
if state.Burn {
return pos
}
}
return -1
}
func findAccountState(states *[]types.State, account *types.Account) int {
for pos, state := range *states {
if state.Account != nil && state.Account.Id == account.Id {
return pos
}
}
return -1
}
func getRamainsSum(states *[]types.State) sdk.DecCoins {
sum := sdk.NewDecCoins()
for _, state := range *states {
sum = sum.Add(state.Remains...)
}
return sum
}
func (k Keeper) PrepareCoinsToDistribute(sources []*types.Account, ctx sdk.Context, states []types.State, subDistributorName string) sdk.DecCoins {
allCoinsToDistribute := sdk.NewDecCoins()
for _, source := range sources {
var coinsToDistribute sdk.DecCoins
if source.Type == types.Main {
coinsToDistribute = k.prepareCoinToDistributeForMainAccount(ctx, states, subDistributorName)
} else {
coinsToDistribute = k.prepareCoinToDistributeForNotMainAccount(ctx, *source, states, subDistributorName)
}
if len(coinsToDistribute) == 0 {
continue
}
allCoinsToDistribute = allCoinsToDistribute.Add(coinsToDistribute...)
}
return allCoinsToDistribute
}
func (k Keeper) prepareCoinToDistributeForMainAccount(ctx sdk.Context, states []types.State, subDistributorName string) sdk.DecCoins {
coinsToDistribute := sdk.NewDecCoinsFromCoins(k.GetAccountCoinsForModuleAccount(ctx, types.DistributorMainAccount)...)
if len(coinsToDistribute) > 0 {
sum := getRamainsSum(&states)
coinsToDistribute = coinsToDistribute.Sub(sum)
}
k.Logger(ctx).Debug("prepare coins to distribute for main account", "subDistr", subDistributorName, "coins", coinsToDistribute.String())
return coinsToDistribute
}
func (k Keeper) prepareCoinToDistributeForNotMainAccount(ctx sdk.Context, source types.Account, states []types.State, subDistributorName string) sdk.DecCoins {
var coinsToDistribute sdk.DecCoins
if types.ModuleAccount == source.Type {
coinsToDistribute = k.prepareCoinToDistributeForModuleAccount(ctx, source, subDistributorName)
} else if types.InternalAccount != source.Type {
coinsToDistribute = k.prepareCoinToDistributeForBaseAccount(ctx, source, subDistributorName)
} else {
coinsToDistribute = sdk.NewDecCoins()
}
return prepareLeftCoinToDistribute(coinsToDistribute, source, states)
}
func (k Keeper) prepareCoinToDistributeForModuleAccount(ctx sdk.Context, source types.Account, subDistributorName string) sdk.DecCoins {
coinsToSend := k.GetAccountCoinsForModuleAccount(ctx, source.Id)
coinsToDistribute := sdk.NewDecCoinsFromCoins(coinsToSend...)
if len(coinsToDistribute) > 0 {
err := k.SendCoinsFromModuleToModule(ctx, coinsToSend, source.Id, types.DistributorMainAccount)
if err != nil {
k.Logger(ctx).Error("prep coins module - send coins to main account", "subDistributorName", subDistributorName, "source", source, "error", err.Error())
return nil
}
}
k.Logger(ctx).Debug("prepare coins to distribute for module account", "subDistr", subDistributorName,
"account", source.Id, "coinsToDistribute", coinsToDistribute.String())
return coinsToDistribute
}
func (k Keeper) prepareCoinToDistributeForBaseAccount(ctx sdk.Context, source types.Account, subDistributorName string) sdk.DecCoins {
srcAccount, _ := sdk.AccAddressFromBech32(source.Id)
coinsToSend := k.GetAccountCoins(ctx, srcAccount)
coinsToDistribute := sdk.NewDecCoinsFromCoins(coinsToSend...)
if len(coinsToDistribute) > 0 {
err := k.SendCoinsToModuleAccount(ctx, coinsToSend, srcAccount, types.DistributorMainAccount)
if err != nil {
k.Logger(ctx).Error("prepare coin to distribute for internal account error", "error", err.Error())
return nil
}
}
k.Logger(ctx).Debug("prepare coins to distribute for base account", "subDistr", subDistributorName,
"account", source.Id, "coinsToDistribute", coinsToDistribute.String())
return coinsToDistribute
}
func prepareLeftCoinToDistribute(coinsToDistribute sdk.DecCoins, source types.Account, states []types.State) sdk.DecCoins {
pos := findAccountState(&states, &source)
if pos >= 0 {
coin := states[pos].Remains
if !coin.IsZero() {
states[pos].Remains = sdk.NewDecCoins()
coinsToDistribute = coinsToDistribute.Add(coin...)
}
}
return coinsToDistribute
}
func (k Keeper) burnCoins(ctx sdk.Context, state *types.State) {
toSend, change := state.Remains.TruncateDecimal()
if err := k.BurnCoinsForSpecifiedModuleAccount(ctx, toSend, types.DistributorMainAccount); err != nil {
ctx.Logger().Error("burn coins error", "state", state, "error", err.Error())
} else {
k.Logger(ctx).Debug("Coins burned", "coins", toSend)
defer func() {
sendCoinsSetGuage(types.BurnDestination, toSend)
}()
state.Remains = change
}
}
func (k Keeper) sendCoinsToModuleAccount(ctx sdk.Context, state *types.State) {
toSend, change := state.Remains.TruncateDecimal()
if err := k.SendCoinsFromModuleToModule(ctx, toSend, types.DistributorMainAccount, state.Account.Id); err != nil {
ctx.Logger().Error("send coins to module account dst error", "accountId", state.Account.Id, "error", err.Error())
} else {
k.Logger(ctx).Debug("coins sent to module account dst", "accountId", state.Account.Id, "toSend", toSend.String())
defer func() {
sendCoinsSetGuage(state.Account.Id, toSend)
}()
state.Remains = change
}
}
func (k Keeper) sendCoinsToBaseAccount(ctx sdk.Context, state *types.State) {
toSend, change := state.Remains.TruncateDecimal()
if dstAccount, err := sdk.AccAddressFromBech32(state.Account.Id); err != nil {
k.Logger(ctx).Error("destination base account address parsing error", "accountId", state.Account.Id, "error", err.Error())
} else if err := k.SendCoinsFromModuleAccount(ctx, toSend, types.DistributorMainAccount, dstAccount); err != nil {
k.Logger(ctx).Error("send coins to base account dst error", "accountId", state.Account.Id, "toSend", toSend, "error", err.Error())
} else {
k.Logger(ctx).Debug("coins sent to base account dst", "accountId", state.Account.Id, "toSend", toSend)
defer func() {
sendCoinsSetGuage(state.Account.Id, toSend)
}()
state.Remains = change
}
}
func sendCoinsSetGuage(accountName string, coins sdk.Coins) {
for _, coin := range coins {
telemetry.SetGaugeWithLabels(
[]string{types.ModuleName, "coin_send", coin.Denom, accountName},
float32(coin.Amount.Int64()),
[]metrics.Label{telemetry.NewLabel("denom", coin.Denom)},
)
}
}
func (k Keeper) SendCoinsFromStates(ctx sdk.Context, states []types.State) {
for _, state := range states {
if (state.Account == nil || types.InternalAccount != state.Account.Type) && checkIfAnyCoinIsGTE1(state.Remains) {
if state.Burn {
k.burnCoins(ctx, &state)
} else if types.ModuleAccount == state.Account.Type {
k.sendCoinsToModuleAccount(ctx, &state)
} else {
k.sendCoinsToBaseAccount(ctx, &state)
}
}
k.SetState(ctx, state)
}
}
func checkIfAnyCoinIsGTE1(coins sdk.DecCoins) bool {
if len(coins) == 0 {
return false
}
for _, coin := range coins {
if coin.Amount.GTE(sdk.NewDec(1)) {
return true
}
}
return false
}
func (k Keeper) addSharesToBurnState(ctx sdk.Context, localRemains *[]types.State, calculatedShare sdk.DecCoins, findState func() int) *[]types.State {
return k.addSharesToState(ctx, localRemains, true, nil, calculatedShare, findState)
}
func (k Keeper) addSharesToAccountState(ctx sdk.Context, localRemains *[]types.State, account *types.Account, calculatedShare sdk.DecCoins, findState func() int) *[]types.State {
return k.addSharesToState(ctx, localRemains, false, account, calculatedShare, findState)
}
func (k Keeper) addSharesToState(ctx sdk.Context, localRemains *[]types.State, burn bool, account *types.Account, calculatedShare sdk.DecCoins, findState func() int) *[]types.State {
pos := findState()
logger := k.Logger(ctx).With("localRemains", localRemains, "account", account, "burn", burn,
"calculatedShare", calculatedShare.String(), "pos", pos)
if pos < 0 {
var state types.State
if burn || account == nil {
state = types.State{Account: nil, Remains: sdk.NewDecCoins(), Burn: true}
} else {
state = types.State{Account: account, Remains: sdk.NewDecCoins(), Burn: false}
}
withAppended := append(*localRemains, state)
localRemains = &withAppended
pos = len(*localRemains) - 1
logger.Debug("add shares to state", "state", state)
} else {
logger.Debug("add shares to state")
}
(*localRemains)[pos].Remains = (*localRemains)[pos].Remains.Add(calculatedShare...)
return localRemains
}
func (k Keeper) StartDistributionProcess(ctx sdk.Context, states *[]types.State, coinsToDistributeDec sdk.DecCoins, subDistributor types.SubDistributor) (localRemains *[]types.State, distributionEvents []*types.EventDistribution, burnEvent *types.EventDistributionBurn) {
k.Logger(ctx).Debug("start distribution process", "subDistributor", subDistributor.String(),
"coinsToDistributeDec", coinsToDistributeDec.String())
localRemains = states
defaultShare := coinsToDistributeDec
for _, share := range subDistributor.Destinations.Shares {
if share.Destination.Type == types.Main {
continue
}
calculatedShare := calculatePercentage(share.Share, coinsToDistributeDec)
defaultShare = defaultShare.Sub(calculatedShare)
if !calculatedShare.IsZero() {
findFunc := func() int {
return findAccountState(localRemains, &share.Destination)
}
localRemains = k.addSharesToAccountState(ctx, localRemains, &share.Destination, calculatedShare, findFunc)
distributionEvents = append(distributionEvents, &types.EventDistribution{
Subdistributor: subDistributor.Name,
ShareName: share.Name,
Sources: subDistributor.Sources,
Destination: &share.Destination,
Amount: calculatedShare,
})
}
}
if subDistributor.Destinations.BurnShare != sdk.ZeroDec() {
calculatedShare := calculatePercentage(subDistributor.Destinations.BurnShare, coinsToDistributeDec)
defaultShare = defaultShare.Sub(calculatedShare)
if !calculatedShare.IsZero() {
findFunc := func() int {
return findBurnState(localRemains)
}
localRemains = k.addSharesToBurnState(ctx, localRemains, calculatedShare, findFunc)
burnEvent = &types.EventDistributionBurn{
Subdistributor: subDistributor.Name,
Sources: subDistributor.Sources,
Amount: calculatedShare,
}
}
}
accountDefault := subDistributor.Destinations.GetPrimaryShare()
if accountDefault.Type != types.Main {
findFunc := func() int {
return findAccountState(localRemains, &accountDefault)
}
localRemains = k.addSharesToAccountState(ctx, localRemains, &accountDefault, defaultShare, findFunc)
distributionEvents = append(distributionEvents, &types.EventDistribution{
Subdistributor: subDistributor.Name,
ShareName: subDistributor.GetPrimaryShareName(),
Sources: subDistributor.Sources,
Destination: &subDistributor.Destinations.PrimaryShare,
Amount: defaultShare,
})
}
k.Logger(ctx).Debug("start distribution process ret", "subDistributor", subDistributor.String(), "localRemains", localRemains)
return
}