Skip to content

Commit

Permalink
Use the baseapp CommitMultiStore for historical queries in the yield …
Browse files Browse the repository at this point in the history
…calculation
  • Loading branch information
LeCodeurDuDimanche committed Oct 5, 2021
1 parent c746803 commit ab75278
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 13 deletions.
11 changes: 11 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"strings"

"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/cosmos/cosmos-sdk/store"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
"github.com/gorilla/mux"
"github.com/rakyll/statik/fs"
"github.com/spf13/cast"
Expand Down Expand Up @@ -260,6 +262,9 @@ type WasmApp struct {

// simulation manager
sm *module.SimulationManager

// Commit multistore for history
cms storetypes.CommitMultiStore
}

// NewWasmApp returns a reference to an initialized WasmApp.
Expand All @@ -276,6 +281,10 @@ func NewWasmApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b
bApp.SetAppVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)

//TODO : this is temporary and used for yield calculation
cms := store.NewCommitMultiStore(db)
bApp.SetCMS(cms)

keys := sdk.NewKVStoreKeys(
authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey,
minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey,
Expand All @@ -295,6 +304,7 @@ func NewWasmApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b
keys: keys,
tkeys: tkeys,
memKeys: memKeys,
cms: cms,
}

app.paramsKeeper = initParamsKeeper(appCodec, legacyAmino, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey])
Expand Down Expand Up @@ -418,6 +428,7 @@ func NewWasmApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b
app.distrKeeper,
app.stakingKeeper,
app.getSubspace(starname.ModuleName),
cms,
)

// The gov proposal types can be individually enabled
Expand Down
36 changes: 26 additions & 10 deletions x/starname/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,19 @@ type Keeper struct {
Cdc codec.Marshaler
paramspace ParamSubspace
// crud stores
accountStore crud.Store
domainStore crud.Store
accountStore crud.Store
domainStore crud.Store
//TODO: find a way to persist this
feesSum sdk.Coins
feesSumCount uint64
lastComputedHeight uint64
// TODO: this should maybe moved out of this keeper
// Used for block fees queries
cms sdk.CommitMultiStore
}

