Skip to content

Commit

Permalink
[R4R] sidechain staking reward distribution (#835)
Browse files Browse the repository at this point in the history
* sidechain staking reward distribution
  • Loading branch information
forcodedancing committed Mar 8, 2022
1 parent db72b99 commit 380a13c
Show file tree
Hide file tree
Showing 12 changed files with 124 additions and 55 deletions.
15 changes: 13 additions & 2 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ func NewBinanceChain(logger log.Logger, db dbm.DB, traceStore io.Writer, baseApp

app.stakeKeeper = stake.NewKeeper(
cdc,
common.StakeStoreKey, common.TStakeStoreKey,
common.StakeStoreKey, common.StakeRewardStoreKey, common.TStakeStoreKey,
app.CoinKeeper, app.Pool, app.ParamHub.Subspace(stake.DefaultParamspace),
app.RegisterCodespace(stake.DefaultCodespace),
)
Expand Down Expand Up @@ -241,6 +241,7 @@ func NewBinanceChain(logger log.Logger, db dbm.DB, traceStore io.Writer, baseApp
common.PairStoreKey,
common.ParamsStoreKey,
common.StakeStoreKey,
common.StakeRewardStoreKey,
common.SlashingStoreKey,
common.GovStoreKey,
common.TimeLockStoreKey,
Expand Down Expand Up @@ -326,12 +327,14 @@ func SetUpgradeConfig(upgradeConfig *config.UpgradeConfig) {
upgrade.Mgr.AddUpgradeHeight(upgrade.BEP84, upgradeConfig.BEP84Height)
upgrade.Mgr.AddUpgradeHeight(upgrade.BEP87, upgradeConfig.BEP87Height)
upgrade.Mgr.AddUpgradeHeight(upgrade.FixFailAckPackage, upgradeConfig.FixFailAckPackageHeight)
upgrade.Mgr.AddUpgradeHeight(upgrade.BEP128, upgradeConfig.BEP128Height)

// register store keys of upgrade
upgrade.Mgr.RegisterStoreKeys(upgrade.BEP9, common.TimeLockStoreKey.Name())
upgrade.Mgr.RegisterStoreKeys(upgrade.BEP3, common.AtomicSwapStoreKey.Name())
upgrade.Mgr.RegisterStoreKeys(upgrade.LaunchBscUpgrade, common.IbcStoreKey.Name(), common.SideChainStoreKey.Name(),
common.SlashingStoreKey.Name(), common.BridgeStoreKey.Name(), common.OracleStoreKey.Name())
upgrade.Mgr.RegisterStoreKeys(upgrade.BEP128, common.StakeRewardStoreKey.Name())

// register msg types of upgrade
upgrade.Mgr.RegisterMsgTypes(upgrade.BEP9,
Expand Down Expand Up @@ -525,6 +528,14 @@ func (app *BinanceChain) initStaking() {
LooseTokens: sdk.NewDec(5e15),
})
})
upgrade.Mgr.RegisterBeginBlocker(sdk.BEP128, func(ctx sdk.Context) {
storePrefix := app.scKeeper.GetSideChainStorePrefix(ctx, ServerContext.BscChainId)
// init new param RewardDistributionBatchSize
newCtx := ctx.WithSideChainKeyPrefix(storePrefix)
params := app.stakeKeeper.GetParams(newCtx)
params.RewardDistributionBatchSize = 1000
app.stakeKeeper.SetParams(newCtx, params)
})
app.stakeKeeper.SubscribeParamChange(app.ParamHub)
app.stakeKeeper = app.stakeKeeper.WithHooks(app.slashKeeper.Hooks())
}
Expand Down Expand Up @@ -823,7 +834,7 @@ func (app *BinanceChain) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) a
var validatorUpdates abci.ValidatorUpdates
if isBreatheBlock {
validatorUpdates, completedUbd = stake.EndBreatheBlock(ctx, app.stakeKeeper)
} else if ctx.RouterCallRecord()["stake"] {
} else if ctx.RouterCallRecord()["stake"] || sdk.IsUpgrade(upgrade.BEP128) {
validatorUpdates, completedUbd = stake.EndBlocker(ctx, app.stakeKeeper)
}
ibc.EndBlocker(ctx, app.ibcKeeper)
Expand Down
2 changes: 1 addition & 1 deletion app/app_paramhub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ var (
logger = log.NewTMLogger(os.Stdout)
genAccs, addrs, pubKeys, privKeys = mock.CreateGenAccounts(4,
sdk.Coins{sdk.NewCoin("BNB", 500000e8), sdk.NewCoin("BTC-000", 200e8)})
testScParams = `[{"type": "params/StakeParamSet","value": {"unbonding_time": "604800000000000","max_validators": 11,"bond_denom": "BNB","min_self_delegation": "5000000000000","min_delegation_change": "100000000"}},{"type": "params/SlashParamSet","value": {"max_evidence_age": "259200000000000","signed_blocks_window": "0","min_signed_per_window": "0","double_sign_unbond_duration": "9223372036854775807","downtime_unbond_duration": "172800000000000","too_low_del_unbond_duration": "86400000000000","slash_fraction_double_sign": "0","slash_fraction_downtime": "0","double_sign_slash_amount": "1000000000000","downtime_slash_amount": "5000000000","submitter_reward": "100000000000","downtime_slash_fee": "1000000000"}},{"type": "params/OracleParamSet","value": {"ConsensusNeeded": "70000000"}},{"type": "params/IbcParamSet","value": {"relayer_fee": "1000000"}}]`
testScParams = `[{"type": "params/StakeParamSet","value": {"unbonding_time": "604800000000000","max_validators": 11,"bond_denom": "BNB","min_self_delegation": "5000000000000","min_delegation_change": "100000000","reward_distribution_batch_size":"200"}},{"type": "params/SlashParamSet","value": {"max_evidence_age": "259200000000000","signed_blocks_window": "0","min_signed_per_window": "0","double_sign_unbond_duration": "9223372036854775807","downtime_unbond_duration": "172800000000000","too_low_del_unbond_duration": "86400000000000","slash_fraction_double_sign": "0","slash_fraction_downtime": "0","double_sign_slash_amount": "1000000000000","downtime_slash_amount": "5000000000","submitter_reward": "100000000000","downtime_slash_fee": "1000000000"}},{"type": "params/OracleParamSet","value": {"ConsensusNeeded": "70000000"}},{"type": "params/IbcParamSet","value": {"relayer_fee": "1000000"}}]`
testClient *TestClient
testApp *BinanceChain
)
Expand Down
7 changes: 5 additions & 2 deletions app/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ BEP87Height = {{ .UpgradeConfig.BEP87Height }}
FixFailAckPackageHeight = {{ .UpgradeConfig.FixFailAckPackageHeight }}
# Block height of EnableAccountScriptsForCrossChainTransferHeight upgrade
EnableAccountScriptsForCrossChainTransferHeight = {{ .UpgradeConfig.EnableAccountScriptsForCrossChainTransferHeight }}
# Block height of BEP128 upgrade
BEP128Height = {{ .UpgradeConfig.BEP128Height }}
[query]
# ABCI query interface black list, suggested value: ["custom/gov/proposals", "custom/timelock/timelocks", "custom/atomicSwap/swapcreator", "custom/atomicSwap/swaprecipient"]
Expand Down Expand Up @@ -512,10 +514,9 @@ type UpgradeConfig struct {
LotSizeUpgradeHeight int64 `mapstructure:"LotSizeUpgradeHeight"`
ListingRuleUpgradeHeight int64 `mapstructure:"ListingRuleUpgradeHeight"`
FixZeroBalanceHeight int64 `mapstructure:"FixZeroBalanceHeight"`
// TODO: add upgrade name

LaunchBscUpgradeHeight int64 `mapstructure:"LaunchBscUpgradeHeight"`

// TODO: add upgrade name
BEP8Height int64 `mapstructure:"BEP8Height"`
BEP67Height int64 `mapstructure:"BEP67Height"`
BEP70Height int64 `mapstructure:"BEP70Height"`
Expand All @@ -525,6 +526,7 @@ type UpgradeConfig struct {
BEP87Height int64 `mapstructure:"BEP87Height"`
FixFailAckPackageHeight int64 `mapstructure:"FixFailAckPackageHeight"`
EnableAccountScriptsForCrossChainTransferHeight int64 `mapstructure:"EnableAccountScriptsForCrossChainTransferHeight"`
BEP128Height int64 `mapstructure:"BEP128Height"`
}

func defaultUpgradeConfig() *UpgradeConfig {
Expand All @@ -544,6 +546,7 @@ func defaultUpgradeConfig() *UpgradeConfig {
BEP67Height: 1,
BEP70Height: 1,
LaunchBscUpgradeHeight: 1,
BEP128Height: math.MaxInt64,
BEP82Height: math.MaxInt64,
BEP84Height: math.MaxInt64,
BEP87Height: math.MaxInt64,
Expand Down
4 changes: 3 additions & 1 deletion app/pub/msgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ var latestSchemaVersions = map[msgType]int{
transferTpe: 1,
blockTpe: 0,
stakingTpe: 0,
distributionTpe: 0,
distributionTpe: 1,
slashingTpe: 0,
crossTransferTpe: 0,
mirrorTpe: 0,
Expand Down Expand Up @@ -1026,6 +1026,7 @@ func (msg *Distribution) toNativeMap() map[string]interface{} {
}

type Reward struct {
Validator sdk.ValAddress
Delegator sdk.AccAddress
Tokens int64
Amount int64
Expand All @@ -1037,6 +1038,7 @@ func (msg *Reward) String() string {

func (msg *Reward) toNativeMap() map[string]interface{} {
var native = make(map[string]interface{})
native["validator"] = msg.Validator.String()
native["delegator"] = msg.Delegator.String()
native["delegationTokens"] = msg.Tokens
native["reward"] = msg.Amount
Expand Down
22 changes: 12 additions & 10 deletions app/pub/publisher.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,29 +276,31 @@ func PublishEvent(
for i, disData := range disData {
rewards := make([]*Reward, len(disData.Rewards), len(disData.Rewards))
for i, reward := range disData.Rewards {
delegatorTokens, err := sdk.MulQuoDec(disData.ValTokens, reward.Shares, disData.ValShares)
if err != nil {
Logger.Error("error convert shares to tokens, delegator: %s", reward.AccAddr)
continue
}
rewardMsg := &Reward{
Validator: reward.ValAddr,
Delegator: reward.AccAddr,
Amount: reward.Amount,
Tokens: delegatorTokens.RawInt(),
Tokens: reward.Tokens.RawInt(),
}
rewards[i] = rewardMsg
}
var valTokens, totalReward, commission int64
if disData.Validator != nil {
valTokens = disData.ValTokens.RawInt()
totalReward = disData.TotalReward.RawInt()
commission = disData.Commission.RawInt()
}
dis[i] = &Distribution{
Validator: disData.Validator,
SelfDelegator: disData.SelfDelegator,
DistributeAddr: disData.DistributeAddr,
ValTokens: disData.ValTokens.RawInt(),
TotalReward: disData.TotalReward.RawInt(),
Commission: disData.Commission.RawInt(),
ValTokens: valTokens,
TotalReward: totalReward,
Commission: commission,
Rewards: rewards,
}
msgNum += len(disData.Rewards)
}
msgNum++
distributions[chainId] = dis
}
}
Expand Down
1 change: 1 addition & 0 deletions app/pub/schemas.go
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,7 @@ const (
"name": "Reward",
"namespace": "org.binance.dex.model.avro",
"fields":[
{"name": "validator", "type": "string"},
{"name": "delegator", "type": "string"},
{"name": "delegationTokens", "type": "long"},
{"name": "reward", "type": "long"}
Expand Down
43 changes: 43 additions & 0 deletions app/pub/schemas/distribution0.avsc
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"type": "record",
"name": "Distribution",
"namespace": "org.binance.dex.model.avro",
"fields": [
{ "name": "height", "type": "long" },
{ "name": "timestamp", "type": "long" },
{ "name": "numOfMsgs", "type": "int" },
{ "name": "distributions", "type": {
"type": "map",
"values": {
"type": "array",
"items": {
"type": "record",
"name": "DistributionData",
"namespace": "org.binance.dex.model.avro",
"fields": [
{"name": "validator", "type": "string"},
{"name": "selfDelegator","type": "string"},
{"name": "distributeAddr","type": "string"},
{"name": "valTokens", "type": "long"},
{"name": "totalReward", "type": "long"},
{"name": "commission", "type": "long"},
{"name": "rewards", "type":{
"type": "array",
"items": {
"type": "record",
"name": "Reward",
"namespace": "org.binance.dex.model.avro",
"fields":[
{"name": "delegator", "type": "string"},
{"name": "delegationTokens", "type": "long"},
{"name": "reward", "type": "long"}
]
}
}}
]
}
}
}
}
]
}
68 changes: 36 additions & 32 deletions common/stores.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,47 @@ package common
import sdk "github.com/cosmos/cosmos-sdk/types"

const (
MainStoreName = "main"
AccountStoreName = "acc"
ValAddrStoreName = "val"
TokenStoreName = "tokens"
DexStoreName = "dex"
PairStoreName = "pairs"
StakeStoreName = "stake"
SlashingStoreName = "slashing"
ParamsStoreName = "params"
GovStoreName = "gov"
TimeLockStoreName = "time_lock"
AtomicSwapStoreName = "atomic_swap"
BridgeStoreName = "bridge"
OracleStoreName = "oracle"
IbcStoreName = "ibc"
SideChainStoreName = "sc"
MainStoreName = "main"
AccountStoreName = "acc"
ValAddrStoreName = "val"
TokenStoreName = "tokens"
DexStoreName = "dex"
PairStoreName = "pairs"
StakeStoreName = "stake"
StakeRewardStoreName = "stake_reward"
SlashingStoreName = "slashing"
ParamsStoreName = "params"
GovStoreName = "gov"
TimeLockStoreName = "time_lock"
AtomicSwapStoreName = "atomic_swap"
BridgeStoreName = "bridge"
OracleStoreName = "oracle"
IbcStoreName = "ibc"
SideChainStoreName = "sc"

StakeTransientStoreName = "transient_stake"
ParamsTransientStoreName = "transient_params"
)

var (
// keys to access the substores
MainStoreKey = sdk.NewKVStoreKey(MainStoreName)
AccountStoreKey = sdk.NewKVStoreKey(AccountStoreName)
ValAddrStoreKey = sdk.NewKVStoreKey(ValAddrStoreName)
TokenStoreKey = sdk.NewKVStoreKey(TokenStoreName)
DexStoreKey = sdk.NewKVStoreKey(DexStoreName)
PairStoreKey = sdk.NewKVStoreKey(PairStoreName)
StakeStoreKey = sdk.NewKVStoreKey(StakeStoreName)
SlashingStoreKey = sdk.NewKVStoreKey(SlashingStoreName)
ParamsStoreKey = sdk.NewKVStoreKey(ParamsStoreName)
GovStoreKey = sdk.NewKVStoreKey(GovStoreName)
TimeLockStoreKey = sdk.NewKVStoreKey(TimeLockStoreName)
AtomicSwapStoreKey = sdk.NewKVStoreKey(AtomicSwapStoreName)
BridgeStoreKey = sdk.NewKVStoreKey(BridgeStoreName)
OracleStoreKey = sdk.NewKVStoreKey(OracleStoreName)
IbcStoreKey = sdk.NewKVStoreKey(IbcStoreName)
SideChainStoreKey = sdk.NewKVStoreKey(SideChainStoreName)
MainStoreKey = sdk.NewKVStoreKey(MainStoreName)
AccountStoreKey = sdk.NewKVStoreKey(AccountStoreName)
ValAddrStoreKey = sdk.NewKVStoreKey(ValAddrStoreName)
TokenStoreKey = sdk.NewKVStoreKey(TokenStoreName)
DexStoreKey = sdk.NewKVStoreKey(DexStoreName)
PairStoreKey = sdk.NewKVStoreKey(PairStoreName)
StakeStoreKey = sdk.NewKVStoreKey(StakeStoreName)
StakeRewardStoreKey = sdk.NewKVStoreKey(StakeRewardStoreName)
SlashingStoreKey = sdk.NewKVStoreKey(SlashingStoreName)
ParamsStoreKey = sdk.NewKVStoreKey(ParamsStoreName)
GovStoreKey = sdk.NewKVStoreKey(GovStoreName)
TimeLockStoreKey = sdk.NewKVStoreKey(TimeLockStoreName)
AtomicSwapStoreKey = sdk.NewKVStoreKey(AtomicSwapStoreName)
BridgeStoreKey = sdk.NewKVStoreKey(BridgeStoreName)
OracleStoreKey = sdk.NewKVStoreKey(OracleStoreName)
IbcStoreKey = sdk.NewKVStoreKey(IbcStoreName)
SideChainStoreKey = sdk.NewKVStoreKey(SideChainStoreName)

TStakeStoreKey = sdk.NewTransientStoreKey(StakeTransientStoreName)
TParamsStoreKey = sdk.NewTransientStoreKey(ParamsTransientStoreName)
Expand All @@ -54,6 +56,7 @@ var (
DexStoreName: DexStoreKey,
PairStoreName: PairStoreKey,
StakeStoreName: StakeStoreKey,
StakeRewardStoreName: StakeRewardStoreKey,
SlashingStoreName: SlashingStoreKey,
ParamsStoreName: ParamsStoreKey,
GovStoreName: GovStoreKey,
Expand All @@ -75,6 +78,7 @@ var (
DexStoreName,
PairStoreName,
StakeStoreName,
StakeRewardStoreName,
SlashingStoreName,
ParamsStoreName,
GovStoreName,
Expand Down
7 changes: 4 additions & 3 deletions common/upgrade/upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,21 @@ const (
ListingRuleUpgrade = "ListingRuleUpgrade" // Remove restriction that only the owner of base asset can list trading pair
FixZeroBalance = "FixZeroBalance"

// TODO: add upgrade name
LaunchBscUpgrade = sdk.LaunchBscUpgrade

EnableAccountScriptsForCrossChainTransfer = "EnableAccountScriptsForCrossChainTransfer"

//Nightingale upgrade
BEP8 = sdk.BEP8 // https://github.com/binance-chain/BEPs/pull/69 Mini token upgrade
BEP67 = "BEP67" // https://github.com/binance-chain/BEPs/pull/67 Expiry time upgrade
BEP70 = "BEP70" // https://github.com/binance-chain/BEPs/pull/70 BUSD Pair Upgrade
BEP70 = "BEP70" // https://github.com/binance-chain/BEPs/pull/70 BUSD pair upgrade

BEP82 = sdk.BEP82 // https://github.com/binance-chain/BEPs/pull/82
BEP84 = "BEP84" // https://github.com/binance-chain/BEPs/pull/84 Mirror Sync Upgrade
BEP84 = "BEP84" // https://github.com/binance-chain/BEPs/pull/84 Mirror sync upgrade
BEP87 = "BEP87" // https://github.com/binance-chain/BEPs/pull/87
FixFailAckPackage = sdk.FixFailAckPackage

BEP128 = sdk.BEP128 // https://github.com/binance-chain/BEPs/pull/128 Staking reward distribution upgrade
)

func UpgradeBEP10(before func(), after func()) {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ require (
)

replace (
github.com/cosmos/cosmos-sdk => github.com/binance-chain/bnc-cosmos-sdk v0.25.0-binance.25
github.com/cosmos/cosmos-sdk => github.com/binance-chain/bnc-cosmos-sdk v0.25.0-binance.26
github.com/tendermint/go-amino => github.com/binance-chain/bnc-go-amino v0.14.1-binance.2
github.com/tendermint/iavl => github.com/binance-chain/bnc-tendermint-iavl v0.12.0-binance.4
github.com/tendermint/tendermint => github.com/binance-chain/bnc-tendermint v0.32.3-binance.6
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/binance-chain/bnc-cosmos-sdk v0.25.0-binance.25 h1:CFb+ATfmOy7wrt8GMwBCVnImOYWXrYGXXuxsgoLD13Q=
github.com/binance-chain/bnc-cosmos-sdk v0.25.0-binance.25/go.mod h1:MX4eWWUtVhyAd9vzzT56PaK4s1jBl7kPhWLwEI0x2EA=
github.com/binance-chain/bnc-cosmos-sdk v0.25.0-binance.26 h1:DYdUOU89ZaY4CUWpbcD5s9KVC7EipNPxV5zYsH5ys/w=
github.com/binance-chain/bnc-cosmos-sdk v0.25.0-binance.26/go.mod h1:MX4eWWUtVhyAd9vzzT56PaK4s1jBl7kPhWLwEI0x2EA=
github.com/binance-chain/bnc-go-amino v0.14.1-binance.2 h1:XcbcfisVItk92UKoGbtNT8nbcfadj3H3ayuM2srAfVs=
github.com/binance-chain/bnc-go-amino v0.14.1-binance.2/go.mod h1:yaElUUxWtv/TC/ldGtlKAvS1vKwokxgJ1d97I+6is80=
github.com/binance-chain/bnc-tendermint v0.32.3-binance.6 h1:3Xt3IaH5zAGssK0ZxyGz5dQ7plxWdUCdtT4z7kS2M3U=
Expand Down
4 changes: 3 additions & 1 deletion plugins/dex/list/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func MakeKeepers(cdc *codec.Codec) (ms sdkStore.CommitMultiStore, dexKeeper *ord
paramKey := sdk.NewKVStoreKey("param")
paramTKey := sdk.NewTransientStoreKey("t_param")
stakeKey := sdk.NewKVStoreKey("stake")
stakeRewardKey := sdk.NewKVStoreKey("stake_reward")
stakeTKey := sdk.NewTransientStoreKey("t_stake")
govKey := sdk.NewKVStoreKey("gov")

Expand All @@ -58,6 +59,7 @@ func MakeKeepers(cdc *codec.Codec) (ms sdkStore.CommitMultiStore, dexKeeper *ord
ms.MountStoreWithDB(tokenKey, sdk.StoreTypeIAVL, memDB)
ms.MountStoreWithDB(paramKey, sdk.StoreTypeIAVL, memDB)
ms.MountStoreWithDB(stakeKey, sdk.StoreTypeIAVL, memDB)
ms.MountStoreWithDB(stakeRewardKey, sdk.StoreTypeIAVL, memDB)
ms.MountStoreWithDB(govKey, sdk.StoreTypeIAVL, memDB)
ms.LoadLatestVersion()

Expand All @@ -72,7 +74,7 @@ func MakeKeepers(cdc *codec.Codec) (ms sdkStore.CommitMultiStore, dexKeeper *ord
bankKeeper := bank.NewBaseKeeper(accKeeper)
stakeKeeper := stake.NewKeeper(
cdc,
stakeKey, stakeTKey,
stakeKey, stakeRewardKey, stakeTKey,
bankKeeper, nil, paramsKeeper.Subspace(stake.DefaultParamspace),
stake.DefaultCodespace,
)
Expand Down

0 comments on commit 380a13c

Please sign in to comment.