Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add MakerFees to FeeStats #9764

Merged
merged 3 commits into from
Oct 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@
- [2985](https://github.com/vegaprotocol/system-tests/issues/2985) - Coverage for insurance pool transfers, fix deadlock when terminating pending market through governance.
- [9770](https://github.com/vegaprotocol/vega/issues/9770) - Fix `PnL` flickering bug.
- [9785](https://github.com/vegaprotocol/vega/issues/9785) - Support transfers to network treasury.
- [9743](https://github.com/vegaprotocol/system-tests/issues/9743) - Expose maker fees in fees stats API.

### 🐛 Fixes

Expand Down
11 changes: 5 additions & 6 deletions core/execution/future/market.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import (
"code.vegaprotocol.io/vega/libs/ptr"
"code.vegaprotocol.io/vega/logging"
vegapb "code.vegaprotocol.io/vega/protos/vega"

"golang.org/x/exp/maps"
)

Expand Down Expand Up @@ -362,12 +363,10 @@ func (m *Market) OnEpochEvent(ctx context.Context, epoch types.Epoch) {
if !m.finalFeesDistributed {
m.liquidity.OnEpochEnd(ctx, m.timeService.GetTimeNow())
}
FeesStats := m.fee.GetFeesStatsOnEpochEnd()
FeesStats.Market = m.GetID()
FeesStats.EpochSeq = epoch.Seq
m.broker.Send(
events.NewFeesStatsEvent(ctx, FeesStats),
)
feesStats := m.fee.GetFeesStatsOnEpochEnd()
feesStats.Market = m.GetID()
feesStats.EpochSeq = epoch.Seq
m.broker.Send(events.NewFeesStatsEvent(ctx, feesStats))
}

m.updateLiquidityFee(ctx)
Expand Down
43 changes: 24 additions & 19 deletions core/fee/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func (e *Engine) CalculateForContinuousMode(
}

var (
aggressor, maker string
taker, maker string
totalFeeAmount = num.UintZero()
totalInfrastructureFeeAmount = num.UintZero()
totalLiquidityFeeAmount = num.UintZero()
Expand All @@ -162,29 +162,34 @@ func (e *Engine) CalculateForContinuousMode(
transfersRecv = make([]*types.Transfer, 0, len(trades)+2)
)

for _, v := range trades {
aggressor = v.Buyer
if v.Aggressor == types.SideSell {
aggressor = v.Seller
for _, trade := range trades {
taker = trade.Buyer
maker = trade.Seller
if trade.Aggressor == types.SideSell {
taker = trade.Seller
maker = trade.Buyer
}
fee, reward := e.applyDiscountsAndRewards(aggressor, e.calculateContinuousModeFees(v), referral, volumeDiscountService)
switch v.Aggressor {
fee, reward := e.applyDiscountsAndRewards(taker, e.calculateContinuousModeFees(trade), referral, volumeDiscountService)

e.feesStats.RegisterMakerFee(maker, taker, fee.MakerFee)

switch trade.Aggressor {
case types.SideBuy:
v.BuyerFee = fee
v.SellerFee = types.NewFee()
maker = v.Seller
trade.BuyerFee = fee
trade.SellerFee = types.NewFee()
maker = trade.Seller
case types.SideSell:
v.SellerFee = fee
v.BuyerFee = types.NewFee()
maker = v.Buyer
trade.SellerFee = fee
trade.BuyerFee = types.NewFee()
maker = trade.Buyer
}

totalFeeAmount.AddSum(fee.InfrastructureFee, fee.LiquidityFee, fee.MakerFee)
totalInfrastructureFeeAmount.AddSum(fee.InfrastructureFee)
totalLiquidityFeeAmount.AddSum(fee.LiquidityFee)
// create a transfer for the aggressor
transfers = append(transfers, &types.Transfer{
Owner: aggressor,
Owner: taker,
Amount: &types.FinancialAmount{
Asset: e.asset,
Amount: fee.MakerFee.Clone(),
Expand All @@ -211,7 +216,7 @@ func (e *Engine) CalculateForContinuousMode(

// now create transfer for the infrastructure
transfers = append(transfers, &types.Transfer{
Owner: aggressor,
Owner: taker,
Amount: &types.FinancialAmount{
Asset: e.asset,
Amount: totalInfrastructureFeeAmount,
Expand All @@ -220,7 +225,7 @@ func (e *Engine) CalculateForContinuousMode(
})
// now create transfer for the liquidity
transfers = append(transfers, &types.Transfer{
Owner: aggressor,
Owner: taker,
Amount: &types.FinancialAmount{
Asset: e.asset,
Amount: totalLiquidityFeeAmount,
Expand All @@ -230,9 +235,9 @@ func (e *Engine) CalculateForContinuousMode(

// if there's a referral reward - add transfers for it
if !totalRewardAmount.IsZero() {
referrer, _ := referral.GetReferrer(types.PartyID(aggressor))
referrer, _ := referral.GetReferrer(types.PartyID(taker))
transfers = append(transfers, &types.Transfer{
Owner: aggressor,
Owner: taker,
Amount: &types.FinancialAmount{
Asset: e.asset,
Amount: totalRewardAmount.Clone(),
Expand All @@ -250,7 +255,7 @@ func (e *Engine) CalculateForContinuousMode(
}

return &feesTransfer{
totalFeesAmountsPerParty: map[string]*num.Uint{aggressor: totalFeeAmount, maker: num.UintZero()},
totalFeesAmountsPerParty: map[string]*num.Uint{taker: totalFeeAmount, maker: num.UintZero()},
transfers: append(transfers, transfersRecv...),
}, nil
}
Expand Down
83 changes: 83 additions & 0 deletions core/fee/rebate_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ import (
)

type FeesStats struct {
// TotalMakerFeesReceived is the total maker fees received by the maker side.
// maker -> amount
TotalMakerFeesReceived map[string]*num.Uint
// MakerFeesGenerated tracks maker fees paid by taker (aggressor) to the maker.
// taker -> maker -> amount
MakerFeesGenerated map[string]map[string]*num.Uint
TotalRewardsPaid map[string]*num.Uint
ReferrerRewardsGenerated map[string]map[string]*num.Uint
RefereeDiscountApplied map[string]*num.Uint
Expand All @@ -33,6 +39,8 @@ type FeesStats struct {

func NewFeesStats() *FeesStats {
return &FeesStats{
TotalMakerFeesReceived: map[string]*num.Uint{},
MakerFeesGenerated: map[string]map[string]*num.Uint{},
TotalRewardsPaid: map[string]*num.Uint{},
ReferrerRewardsGenerated: map[string]map[string]*num.Uint{},
RefereeDiscountApplied: map[string]*num.Uint{},
Expand Down Expand Up @@ -64,9 +72,46 @@ func NewFeesStatsFromProto(fsp *eventspb.FeesStats) *FeesStats {
fs.ReferrerRewardsGenerated[v.Referrer] = rg
}

for _, v := range fsp.TotalMakerFeesReceived {
fs.TotalMakerFeesReceived[v.Party] = num.MustUintFromString(v.Amount, 10)
}

for _, f := range fsp.MakerFeesGenerated {
rg := map[string]*num.Uint{}
for _, pa := range f.MakerFeesPaid {
rg[pa.Party] = num.MustUintFromString(pa.Amount, 10)
}

fs.MakerFeesGenerated[f.Taker] = rg
}

return fs
}

func (f *FeesStats) RegisterMakerFee(makerID, takerID string, amount *num.Uint) {
total, ok := f.TotalMakerFeesReceived[makerID]
if !ok {
total = num.NewUint(0)
f.TotalMakerFeesReceived[makerID] = total
}

total.Add(total, amount)

makerFeesGenerated, ok := f.MakerFeesGenerated[takerID]
if !ok {
makerFeesGenerated = map[string]*num.Uint{}
f.MakerFeesGenerated[takerID] = makerFeesGenerated
}

makerTally, ok := makerFeesGenerated[makerID]
if !ok {
makerTally = num.NewUint(0)
makerFeesGenerated[makerID] = makerTally
}

makerTally.Add(makerTally, amount)
}

func (f *FeesStats) RegisterReferrerReward(
referrer, referee string,
amount *num.Uint,
Expand Down Expand Up @@ -121,6 +166,8 @@ func (f *FeesStats) ToProto(asset string) *eventspb.FeesStats {
ReferrerRewardsGenerated: make([]*eventspb.ReferrerRewardsGenerated, 0, len(f.ReferrerRewardsGenerated)),
RefereesDiscountApplied: make([]*eventspb.PartyAmount, 0, len(f.RefereeDiscountApplied)),
VolumeDiscountApplied: make([]*eventspb.PartyAmount, 0, len(f.VolumeDiscountApplied)),
TotalMakerFeesReceived: make([]*eventspb.PartyAmount, 0, len(f.TotalMakerFeesReceived)),
MakerFeesGenerated: make([]*eventspb.MakerFeesGenerated, 0, len(f.MakerFeesGenerated)),
}

totalRewardsPaidParties := maps.Keys(f.TotalRewardsPaid)
Expand Down Expand Up @@ -179,5 +226,41 @@ func (f *FeesStats) ToProto(asset string) *eventspb.FeesStats {
fs.ReferrerRewardsGenerated = append(fs.ReferrerRewardsGenerated, rewardsGenerated)
}

totalMakerFeesReceivedParties := maps.Keys(f.TotalMakerFeesReceived)
sort.Strings(totalMakerFeesReceivedParties)
for _, maker := range totalMakerFeesReceivedParties {
amount := f.TotalMakerFeesReceived[maker]
fs.TotalMakerFeesReceived = append(fs.TotalMakerFeesReceived, &eventspb.PartyAmount{
Party: maker,
Amount: amount.String(),
})
}

makerFeesGeneratedParties := maps.Keys(f.MakerFeesGenerated)
sort.Strings(makerFeesGeneratedParties)
for _, taker := range makerFeesGeneratedParties {
makersAmounts := f.MakerFeesGenerated[taker]

rewardsGenerated := &eventspb.MakerFeesGenerated{
Taker: taker,
MakerFeesPaid: make([]*eventspb.PartyAmount, 0, len(makersAmounts)),
}

makersAmountsParties := maps.Keys(makersAmounts)
sort.Strings(makersAmountsParties)
for _, maker := range makersAmountsParties {
amount := makersAmounts[maker]
rewardsGenerated.MakerFeesPaid = append(
rewardsGenerated.MakerFeesPaid,
&eventspb.PartyAmount{
Party: maker,
Amount: amount.String(),
},
)
}

fs.MakerFeesGenerated = append(fs.MakerFeesGenerated, rewardsGenerated)
}

return fs
}
2 changes: 1 addition & 1 deletion datanode/api/trading_data_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -4450,7 +4450,7 @@ func (t *TradingDataServiceV2) GetFeesStats(ctx context.Context, req *v2.GetFees
assetID = ptr.From(entities.AssetID(*req.AssetId))
}

stats, err := t.feesStatsService.GetFeesStats(ctx, marketID, assetID, req.EpochSeq, req.Referrer, req.Referee)
stats, err := t.feesStatsService.GetFeesStats(ctx, marketID, assetID, req.EpochSeq, req.PartyId)
if err != nil {
return nil, formatE(ErrGetFeesStats, err)
}
Expand Down
49 changes: 49 additions & 0 deletions datanode/entities/fees_stats.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package entities

import (
"time"

eventspb "code.vegaprotocol.io/vega/protos/vega/events/v1"
)

type FeesStats struct {
MarketID MarketID
AssetID AssetID
EpochSeq uint64
TotalRewardsPaid []*eventspb.PartyAmount
ReferrerRewardsGenerated []*eventspb.ReferrerRewardsGenerated
RefereesDiscountApplied []*eventspb.PartyAmount
VolumeDiscountApplied []*eventspb.PartyAmount
TotalMakerFeesReceived []*eventspb.PartyAmount
MakerFeesGenerated []*eventspb.MakerFeesGenerated
VegaTime time.Time
}

func FeesStatsFromProto(proto *eventspb.FeesStats, vegaTime time.Time) *FeesStats {
return &FeesStats{
MarketID: MarketID(proto.Market),
AssetID: AssetID(proto.Asset),
EpochSeq: proto.EpochSeq,
TotalRewardsPaid: proto.TotalRewardsPaid,
ReferrerRewardsGenerated: proto.ReferrerRewardsGenerated,
RefereesDiscountApplied: proto.RefereesDiscountApplied,
VolumeDiscountApplied: proto.VolumeDiscountApplied,
TotalMakerFeesReceived: proto.TotalMakerFeesReceived,
MakerFeesGenerated: proto.MakerFeesGenerated,
VegaTime: vegaTime,
}
}

func (stats *FeesStats) ToProto() *eventspb.FeesStats {
return &eventspb.FeesStats{
Market: stats.MarketID.String(),
Asset: stats.AssetID.String(),
EpochSeq: stats.EpochSeq,
TotalRewardsPaid: stats.TotalRewardsPaid,
ReferrerRewardsGenerated: stats.ReferrerRewardsGenerated,
RefereesDiscountApplied: stats.RefereesDiscountApplied,
VolumeDiscountApplied: stats.VolumeDiscountApplied,
TotalMakerFeesReceived: stats.TotalMakerFeesReceived,
MakerFeesGenerated: stats.MakerFeesGenerated,
}
}
36 changes: 0 additions & 36 deletions datanode/entities/referral_set_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,6 @@ type (
SetID string
PartyID string
}

FeesStats struct {
MarketID MarketID
AssetID AssetID
EpochSeq uint64
TotalRewardsPaid []*eventspb.PartyAmount
ReferrerRewardsGenerated []*eventspb.ReferrerRewardsGenerated
RefereesDiscountApplied []*eventspb.PartyAmount
VolumeDiscountApplied []*eventspb.PartyAmount
VegaTime time.Time
}
)

func (s FlattenReferralSetStats) Cursor() *Cursor {
Expand Down Expand Up @@ -120,28 +109,3 @@ func ReferralSetStatsFromProto(proto *eventspb.ReferralSetStatsUpdated, vegaTime
RewardsFactorMultiplier: proto.RewardsFactorMultiplier,
}, nil
}

func FeesStatsFromProto(proto *eventspb.FeesStats, vegaTime time.Time) *FeesStats {
return &FeesStats{
MarketID: MarketID(proto.Market),
AssetID: AssetID(proto.Asset),
EpochSeq: proto.EpochSeq,
TotalRewardsPaid: proto.TotalRewardsPaid,
ReferrerRewardsGenerated: proto.ReferrerRewardsGenerated,
RefereesDiscountApplied: proto.RefereesDiscountApplied,
VolumeDiscountApplied: proto.VolumeDiscountApplied,
VegaTime: vegaTime,
}
}

func (stats *FeesStats) ToProto() *eventspb.FeesStats {
return &eventspb.FeesStats{
Market: stats.MarketID.String(),
Asset: stats.AssetID.String(),
EpochSeq: stats.EpochSeq,
TotalRewardsPaid: stats.TotalRewardsPaid,
ReferrerRewardsGenerated: stats.ReferrerRewardsGenerated,
RefereesDiscountApplied: stats.RefereesDiscountApplied,
VolumeDiscountApplied: stats.VolumeDiscountApplied,
}
}
4 changes: 4 additions & 0 deletions datanode/gateway/graphql/fees_stats_resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ func (r *feesStatsResolver) Epoch(_ context.Context, obj *eventspb.FeesStats) (i
return int(obj.EpochSeq), nil
}

func (r *feesStatsResolver) TotalMakeFeesReceived(_ context.Context, obj *eventspb.FeesStats) ([]*eventspb.PartyAmount, error) {
return obj.TotalMakerFeesReceived, nil
}
ValentinTrinque marked this conversation as resolved.
Show resolved Hide resolved

func (r *referrerRewardsGeneratedResolver) ReferrerID(_ context.Context, obj *eventspb.ReferrerRewardsGenerated) (string, error) {
return obj.Referrer, nil
}
Loading