// NewKeeper creates a domain keeper
func NewKeeper(cdc codec.Marshaler, storeKey sdk.StoreKey, configKeeper ConfigurationKeeper, supply SupplyKeeper, auth AuthKeeper, distrib DistributionKeeper, staking StakingKeeper, paramspace ParamSubspace) Keeper {
func NewKeeper(cdc codec.Marshaler, storeKey sdk.StoreKey, configKeeper ConfigurationKeeper, supply SupplyKeeper, auth AuthKeeper, distrib DistributionKeeper, staking StakingKeeper, paramspace ParamSubspace, cms sdk.CommitMultiStore) Keeper {
keeper := Keeper{
StoreKey: storeKey,
Cdc: cdc,
Expand All @@ -93,6 +97,7 @@ func NewKeeper(cdc codec.Marshaler, storeKey sdk.StoreKey, configKeeper Configur
DistributionKeeper: distrib,
StakingKeeper: staking,
paramspace: paramspace,
cms: cms,
}
return keeper
}
Expand All @@ -112,16 +117,25 @@ func (k Keeper) DomainStore(ctx sdk.Context) crud.Store {
// GetBlockFeesSum retrieves the current value for the sum of the last n blocks
func (k Keeper) GetBlockFeesSum(ctx sdk.Context) (sdk.Coins, uint64) {
// TODO: this shouldn't be an hardcoded value
const MaxBlocksInSum = 100000
const MaxBlocksInSum = 50000

//TODO: should we offset this to take into account that fee collectors funds are transferred on block start ?
currentHeight := ctx.BlockHeight()

//fmt.Printf("Begin block fees sum before %v until %v\n", k.lastComputedHeight, currentHeight)

// if lastComputedHeight is too far behind we discard the current sliding sum and reset it
if k.lastComputedHeight+MaxBlocksInSum < uint64(currentHeight) {
k.lastComputedHeight = uint64(currentHeight) - MaxBlocksInSum
k.feesSum = sdk.Coins{}
k.feesSumCount = 0
}

// If we need to, we update the value of the sliding sum
// lastComputedHeight is initialized at 0 (first block)
for ; k.lastComputedHeight < uint64(currentHeight); k.lastComputedHeight++ {

// We store the new value in the sliding sum
fees, err := k.GetBlockFees(ctx, uint64(currentHeight))
fees, err := k.GetBlockFees(ctx, uint64(k.lastComputedHeight))
if err != nil {
panic(fmt.Sprintf("Cannot retrieve fees for the block at height %v", currentHeight))
}
Expand All @@ -143,14 +157,16 @@ func (k Keeper) GetBlockFeesSum(ctx sdk.Context) (sdk.Coins, uint64) {
}

func (k Keeper) GetBlockFees(ctx sdk.Context, height uint64) (sdk.Coins, error) {
cms, err := ctx.MultiStore().CacheMultiStoreWithVersion(int64(height))

cms, err := k.cms.CacheMultiStoreWithVersion(int64(height))
if err != nil {
return nil, err
}
ctxWithPrevHeight := ctx.WithMultiStore(cms)
ctxWithCurrentHeight := ctx.WithMultiStore(cms)

fees := k.SupplyKeeper.GetAllBalances(ctxWithCurrentHeight, k.AuthKeeper.GetModuleAddress(authtypes.FeeCollectorName))

blockFees := k.SupplyKeeper.GetAllBalances(ctxWithPrevHeight, k.AuthKeeper.GetModuleAddress(authtypes.FeeCollectorName))
return blockFees, nil
return fees, nil
}

// Logger returns aliceAddr module-specific logger.
Expand Down
13 changes: 11 additions & 2 deletions x/starname/keeper/querier.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,23 +343,32 @@ func calculateYield(ctx sdk.Context, keeper *Keeper, validatorCommission sdk.Dec
MulDec(sdk.OneDec().Sub(communityTax)).
MulDec(sdk.OneDec().Sub(validatorCommission))

//fmt.Printf("reward pool is " + rewardPool.String() + "\n")

totalDelegatedTokens := keeper.StakingKeeper.GetLastTotalPower(ctx)

//fmt.Printf("total delegated tokens is " + totalDelegatedTokens.String() + "\n")

// TODO: use a non hardcoded parameter instead
// Voting power is returned in tokens while fees in the sub-unit (iov vs uiov)
totalDelegatedTokens = totalDelegatedTokens.Mul(sdk.NewInt(1000000))
yieldForPeriod := rewardPool.QuoDec(sdk.NewDecFromInt(totalDelegatedTokens))

//fmt.Printf("yield for period " + yieldForPeriod.String() + "\n")

var apy sdk.Dec
if len(yieldForPeriod) == 0 {
apy = sdk.ZeroDec()
} else {
const SecondsPerYear = 365 * 24 * 3600
numBlocksPerYear := SecondsPerYear / EstimatedBlockTime

//fmt.Printf("num blocks %v, per year %v, multiplier %v\n", numBlocks, numBlocksPerYear, uint64(numBlocksPerYear)/numBlocks)

// TODO: manage multiple tokens for fees
apy = yieldForPeriod.
QuoDec(sdk.NewDec(int64(numBlocks))).
MulDec(sdk.NewDec(int64(numBlocksPerYear)))[0].Amount
MulDec(sdk.NewDec(int64(numBlocksPerYear))).
QuoDec(sdk.NewDec(int64(numBlocks)))[0].Amount
}

// Give it a nice percentage format
Expand Down
2 changes: 1 addition & 1 deletion x/starname/keeper/test_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func NewTestKeeper(t testing.TB, isCheckTx bool) (Keeper, sdk.Context, *Mocks) {
accountKeeper,
distributionKeeper,
stakingKeeper,
nil), ctx, &mocks
nil, nil), ctx, &mocks
}

var _, testAddrs = utils.GeneratePrivKeyAddressPairs(3)
Expand Down

0 comments on commit ab75278

Please sign in to comment.