-
Notifications
You must be signed in to change notification settings - Fork 21
/
gov_transfers.go
433 lines (383 loc) · 17.8 KB
/
gov_transfers.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package banking
import (
"context"
"encoding/hex"
"errors"
"fmt"
"time"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/crypto"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/libs/proto"
"code.vegaprotocol.io/vega/logging"
vegapb "code.vegaprotocol.io/vega/protos/vega"
)
var (
validSources = map[types.AccountType]struct{}{
types.AccountTypeInsurance: {},
types.AccountTypeGlobalInsurance: {},
types.AccountTypeGlobalReward: {},
types.AccountTypeNetworkTreasury: {},
}
validDestinations = map[types.AccountType]struct{}{
types.AccountTypeInsurance: {},
types.AccountTypeGlobalInsurance: {},
types.AccountTypeGlobalReward: {},
types.AccountTypeNetworkTreasury: {},
types.AccountTypeGeneral: {},
types.AccountTypeMakerPaidFeeReward: {},
types.AccountTypeMakerReceivedFeeReward: {},
types.AccountTypeMarketProposerReward: {},
types.AccountTypeLPFeeReward: {},
types.AccountTypeAveragePositionReward: {},
types.AccountTypeRelativeReturnReward: {},
types.AccountTypeReturnVolatilityReward: {},
types.AccountTypeValidatorRankingReward: {},
types.AccountTypeRealisedReturnReward: {},
}
)
func (e *Engine) distributeScheduledGovernanceTransfers(ctx context.Context, now time.Time) {
timepoints := []int64{}
for k := range e.scheduledGovernanceTransfers {
if now.UnixNano() >= k {
timepoints = append(timepoints, k)
}
}
for _, t := range timepoints {
transfers := e.scheduledGovernanceTransfers[t]
for _, gTransfer := range transfers {
_, err := e.processGovernanceTransfer(ctx, gTransfer)
if err != nil {
gTransfer.Status = types.TransferStatusStopped
e.broker.Send(events.NewGovTransferFundsEventWithReason(ctx, gTransfer, gTransfer.Config.MaxAmount, err.Error(), e.getGovGameID(gTransfer)))
} else {
gTransfer.Status = types.TransferStatusDone
e.broker.Send(events.NewGovTransferFundsEvent(ctx, gTransfer, gTransfer.Config.MaxAmount, e.getGovGameID(gTransfer)))
}
}
delete(e.scheduledGovernanceTransfers, t)
}
}
func (e *Engine) distributeRecurringGovernanceTransfers(ctx context.Context) {
var (
transfersDone = []events.Event{}
doneIDs = []string{}
)
for _, gTransfer := range e.recurringGovernanceTransfers {
e.log.Info("distributeRecurringGovernanceTransfers", logging.Uint64("epoch", e.currentEpoch), logging.String("transfer", gTransfer.IntoProto().String()))
if gTransfer.Config.RecurringTransferConfig.StartEpoch > e.currentEpoch {
continue
}
if gTransfer.Config.RecurringTransferConfig.DispatchStrategy != nil && gTransfer.Config.RecurringTransferConfig.DispatchStrategy.TransferInterval != nil &&
((e.currentEpoch-gTransfer.Config.RecurringTransferConfig.StartEpoch+1) < uint64(*gTransfer.Config.RecurringTransferConfig.DispatchStrategy.TransferInterval) ||
(e.currentEpoch-gTransfer.Config.RecurringTransferConfig.StartEpoch+1)%uint64(*gTransfer.Config.RecurringTransferConfig.DispatchStrategy.TransferInterval) != 0) {
continue
}
amount, err := e.processGovernanceTransfer(ctx, gTransfer)
e.log.Info("processed transfer", logging.String("amount", amount.String()))
if err != nil {
e.log.Error("error calculating transfer amount for governance transfer", logging.Error(err))
gTransfer.Status = types.TransferStatusStopped
transfersDone = append(transfersDone, events.NewGovTransferFundsEventWithReason(ctx, gTransfer, gTransfer.Config.MaxAmount, err.Error(), e.getGovGameID(gTransfer)))
doneIDs = append(doneIDs, gTransfer.ID)
continue
}
if gTransfer.Config.RecurringTransferConfig.EndEpoch != nil && *gTransfer.Config.RecurringTransferConfig.EndEpoch == e.currentEpoch {
gTransfer.Status = types.TransferStatusDone
transfersDone = append(transfersDone, events.NewGovTransferFundsEvent(ctx, gTransfer, gTransfer.Config.MaxAmount, e.getGovGameID(gTransfer)))
doneIDs = append(doneIDs, gTransfer.ID)
e.log.Info("recurrent transfer is done", logging.String("transfer ID", gTransfer.ID))
continue
}
}
if len(transfersDone) > 0 {
for _, id := range doneIDs {
e.deleteGovTransfer(id)
}
for _, d := range transfersDone {
e.log.Info("transfersDone", logging.String("event", d.StreamMessage().String()))
}
e.broker.SendBatch(transfersDone)
}
}
func (e *Engine) deleteGovTransfer(ID string) {
index := -1
for i, rt := range e.recurringGovernanceTransfers {
if rt.ID == ID {
index = i
e.unregisterDispatchStrategy(rt.Config.RecurringTransferConfig.DispatchStrategy)
break
}
}
if index >= 0 {
e.recurringGovernanceTransfers = append(e.recurringGovernanceTransfers[:index], e.recurringGovernanceTransfers[index+1:]...)
delete(e.recurringGovernanceTransfersMap, ID)
}
}
func (e *Engine) NewGovernanceTransfer(ctx context.Context, ID, reference string, config *types.NewTransferConfiguration) error {
var err error
var gTransfer *types.GovernanceTransfer
defer func() {
if err != nil {
e.broker.Send(events.NewGovTransferFundsEventWithReason(ctx, gTransfer, gTransfer.Config.MaxAmount, err.Error(), e.getGovGameID(gTransfer)))
} else {
e.broker.Send(events.NewGovTransferFundsEvent(ctx, gTransfer, gTransfer.Config.MaxAmount, e.getGovGameID(gTransfer)))
}
}()
now := e.timeService.GetTimeNow()
gTransfer = &types.GovernanceTransfer{
ID: ID,
Reference: reference,
Config: config,
Status: types.TransferStatusPending,
Timestamp: now,
}
if config.Kind == types.TransferKindOneOff {
// one off governance transfer to be executed straight away
if config.OneOffTransferConfig.DeliverOn == 0 || config.OneOffTransferConfig.DeliverOn < now.UnixNano() {
_, err = e.processGovernanceTransfer(ctx, gTransfer)
if err != nil {
gTransfer.Status = types.TransferStatusRejected
return err
}
gTransfer.Status = types.TransferStatusDone
return nil
}
// scheduled one off governance transfer
if _, ok := e.scheduledGovernanceTransfers[config.OneOffTransferConfig.DeliverOn]; !ok {
e.scheduledGovernanceTransfers[config.OneOffTransferConfig.DeliverOn] = []*types.GovernanceTransfer{}
}
e.scheduledGovernanceTransfers[config.OneOffTransferConfig.DeliverOn] = append(e.scheduledGovernanceTransfers[config.OneOffTransferConfig.DeliverOn], gTransfer)
gTransfer.Status = types.TransferStatusPending
return nil
}
// recurring governance transfer
e.recurringGovernanceTransfers = append(e.recurringGovernanceTransfers, gTransfer)
e.recurringGovernanceTransfersMap[ID] = gTransfer
e.registerDispatchStrategy(gTransfer.Config.RecurringTransferConfig.DispatchStrategy)
return nil
}
func CalculateDecayedAmount(initialAmount *num.Uint, startEpoch, currentEpoch uint64, decayFactor string) *num.Uint {
if len(decayFactor) == 0 {
return initialAmount
}
factor := num.MustDecimalFromString(decayFactor)
amount, _ := num.UintFromDecimal(initialAmount.ToDecimal().Mul(factor.Pow(num.NewUint(currentEpoch).ToDecimal().Sub(num.NewUint(startEpoch).ToDecimal()))))
return amount
}
// processGovernanceTransfer process a governance transfer and emit ledger movement events.
func (e *Engine) processGovernanceTransfer(
ctx context.Context,
gTransfer *types.GovernanceTransfer,
) (*num.Uint, error) {
amount := gTransfer.Config.MaxAmount
if gTransfer.Config.RecurringTransferConfig != nil {
amount = CalculateDecayedAmount(amount, gTransfer.Config.RecurringTransferConfig.StartEpoch, e.currentEpoch, gTransfer.Config.RecurringTransferConfig.Factor)
}
transferAmount, err := e.CalculateGovernanceTransferAmount(gTransfer.Config.Asset, gTransfer.Config.Source, gTransfer.Config.SourceType, gTransfer.Config.FractionOfBalance, amount, gTransfer.Config.TransferType)
if err != nil {
e.log.Error("failed to calculate amount for governance transfer", logging.String("proposal", gTransfer.ID), logging.String("error", err.Error()))
return num.UintZero(), err
}
from := "*"
fromMarket := gTransfer.Config.Source
toMarket := ""
to := gTransfer.Config.Destination
if gTransfer.Config.DestinationType == types.AccountTypeGlobalReward {
to = "*"
} else if gTransfer.Config.DestinationType == types.AccountTypeInsurance {
toMarket = to
to = "*"
}
if gTransfer.Config.RecurringTransferConfig != nil && gTransfer.Config.RecurringTransferConfig.DispatchStrategy != nil {
var resps []*types.LedgerMovement
ds := gTransfer.Config.RecurringTransferConfig.DispatchStrategy
// if the metric is market value we make the transfer to the market account (as opposed to the metric's hash account)
if ds.Metric == vegapb.DispatchMetric_DISPATCH_METRIC_MARKET_VALUE {
marketProposersScore := e.marketActivityTracker.GetMarketsWithEligibleProposer(ds.AssetForMetric, ds.Markets, gTransfer.Config.Asset, gTransfer.Config.Source)
for _, fms := range marketProposersScore {
amt, _ := num.UintFromDecimal(transferAmount.ToDecimal().Mul(fms.Score))
if amt.IsZero() {
continue
}
fromTransfer, toTransfer := e.makeTransfers(from, to, gTransfer.Config.Asset, fromMarket, fms.Market, amt, &gTransfer.ID)
transfers := []*types.Transfer{fromTransfer, toTransfer}
accountTypes := []types.AccountType{gTransfer.Config.SourceType, gTransfer.Config.DestinationType}
references := []string{gTransfer.Reference, gTransfer.Reference}
tresps, err := e.col.GovernanceTransferFunds(ctx, transfers, accountTypes, references)
if err != nil {
e.log.Error("error transferring governance transfer funds", logging.Error(err))
return num.UintZero(), err
}
if fms.Score.IsPositive() {
e.marketActivityTracker.MarkPaidProposer(ds.AssetForMetric, fms.Market, gTransfer.Config.Asset, gTransfer.Config.RecurringTransferConfig.DispatchStrategy.Markets, from)
}
resps = append(resps, tresps...)
}
}
// here we transfer the governance transfer amount into the account: transfer_asset/dispatch_hash/reward_account_type
if e.dispatchRequired(ctx, gTransfer.Config.RecurringTransferConfig.DispatchStrategy) {
p, _ := proto.Marshal(gTransfer.Config.RecurringTransferConfig.DispatchStrategy)
hash := hex.EncodeToString(crypto.Hash(p))
fromTransfer, toTransfer := e.makeTransfers(from, to, gTransfer.Config.Asset, fromMarket, hash, transferAmount, &gTransfer.ID)
transfers := []*types.Transfer{fromTransfer, toTransfer}
accountTypes := []types.AccountType{gTransfer.Config.SourceType, gTransfer.Config.DestinationType}
references := []string{gTransfer.Reference, gTransfer.Reference}
tresps, err := e.col.GovernanceTransferFunds(ctx, transfers, accountTypes, references)
if err != nil {
e.log.Error("error transferring governance transfer funds", logging.Error(err))
return num.UintZero(), err
}
resps = append(resps, tresps...)
}
if len(resps) > 0 {
e.broker.Send(events.NewLedgerMovements(ctx, resps))
return transferAmount, nil
}
return num.UintZero(), nil
}
fromTransfer, toTransfer := e.makeTransfers(from, to, gTransfer.Config.Asset, fromMarket, toMarket, transferAmount, &gTransfer.ID)
transfers := []*types.Transfer{fromTransfer, toTransfer}
accountTypes := []types.AccountType{gTransfer.Config.SourceType, gTransfer.Config.DestinationType}
references := []string{gTransfer.Reference, gTransfer.Reference}
tresps, err := e.col.GovernanceTransferFunds(ctx, transfers, accountTypes, references)
if err != nil {
e.log.Error("error transferring governance transfer funds", logging.Error(err))
return num.UintZero(), err
}
for _, lm := range tresps {
e.log.Info("processGovernanceTransfer", logging.String("ledger-movement", lm.IntoProto().String()))
}
e.broker.Send(events.NewLedgerMovements(ctx, tresps))
return transferAmount, nil
}
// CalculateGovernanceTransferAmount calculates the balance of a governance transfer as follows:
//
// transfer_amount = min(
//
// proposal.fraction_of_balance * source.balance,
// proposal.amount,
// NETWORK_MAX_AMOUNT,
// NETWORK_MAX_FRACTION * source.balance
//
// )
// where
// NETWORK_MAX_AMOUNT is a network parameter specifying the maximum absolute amount that can be transferred by governance for the source account type
// NETWORK_MAX_FRACTION is a network parameter specifying the maximum fraction of the balance that can be transferred by governance for the source account type (must be <= 1)
//
// If type is "all or nothing" then the transfer will only proceed if:
//
// transfer_amount == min(proposal.fraction_of_balance * source.balance,proposal.amount).
func (e *Engine) CalculateGovernanceTransferAmount(asset string, market string, accountType types.AccountType, fraction num.Decimal, amount *num.Uint, transferType vegapb.GovernanceTransferType) (*num.Uint, error) {
balance, err := e.col.GetSystemAccountBalance(asset, market, accountType)
if err != nil {
e.log.Error("could not find system account balance for", logging.String("asset", asset), logging.String("market", market), logging.String("account-type", accountType.String()))
return nil, err
}
a, err := e.assets.Get(asset)
if err != nil {
e.log.Debug("cannot transfer funds, invalid asset", logging.Error(err))
return nil, fmt.Errorf("could not transfer funds, %w", err)
}
quantum := a.Type().Details.Quantum
globalMaxAmount, _ := num.UintFromDecimal(quantum.Mul(e.maxGovTransferQunatumMultiplier))
amountFromMaxFraction, _ := num.UintFromDecimal(e.maxGovTransferFraction.Mul(balance.ToDecimal()))
amountFromProposalFraction, _ := num.UintFromDecimal(fraction.Mul(balance.ToDecimal()))
min1 := num.Min(amountFromMaxFraction, amountFromProposalFraction)
min2 := num.Min(amount, globalMaxAmount)
amt := num.Min(min1, min2)
if transferType == vegapb.GovernanceTransferType_GOVERNANCE_TRANSFER_TYPE_ALL_OR_NOTHING && amt.NEQ(num.Min(amountFromProposalFraction, amount)) {
e.log.Error("could not process governance transfer with type all of nothing", logging.String("transfer-amount", amt.String()), logging.String("fraction-of-balance", amountFromProposalFraction.String()), logging.String("amount", amount.String()))
return nil, errors.New("invalid transfer amount for transfer type all or nothing")
}
return amt, nil
}
func (e *Engine) VerifyGovernanceTransfer(transfer *types.NewTransferConfiguration) error {
if transfer == nil {
return errors.New("missing transfer configuration")
}
// check source type is valid
if _, ok := validSources[transfer.SourceType]; !ok {
return errors.New("invalid source type for governance transfer")
}
// check destination type is valid
if _, ok := validDestinations[transfer.DestinationType]; !ok {
return errors.New("invalid destination for governance transfer")
}
// check asset is not empty
if len(transfer.Asset) == 0 {
return errors.New("missing asset for governance transfer")
}
// check if destination market insurance account exist
if transfer.DestinationType == types.AccountTypeInsurance && len(transfer.Destination) > 0 {
_, err := e.col.GetSystemAccountBalance(transfer.Asset, transfer.Destination, transfer.DestinationType)
if err != nil {
return err
}
}
// verify systemn destination account which ought to preexist actually exists
if (transfer.RecurringTransferConfig == nil || transfer.RecurringTransferConfig.DispatchStrategy == nil) &&
len(transfer.Destination) == 0 &&
transfer.DestinationType != types.AccountTypeGeneral {
_, err := e.col.GetSystemAccountBalance(transfer.Asset, transfer.Destination, transfer.DestinationType)
if err != nil {
return err
}
}
if transfer.RecurringTransferConfig != nil && transfer.RecurringTransferConfig.DispatchStrategy != nil {
if len(transfer.RecurringTransferConfig.DispatchStrategy.AssetForMetric) > 0 {
if _, err := e.assets.Get(transfer.RecurringTransferConfig.DispatchStrategy.AssetForMetric); err != nil {
return fmt.Errorf("could not transfer funds, invalid asset for metric: %w", err)
}
}
}
// check source account exists
if _, err := e.col.GetSystemAccountBalance(transfer.Asset, transfer.Source, transfer.SourceType); err != nil {
return err
}
// check transfer type is specified
if transfer.TransferType == vegapb.GovernanceTransferType_GOVERNANCE_TRANSFER_TYPE_UNSPECIFIED {
return errors.New("invalid governance transfer type")
}
// check max amount is positive
if transfer.MaxAmount == nil || transfer.MaxAmount.IsNegative() || transfer.MaxAmount.IsZero() {
return errors.New("invalid max amount for governance transfer")
}
// check fraction of balance is positive
if !transfer.FractionOfBalance.IsPositive() {
return errors.New("invalid fraction of balance for governance transfer")
}
// verify recurring transfer starting epoch is not in the past
if transfer.RecurringTransferConfig != nil && transfer.RecurringTransferConfig.StartEpoch < e.currentEpoch {
return ErrStartEpochInThePast
}
return nil
}
func (e *Engine) VerifyCancelGovernanceTransfer(transferID string) error {
if _, ok := e.recurringGovernanceTransfersMap[transferID]; !ok {
return fmt.Errorf("Governance transfer %s not found", transferID)
}
return nil
}
func (e *Engine) getGovGameID(transfer *types.GovernanceTransfer) *string {
if transfer.Config.RecurringTransferConfig == nil || transfer.Config.RecurringTransferConfig.DispatchStrategy == nil {
return nil
}
gameID := e.hashDispatchStrategy(transfer.Config.RecurringTransferConfig.DispatchStrategy)
return &gameID
}