Skip to content

Commit ad85ea8

Browse files
committed
review code
1 parent 4615c67 commit ad85ea8

File tree

14 files changed

+354
-136
lines changed

14 files changed

+354
-136
lines changed

init.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#!/bin/bash
22

3+
set -euo pipefail
4+
IFS=$'\n\t'
35
# Set environment variables
46
KEY="dev0"
57
CHAINID="hetu_560000-1"

x/blockinflation/keeper/alpha_token.go

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"fmt"
66
"math/big"
7+
"strings"
78
"sync"
89

910
sdk "github.com/cosmos/cosmos-sdk/types"
@@ -37,16 +38,17 @@ func (k Keeper) MintAlphaTokens(ctx sdk.Context, netuid uint16, recipient string
3738
return fmt.Errorf("subnet not found: %d", netuid)
3839
}
3940

40-
// 2. Check if the subnet has an AlphaToken address in its params
41+
// 2. Resolve and validate the subnet's AlphaToken address
4142
alphaTokenAddress, ok := subnet.Params["alpha_token"]
42-
if !ok || alphaTokenAddress == "" {
43-
return fmt.Errorf("subnet has no alpha token address in params: %d", netuid)
43+
alphaTokenAddress = strings.TrimSpace(alphaTokenAddress)
44+
if !ok || alphaTokenAddress == "" || !common.IsHexAddress(alphaTokenAddress) {
45+
return fmt.Errorf("invalid or missing alpha token address in subnet params: %d", netuid)
4446
}
4547

46-
// 3. Parse the AlphaToken address
48+
// 3. Parse and validate the AlphaToken address
4749
alphaTokenAddr := common.HexToAddress(alphaTokenAddress)
48-
if (alphaTokenAddr == common.Address{}) {
49-
return fmt.Errorf("invalid alpha token address: %s", alphaTokenAddress)
50+
if alphaTokenAddr == (common.Address{}) {
51+
return fmt.Errorf("alpha token address cannot be the zero address: %s", alphaTokenAddress)
5052
}
5153

5254
// 4. Get the AlphaToken ABI (cached)
@@ -55,11 +57,15 @@ func (k Keeper) MintAlphaTokens(ctx sdk.Context, netuid uint16, recipient string
5557
return fmt.Errorf("failed to load AlphaToken ABI: %w", err)
5658
}
5759

58-
// 5. Convert recipient address to Ethereum address
59-
recipientAddr := common.HexToAddress(recipient)
60-
if (recipientAddr == common.Address{}) {
60+
// 5. Validate and convert recipient address
61+
recipient = strings.TrimSpace(recipient)
62+
if !common.IsHexAddress(recipient) {
6163
return fmt.Errorf("invalid recipient address: %s", recipient)
6264
}
65+
recipientAddr := common.HexToAddress(recipient)
66+
if recipientAddr == (common.Address{}) {
67+
return fmt.Errorf("recipient address cannot be the zero address: %s", recipient)
68+
}
6369

6470
// 6. Convert amount to big.Int
6571
amountBig := new(big.Int).SetUint64(amount)

x/blockinflation/keeper/genesis.go

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,26 @@
11
package keeper
22

33
import (
4+
"fmt"
5+
46
"github.com/cosmos/cosmos-sdk/codec"
57
sdk "github.com/cosmos/cosmos-sdk/types"
68
blockinflationtypes "github.com/hetu-project/hetu/v1/x/blockinflation/types"
79
)
810

911
// InitGenesis initializes the blockinflation module's state from a provided genesis state.
1012
func (k Keeper) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data *blockinflationtypes.GenesisState) {
13+
if data == nil {
14+
panic("blockinflation: nil genesis state")
15+
}
16+
17+
// Validate parameters
18+
if data.Params.MintDenom == "" {
19+
panic("blockinflation: params.mint_denom must not be empty")
20+
}
21+
// TODO: If Params exposes a Validate() or ValidateBasic(), call it here.
22+
// if err := data.Params.Validate(); err != nil { panic(fmt.Errorf("invalid blockinflation params: %w", err)) }
23+
1124
// Set parameters
1225
k.SetParams(ctx, data.Params)
1326

@@ -19,19 +32,40 @@ func (k Keeper) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data *blockinf
1932
k.Logger(ctx).Debug("InitGenesis: retrieved params", "params", params)
2033

2134
// Set total issuance
22-
if !data.TotalIssuance.Amount.IsNil() {
23-
k.SetTotalIssuance(ctx, data.TotalIssuance)
35+
if err := sdk.ValidateDenom(data.TotalIssuance.Denom); err != nil {
36+
panic(fmt.Errorf("blockinflation: invalid total_issuance denom: %w", err))
37+
}
38+
if data.TotalIssuance.Amount.IsNegative() {
39+
panic("blockinflation: total_issuance amount must be >= 0")
2440
}
41+
if data.TotalIssuance.Denom != data.Params.MintDenom {
42+
panic(fmt.Errorf("blockinflation: total_issuance denom %q must match params.mint_denom %q", data.TotalIssuance.Denom, data.Params.MintDenom))
43+
}
44+
k.SetTotalIssuance(ctx, data.TotalIssuance)
2545

2646
// Set total burned
27-
if !data.TotalBurned.Amount.IsNil() {
28-
k.SetTotalBurned(ctx, data.TotalBurned)
47+
if err := sdk.ValidateDenom(data.TotalBurned.Denom); err != nil {
48+
panic(fmt.Errorf("blockinflation: invalid total_burned denom: %w", err))
49+
}
50+
if data.TotalBurned.Amount.IsNegative() {
51+
panic("blockinflation: total_burned amount must be >= 0")
52+
}
53+
if data.TotalBurned.Denom != data.Params.MintDenom {
54+
panic(fmt.Errorf("blockinflation: total_burned denom %q must match params.mint_denom %q", data.TotalBurned.Denom, data.Params.MintDenom))
2955
}
56+
k.SetTotalBurned(ctx, data.TotalBurned)
3057

3158
// Set pending subnet rewards
32-
if !data.PendingSubnetRewards.Amount.IsNil() {
33-
k.SetPendingSubnetRewards(ctx, data.PendingSubnetRewards)
59+
if err := sdk.ValidateDenom(data.PendingSubnetRewards.Denom); err != nil {
60+
panic(fmt.Errorf("blockinflation: invalid pending_subnet_rewards denom: %w", err))
61+
}
62+
if data.PendingSubnetRewards.Amount.IsNegative() {
63+
panic("blockinflation: pending_subnet_rewards amount must be >= 0")
64+
}
65+
if data.PendingSubnetRewards.Denom != data.Params.MintDenom {
66+
panic(fmt.Errorf("blockinflation: pending_subnet_rewards denom %q must match params.mint_denom %q", data.PendingSubnetRewards.Denom, data.Params.MintDenom))
3467
}
68+
k.SetPendingSubnetRewards(ctx, data.PendingSubnetRewards)
3569

3670
k.Logger(ctx).Info("blockinflation: initialized genesis state",
3771
"total_issuance", data.TotalIssuance.String(),

x/blockinflation/keeper/inflation.go

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -50,14 +50,12 @@ func (k Keeper) CalculateBlockEmission(ctx sdk.Context) (math.Int, error) {
5050
flooredLog := stdmath.Floor(logResult)
5151
flooredLogInt := int64(flooredLog)
5252

53-
// Calculate 2^flooredLog
54-
multiplier := stdmath.Pow(2.0, float64(flooredLogInt))
55-
56-
// Calculate block emission percentage: 1 / multiplier
57-
blockEmissionPercentage := math.LegacyOneDec().Quo(math.LegacyNewDecWithPrec(int64(multiplier*1000), 3))
58-
59-
// Calculate actual block emission using high-precision arithmetic
60-
blockEmission := defaultBlockEmissionDec.Mul(blockEmissionPercentage)
53+
// Calculate actual block emission by halving default emission flooredLogInt times.
54+
// This avoids float math and overflow.
55+
blockEmission := defaultBlockEmissionDec
56+
for i := int64(0); i < flooredLogInt; i++ {
57+
blockEmission = blockEmission.Quo(math.LegacyNewDec(2))
58+
}
6159

6260
// Convert back to math.Int with proper rounding
6361
blockEmissionInt := blockEmission.TruncateInt()
@@ -69,8 +67,6 @@ func (k Keeper) CalculateBlockEmission(ctx sdk.Context) (math.Int, error) {
6967
"log_arg", logArg.String(),
7068
"log_result", fmt.Sprintf("%.6f", logResult),
7169
"floored_log", flooredLogInt,
72-
"multiplier", fmt.Sprintf("%.6f", multiplier),
73-
"emission_percentage", blockEmissionPercentage.String(),
7470
"block_emission", blockEmissionInt.String(),
7571
)
7672

@@ -159,7 +155,10 @@ func (k Keeper) MintAndAllocateBlockInflation(ctx sdk.Context) error {
159155

160156
// Update total issuance
161157
currentIssuance := k.GetTotalIssuance(ctx)
162-
newIssuance := currentIssuance.Add(mintedCoin)
158+
if currentIssuance.Denom != mintedCoin.Denom {
159+
return fmt.Errorf("denom mismatch: totalIssuance=%s minted=%s", currentIssuance.Denom, mintedCoin.Denom)
160+
}
161+
newIssuance := sdk.NewCoin(currentIssuance.Denom, currentIssuance.Amount.Add(mintedCoin.Amount))
163162
k.SetTotalIssuance(ctx, newIssuance)
164163

165164
k.Logger(ctx).Info("minted and allocated block inflation",

x/blockinflation/types/expected_keepers.go

Lines changed: 4 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ package types
44
import (
55
"context"
66

7-
"cosmossdk.io/math"
87
sdk "github.com/cosmos/cosmos-sdk/types"
98
"github.com/ethereum/go-ethereum/accounts/abi"
109
"github.com/ethereum/go-ethereum/common"
@@ -14,13 +13,8 @@ import (
1413
)
1514

1615
// SubnetInfo defines the expected subnet info structure
17-
type SubnetInfo struct {
18-
Netuid uint16
19-
Owner string
20-
AlphaToken string
21-
EMAPriceHalvingBlocks uint64
22-
Params map[string]string
23-
}
16+
// Deprecated: Use eventtypes.SubnetInfo directly
17+
type SubnetInfo = eventtypes.SubnetInfo
2418

2519
// AccountKeeper defines the expected interface needed to retrieve account info.
2620
type AccountKeeper interface {
@@ -38,39 +32,8 @@ type BankKeeper interface {
3832
}
3933

4034
// EventKeeper defines the expected interface for the event module keeper
41-
type EventKeeper interface {
42-
GetAllSubnetNetuids(ctx sdk.Context) []uint16
43-
GetSubnetsToEmitTo(ctx sdk.Context) []uint16
44-
GetSubnetFirstEmissionBlock(ctx sdk.Context, netuid uint16) (uint64, bool)
45-
GetSubnet(ctx sdk.Context, netuid uint16) (eventtypes.Subnet, bool)
46-
GetAlphaPrice(ctx sdk.Context, netuid uint16) math.LegacyDec
47-
GetMovingAlphaPrice(ctx sdk.Context, netuid uint16) math.LegacyDec
48-
UpdateMovingPrice(ctx sdk.Context, netuid uint16, movingAlpha math.LegacyDec, halvingBlocks uint64)
49-
GetSubnetAlphaIn(ctx sdk.Context, netuid uint16) math.Int
50-
GetSubnetAlphaOut(ctx sdk.Context, netuid uint16) math.Int
51-
GetSubnetTAO(ctx sdk.Context, netuid uint16) math.Int
52-
GetSubnetAlphaInEmission(ctx sdk.Context, netuid uint16) math.Int
53-
GetSubnetAlphaOutEmission(ctx sdk.Context, netuid uint16) math.Int
54-
GetSubnetTaoInEmission(ctx sdk.Context, netuid uint16) math.Int
55-
AddSubnetAlphaIn(ctx sdk.Context, netuid uint16, amount math.Int)
56-
AddSubnetAlphaOut(ctx sdk.Context, netuid uint16, amount math.Int)
57-
AddSubnetTAO(ctx sdk.Context, netuid uint16, amount math.Int)
58-
AddSubnetAlphaInEmission(ctx sdk.Context, netuid uint16, amount math.Int)
59-
AddSubnetAlphaOutEmission(ctx sdk.Context, netuid uint16, amount math.Int)
60-
AddSubnetTaoInEmission(ctx sdk.Context, netuid uint16, amount math.Int)
61-
SetSubnetAlphaOut(ctx sdk.Context, netuid uint16, amount math.Int)
62-
GetPendingEmission(ctx sdk.Context, netuid uint16) math.Int
63-
SetPendingEmission(ctx sdk.Context, netuid uint16, amount math.Int)
64-
AddPendingEmission(ctx sdk.Context, netuid uint16, amount math.Int)
65-
GetPendingOwnerCut(ctx sdk.Context, netuid uint16) math.Int
66-
SetPendingOwnerCut(ctx sdk.Context, netuid uint16, amount math.Int)
67-
AddPendingOwnerCut(ctx sdk.Context, netuid uint16, amount math.Int)
68-
GetBlocksSinceLastStep(ctx sdk.Context, netuid uint16) uint64
69-
SetBlocksSinceLastStep(ctx sdk.Context, netuid uint16, blocks uint64)
70-
GetLastMechanismStepBlock(ctx sdk.Context, netuid uint16) int64
71-
SetLastMechanismStepBlock(ctx sdk.Context, netuid uint16, block int64)
72-
GetAllValidatorStakesByNetuid(ctx sdk.Context, netuid uint16) []eventtypes.ValidatorStake
73-
}
35+
// Deprecated: Use eventtypes.EventKeeper directly
36+
type EventKeeper = eventtypes.EventKeeper
7437

7538
// StakeworkKeeper defines the expected interface for the stakework module keeper
7639
type StakeworkKeeper interface {

x/blockinflation/types/genesis.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package types
22

33
import (
4+
"fmt"
5+
46
"cosmossdk.io/math"
57
sdk "github.com/cosmos/cosmos-sdk/types"
68
)
@@ -19,11 +21,13 @@ type GenesisState struct {
1921

2022
// DefaultGenesisState returns default genesis state
2123
func DefaultGenesisState() *GenesisState {
24+
p := DefaultParams()
25+
denom := p.MintDenom
2226
return &GenesisState{
23-
Params: DefaultParams(),
24-
TotalIssuance: sdk.NewCoin("ahetu", math.ZeroInt()),
25-
TotalBurned: sdk.NewCoin("ahetu", math.ZeroInt()),
26-
PendingSubnetRewards: sdk.NewCoin("ahetu", math.ZeroInt()),
27+
Params: p,
28+
TotalIssuance: sdk.NewCoin(denom, math.ZeroInt()),
29+
TotalBurned: sdk.NewCoin(denom, math.ZeroInt()),
30+
PendingSubnetRewards: sdk.NewCoin(denom, math.ZeroInt()),
2731
}
2832
}
2933

@@ -48,5 +52,16 @@ func (gs GenesisState) Validate() error {
4852
return err
4953
}
5054

55+
// Ensure all coins use the configured mint denom
56+
if gs.TotalIssuance.Denom != gs.Params.MintDenom {
57+
return fmt.Errorf("total_issuance denom %q must match params.mint_denom %q", gs.TotalIssuance.Denom, gs.Params.MintDenom)
58+
}
59+
if gs.TotalBurned.Denom != gs.Params.MintDenom {
60+
return fmt.Errorf("total_burned denom %q must match params.mint_denom %q", gs.TotalBurned.Denom, gs.Params.MintDenom)
61+
}
62+
if gs.PendingSubnetRewards.Denom != gs.Params.MintDenom {
63+
return fmt.Errorf("pending_subnet_rewards denom %q must match params.mint_denom %q", gs.PendingSubnetRewards.Denom, gs.Params.MintDenom)
64+
}
65+
5166
return nil
5267
}

x/blockinflation/types/subnet_reward.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package types
22

33
import (
44
stdmath "math"
5+
"strconv"
56

67
"cosmossdk.io/math"
78
)
@@ -13,9 +14,14 @@ func CalculateSubnetRewardRatio(params Params, subnetCount uint64) math.LegacyDe
1314
return math.LegacyZeroDec()
1415
}
1516

16-
// Calculate log(1 + subnet_count) and convert to LegacyDec
17-
logFloat := stdmath.Log(float64(1 + subnetCount))
18-
logValue := math.LegacyNewDecFromInt(math.NewInt(int64(logFloat * 1000000))).Quo(math.LegacyNewDec(1000000))
17+
// Calculate log(1 + subnet_count) with better numerical stability and convert to LegacyDec
18+
logFloat := stdmath.Log1p(float64(subnetCount))
19+
logStr := strconv.FormatFloat(logFloat, 'f', 18, 64) // 18 fractional digits to match LegacyDec precision
20+
logValue, err := math.LegacyNewDecFromStr(logStr)
21+
if err != nil {
22+
// Fallback to a less precise but safe conversion if string parsing fails
23+
logValue = math.LegacyNewDecWithPrec(int64(logFloat*1000000000000000000), 18)
24+
}
1925

2026
// Calculate base + k * log(1 + subnet_count)
2127
ratio := params.SubnetRewardBase.Add(params.SubnetRewardK.Mul(logValue))

x/event/keeper/keeper.go

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -422,49 +422,49 @@ func (k Keeper) handleNetworkRegistered(ctx sdk.Context, log ethTypes.Log) {
422422

423423
// Override Core network parameters (if event has values)
424424
if event.Hyperparams.Rho != 0 {
425-
params["rho"] = strconv.FormatFloat(float64(event.Hyperparams.Rho)/10000.0, 'f', -1, 64)
425+
params[types.KeyRho] = strconv.FormatFloat(float64(event.Hyperparams.Rho)/10000.0, 'f', -1, 64)
426426
}
427427
if event.Hyperparams.Kappa != 0 {
428-
params["kappa"] = fmt.Sprintf("%d", event.Hyperparams.Kappa)
428+
params[types.KeyKappa] = fmt.Sprintf("%d", event.Hyperparams.Kappa)
429429
}
430430
if event.Hyperparams.ImmunityPeriod != 0 {
431-
params["immunity_period"] = fmt.Sprintf("%d", event.Hyperparams.ImmunityPeriod)
431+
params[types.KeyImmunityPeriod] = fmt.Sprintf("%d", event.Hyperparams.ImmunityPeriod)
432432
}
433433
if event.Hyperparams.Tempo != 0 {
434-
params["tempo"] = fmt.Sprintf("%d", event.Hyperparams.Tempo)
434+
params[types.KeyTempo] = fmt.Sprintf("%d", event.Hyperparams.Tempo)
435435
}
436436
if event.Hyperparams.MaxValidators != 0 {
437-
params["max_validators"] = fmt.Sprintf("%d", event.Hyperparams.MaxValidators)
437+
params[types.KeyMaxValidators] = fmt.Sprintf("%d", event.Hyperparams.MaxValidators)
438438
}
439439
if event.Hyperparams.ActivityCutoff != 0 {
440-
params["activity_cutoff"] = fmt.Sprintf("%d", event.Hyperparams.ActivityCutoff)
440+
params[types.KeyActivityCutoff] = fmt.Sprintf("%d", event.Hyperparams.ActivityCutoff)
441441
}
442442
if event.Hyperparams.MaxAllowedUids != 0 {
443-
params["max_allowed_uids"] = fmt.Sprintf("%d", event.Hyperparams.MaxAllowedUids)
443+
params[types.KeyMaxAllowedUids] = fmt.Sprintf("%d", event.Hyperparams.MaxAllowedUids)
444444
}
445445
if event.Hyperparams.MaxAllowedValidators != 0 {
446-
params["max_allowed_validators"] = fmt.Sprintf("%d", event.Hyperparams.MaxAllowedValidators)
446+
params[types.KeyMaxAllowedValidators] = fmt.Sprintf("%d", event.Hyperparams.MaxAllowedValidators)
447447
}
448448
if event.Hyperparams.MinAllowedWeights != 0 {
449-
params["min_allowed_weights"] = fmt.Sprintf("%d", event.Hyperparams.MinAllowedWeights)
449+
params[types.KeyMinAllowedWeights] = fmt.Sprintf("%d", event.Hyperparams.MinAllowedWeights)
450450
}
451451
if event.Hyperparams.MaxWeightsLimit != 0 {
452-
params["max_weights_limit"] = fmt.Sprintf("%d", event.Hyperparams.MaxWeightsLimit)
452+
params[types.KeyMaxWeightsLimit] = fmt.Sprintf("%d", event.Hyperparams.MaxWeightsLimit)
453453
}
454454

455455
// Directly add Economic & Governance parameters
456-
params["base_neuron_cost"] = event.Hyperparams.BaseNeuronCost.String()
457-
params["current_difficulty"] = fmt.Sprintf("%d", event.Hyperparams.CurrentDifficulty)
458-
params["target_regs_per_interval"] = fmt.Sprintf("%d", event.Hyperparams.TargetRegsPerInterval)
459-
params["max_regs_per_block"] = fmt.Sprintf("%d", event.Hyperparams.MaxRegsPerBlock)
460-
params["weights_rate_limit"] = fmt.Sprintf("%d", event.Hyperparams.WeightsRateLimit)
461-
params["weights_set_rate_limit"] = fmt.Sprintf("%d", event.Hyperparams.WeightsRateLimit) // Compatible with stakework
462-
params["registration_allowed"] = fmt.Sprintf("%t", event.Hyperparams.RegistrationAllowed)
463-
params["commit_reveal_enabled"] = fmt.Sprintf("%t", event.Hyperparams.CommitRevealEnabled)
464-
params["commit_reveal_period"] = fmt.Sprintf("%d", event.Hyperparams.CommitRevealPeriod)
465-
params["serving_rate_limit"] = fmt.Sprintf("%d", event.Hyperparams.ServingRateLimit)
466-
params["validator_threshold"] = event.Hyperparams.ValidatorThreshold.String()
467-
params["neuron_threshold"] = event.Hyperparams.NeuronThreshold.String()
456+
params[types.KeyBaseNeuronCost] = event.Hyperparams.BaseNeuronCost.String()
457+
params[types.KeyCurrentDifficulty] = fmt.Sprintf("%d", event.Hyperparams.CurrentDifficulty)
458+
params[types.KeyTargetRegsPerInterval] = fmt.Sprintf("%d", event.Hyperparams.TargetRegsPerInterval)
459+
params[types.KeyMaxRegsPerBlock] = fmt.Sprintf("%d", event.Hyperparams.MaxRegsPerBlock)
460+
params[types.KeyWeightsRateLimit] = fmt.Sprintf("%d", event.Hyperparams.WeightsRateLimit)
461+
params[types.KeyWeightsSetRateLimit] = fmt.Sprintf("%d", event.Hyperparams.WeightsRateLimit) // Compatible with stakework
462+
params[types.KeyRegistrationAllowed] = fmt.Sprintf("%t", event.Hyperparams.RegistrationAllowed)
463+
params[types.KeyCommitRevealEnabled] = fmt.Sprintf("%t", event.Hyperparams.CommitRevealEnabled)
464+
params[types.KeyCommitRevealPeriod] = fmt.Sprintf("%d", event.Hyperparams.CommitRevealPeriod)
465+
params[types.KeyServingRateLimit] = fmt.Sprintf("%d", event.Hyperparams.ServingRateLimit)
466+
params[types.KeyValidatorThreshold] = event.Hyperparams.ValidatorThreshold.String()
467+
params[types.KeyNeuronThreshold] = event.Hyperparams.NeuronThreshold.String()
468468

469469
// Create subnet structure
470470
subnet := types.Subnet{

0 commit comments

Comments
 (0)