-
Notifications
You must be signed in to change notification settings - Fork 21
/
liquidity_provision_fees.go
318 lines (255 loc) · 9.52 KB
/
liquidity_provision_fees.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
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.VEGA file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package common
import (
"context"
"fmt"
"math/rand"
"sort"
"time"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/liquidity/v2"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/logging"
"golang.org/x/exp/constraints"
)
func (m *MarketLiquidity) NewTransfer(partyID string, transferType types.TransferType, amount *num.Uint) *types.Transfer {
return &types.Transfer{
Owner: partyID,
Amount: &types.FinancialAmount{
Asset: m.asset,
Amount: amount.Clone(),
},
Type: transferType,
MinAmount: amount.Clone(),
Market: m.marketID,
}
}
type FeeTransfer struct {
transfers []*types.Transfer
totalFeesPerParty map[string]*num.Uint
}
func NewFeeTransfer(transfers []*types.Transfer, totalFeesPerParty map[string]*num.Uint) FeeTransfer {
return FeeTransfer{
transfers: transfers,
totalFeesPerParty: totalFeesPerParty,
}
}
func (ft FeeTransfer) Transfers() []*types.Transfer {
return ft.transfers
}
func (ft FeeTransfer) TotalFeesAmountPerParty() map[string]*num.Uint {
return ft.totalFeesPerParty
}
func (m *MarketLiquidity) readyForFeesAllocation(now time.Time) bool {
return now.Sub(m.liquidityEngine.GetLastFeeDistributionTime()) > m.feeCalculationTimeStep
}
// AllocateFees distributes fee from a market fee account to LP fee accounts.
func (m *MarketLiquidity) AllocateFees(ctx context.Context) error {
acc, err := m.collateral.GetMarketLiquidityFeeAccount(m.marketID, m.asset)
if err != nil {
return fmt.Errorf("failed to get market liquidity fee account: %w", err)
}
// We can't distribute any share when no balance.
if acc.Balance.IsZero() {
return nil
}
// Get equity like shares per party.
sharesPerLp := m.equityShares.AllShares()
if len(sharesPerLp) == 0 {
return nil
}
scoresPerLp := m.liquidityEngine.GetAverageLiquidityScores()
// Multiplies each equity like share with corresponding score.
updatedShares := m.updateSharesWithLiquidityScores(sharesPerLp, scoresPerLp)
feeTransfer := m.fee.BuildLiquidityFeeAllocationTransfer(updatedShares, acc)
if feeTransfer == nil {
return nil
}
m.marketActivityTracker.UpdateFeesFromTransfers(m.asset, m.marketID, feeTransfer.Transfers())
ledgerMovements, err := m.transferFees(ctx, feeTransfer)
if err != nil {
return fmt.Errorf("failed to transfer fees: %w", err)
}
if len(ledgerMovements) > 0 {
m.broker.Send(events.NewLedgerMovements(ctx, ledgerMovements))
}
return nil
}
func (m *MarketLiquidity) processBondPenalties(
ctx context.Context,
partyIDs []string,
penaltiesPerParty map[string]*liquidity.SlaPenalty,
) {
ledgerMovements := make([]*types.LedgerMovement, 0, len(partyIDs))
for _, partyID := range partyIDs {
penalty := penaltiesPerParty[partyID]
provision := m.liquidityEngine.LiquidityProvisionByPartyID(partyID)
// bondPenalty x commitmentAmount.
amount := penalty.Bond.Mul(provision.CommitmentAmount.ToDecimal())
amountUint, _ := num.UintFromDecimal(amount)
transfer := m.NewTransfer(partyID, types.TransferTypeSLAPenaltyBondApply, amountUint)
bondLedgerMovement, err := m.bondUpdate(ctx, transfer)
if err != nil {
m.log.Panic("failed to apply SLA penalties to bond account", logging.Error(err))
}
ledgerMovements = append(ledgerMovements, bondLedgerMovement)
}
if len(ledgerMovements) > 0 {
m.broker.Send(events.NewLedgerMovements(ctx, ledgerMovements))
}
}
func (m *MarketLiquidity) getAccruedPerPartyAndTotalFees(partyIDs []string) (map[string]*num.Uint, *num.Uint) {
perParty := map[string]*num.Uint{}
total := num.UintZero()
for _, partyID := range partyIDs {
liquidityFeeAcc, err := m.collateral.GetPartyLiquidityFeeAccount(m.marketID, partyID, m.asset)
if err != nil {
m.log.Panic("failed to get party liquidity fee account", logging.Error(err))
}
perParty[partyID] = liquidityFeeAcc.Balance.Clone()
total.AddSum(liquidityFeeAcc.Balance)
}
return perParty, total
}
func (m *MarketLiquidity) distributeFeesAndCalculateBonuses(
ctx context.Context,
partyIDs []string,
slaPenalties liquidity.SlaPenalties,
) map[string]num.Decimal {
perPartAccruedFees, totalAccruedFees := m.getAccruedPerPartyAndTotalFees(partyIDs)
allTransfers := FeeTransfer{
transfers: []*types.Transfer{},
totalFeesPerParty: perPartAccruedFees,
}
bonusPerParty := map[string]num.Decimal{}
totalBonuses := num.DecimalZero()
for _, partyID := range partyIDs {
accruedFeeAmount := perPartAccruedFees[partyID]
// if all parties have a full penalty then transfer all accrued fees to insurance pool.
if slaPenalties.AllPartiesHaveFullFeePenalty {
transfer := m.NewTransfer(partyID, types.TransferTypeSLAPenaltyLpFeeApply, accruedFeeAmount)
allTransfers.transfers = append(allTransfers.transfers, transfer)
continue
}
penalty := slaPenalties.PenaltiesPerParty[partyID]
oneMinusPenalty := num.DecimalOne().Sub(penalty.Fee)
// transfers fees after penalty is applied.
// (1-feePenalty) x accruedFeeAmount.
netDistributionAmount := oneMinusPenalty.Mul(accruedFeeAmount.ToDecimal())
netDistributionAmountUint, _ := num.UintFromDecimal(netDistributionAmount)
netFeeDistributeTransfer := m.NewTransfer(partyID, types.TransferTypeLiquidityFeeNetDistribute, netDistributionAmountUint)
allTransfers.transfers = append(allTransfers.transfers, netFeeDistributeTransfer)
// transfer unpaid accrued fee to bonus account
// accruedFeeAmount - netDistributionAmountUint
unpaidFees := num.UintZero().Sub(accruedFeeAmount, netDistributionAmountUint)
if !unpaidFees.IsZero() {
unpaidFeesTransfer := m.NewTransfer(partyID, types.TransferTypeLiquidityFeeUnpaidCollect, unpaidFees)
allTransfers.transfers = append(allTransfers.transfers, unpaidFeesTransfer)
}
bonus := num.DecimalZero()
// this is just to avoid panic.
if !totalAccruedFees.IsZero() {
// calculate bonus.
// (1-feePenalty) x (accruedFeeAmount/totalAccruedFees).
bonus = oneMinusPenalty.Mul(accruedFeeAmount.ToDecimal().Div(totalAccruedFees.ToDecimal()))
}
totalBonuses = totalBonuses.Add(bonus)
bonusPerParty[partyID] = bonus
}
// transfer all the fees.
ledgerMovements, err := m.transferFees(ctx, allTransfers)
if err != nil {
m.log.Panic("failed to transfer fees from LP's fees accounts", logging.Error(err))
}
if len(ledgerMovements) > 0 {
m.broker.Send(events.NewLedgerMovements(ctx, ledgerMovements))
}
if !totalBonuses.IsZero() {
// normalize bonuses.
for party, bonus := range bonusPerParty {
// bonus / totalBonuses.
bonusPerParty[party] = bonus.Div(totalBonuses)
}
}
return bonusPerParty
}
func (m *MarketLiquidity) distributePerformanceBonuses(
ctx context.Context,
partyIDs []string,
bonuses map[string]num.Decimal,
) {
bonusDistributionAcc, err := m.collateral.GetLiquidityFeesBonusDistributionAccount(m.marketID, m.asset)
if err != nil {
m.log.Panic("failed to get bonus distribution account", logging.Error(err))
}
bonusTransfers := FeeTransfer{
transfers: []*types.Transfer{},
}
remainingBalance := bonusDistributionAcc.Balance.Clone()
for _, partyID := range partyIDs {
bonus := bonuses[partyID]
// if bonus is 0 there is no need to process.
if bonus.IsZero() {
continue
}
amountD := bonus.Mul(bonusDistributionAcc.Balance.ToDecimal())
amount, _ := num.UintFromDecimal(amountD)
transfer := m.NewTransfer(partyID, types.TransferTypeSlaPerformanceBonusDistribute, amount)
bonusTransfers.transfers = append(bonusTransfers.transfers, transfer)
remainingBalance.Sub(remainingBalance, amount)
}
// in case of remaining balance choose pseudo random provider to receive it.
if !remainingBalance.IsZero() {
keys := sortedKeys(bonuses)
rand.Seed(remainingBalance.BigInt().Int64())
randIndex := rand.Intn(len(keys))
selectedParty := keys[randIndex]
transfer := m.NewTransfer(selectedParty, types.TransferTypeSlaPerformanceBonusDistribute, remainingBalance)
bonusTransfers.transfers = append(bonusTransfers.transfers, transfer)
}
ledgerMovements, err := m.transferFees(ctx, bonusTransfers)
if err != nil {
m.log.Panic("failed to distribute SLA bonuses", logging.Error(err))
}
if len(ledgerMovements) > 0 {
m.broker.Send(events.NewLedgerMovements(ctx, ledgerMovements))
}
}
func (m *MarketLiquidity) distributeFeesBonusesAndApplyPenalties(
ctx context.Context,
slaPenalties liquidity.SlaPenalties,
) {
// No LP penalties available so no need to continue.
// This could happen during opening auction.
if len(slaPenalties.PenaltiesPerParty) < 1 {
return
}
partyIDs := sortedKeys(slaPenalties.PenaltiesPerParty)
// first process bond penalties.
m.processBondPenalties(ctx, partyIDs, slaPenalties.PenaltiesPerParty)
// then distribute fees and calculate bonus.
bonusPerParty := m.distributeFeesAndCalculateBonuses(ctx, partyIDs, slaPenalties)
// lastly distribute performance bonus.
m.distributePerformanceBonuses(ctx, partyIDs, bonusPerParty)
}
func sortedKeys[K constraints.Ordered, V any](m map[K]V) []K {
keys := make([]K, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i] < keys[j]
})
return keys
}