replace sdk.Context with context.Context

refactor to add inputs via depinject
This commit is contained in:
Roy Crihfield 2024-10-27 00:03:31 +08:00
parent ce67b678ce
commit f85ec5ca1f
22 changed files with 303 additions and 340 deletions

View File

@ -115,18 +115,32 @@ func (tf *TestFixture) Setup(t *testing.T) error {
authority.String(),
)
auctionKeeper := auctionkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[auctionTypes.StoreKey]), accountKeeper, bankKeeper, authority.String())
auctionKeeper := auctionkeeper.NewKeeper(
runtime.NewEnvironment(runtime.NewKVStoreService(keys[auctionTypes.StoreKey]), logger),
cdc,
accountKeeper,
bankKeeper,
authority.String(),
logger,
)
bondKeeper := bondkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[bondTypes.StoreKey]), accountKeeper, bankKeeper, authority.String())
bondKeeper := bondkeeper.NewKeeper(
cdc,
runtime.NewKVStoreService(keys[bondTypes.StoreKey]),
accountKeeper,
bankKeeper,
authority.String(),
)
registryKeeper := registrykeeper.NewKeeper(
runtime.NewEnvironment(runtime.NewKVStoreService(keys[registryTypes.StoreKey]), logger),
cdc,
runtime.NewKVStoreService(keys[registryTypes.StoreKey]),
accountKeeper,
bankKeeper,
bondKeeper,
auctionKeeper,
authority.String(),
logger,
)
authModule := auth.NewAppModule(cdc, accountKeeper, accountsModKeeper, authsims.RandomGenesisAccounts, nil)
@ -151,7 +165,7 @@ func (tf *TestFixture) Setup(t *testing.T) error {
},
router, queryRouter)
sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context())
ctx := integrationApp.Context()
// Register MsgServer and QueryServer
auctionTypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), auctionkeeper.NewMsgServerImpl(auctionKeeper))
@ -164,18 +178,18 @@ func (tf *TestFixture) Setup(t *testing.T) error {
registryTypes.RegisterQueryServer(integrationApp.QueryHelper(), registrykeeper.NewQueryServerImpl(registryKeeper))
// set default params
if err := auctionKeeper.Params.Set(sdkCtx, auctionTypes.DefaultParams()); err != nil {
if err := auctionKeeper.Params.Set(ctx, auctionTypes.DefaultParams()); err != nil {
return err
}
if err := bondKeeper.Params.Set(sdkCtx, bondTypes.DefaultParams()); err != nil {
if err := bondKeeper.Params.Set(ctx, bondTypes.DefaultParams()); err != nil {
return err
}
if err := registryKeeper.Params.Set(sdkCtx, registryTypes.DefaultParams()); err != nil {
if err := registryKeeper.Params.Set(ctx, registryTypes.DefaultParams()); err != nil {
return err
}
tf.App = integrationApp
tf.SdkCtx, tf.cdc, tf.keys = sdkCtx, cdc, keys
tf.SdkCtx, tf.cdc, tf.keys = sdk.UnwrapSDKContext(ctx), cdc, keys
tf.AccountKeeper, tf.BankKeeper = accountKeeper, bankKeeper
tf.AuctionKeeper, tf.BondKeeper, tf.RegistryKeeper = auctionKeeper, bondKeeper, registryKeeper

View File

@ -1,16 +1,14 @@
package auction
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
import "context"
// AuctionUsageKeeper keep track of auction usage in other modules.
// Used to, for example, prevent deletion of a auction that's in use.
type AuctionUsageKeeper interface {
ModuleName() string
UsesAuction(ctx sdk.Context, auctionId string) bool
UsesAuction(ctx context.Context, auctionId string) bool
OnAuctionWinnerSelected(ctx sdk.Context, auctionId string)
OnAuctionWinnerSelected(ctx context.Context, auctionId string, currentHeight uint64)
}
// AuctionHooksWrapper is a wrapper for modules to inject AuctionUsageKeeper using depinject.

View File

@ -11,7 +11,7 @@ import (
"cosmossdk.io/collections"
"cosmossdk.io/collections/indexes"
storetypes "cosmossdk.io/core/store"
"cosmossdk.io/core/appmodule"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
"cosmossdk.io/math"
@ -67,8 +67,10 @@ func newBidsIndexes(sb *collections.SchemaBuilder) BidsIndexes {
}
type Keeper struct {
// Codecs
cdc codec.BinaryCodec
appmodule.Environment
cdc codec.BinaryCodec
logger log.Logger
// addressCodec address.Codec //TODO
authority string
@ -92,20 +94,23 @@ type Keeper struct {
// NewKeeper creates a new Keeper instance
func NewKeeper(
env appmodule.Environment,
cdc codec.BinaryCodec,
storeService storetypes.KVStoreService,
accountKeeper auth.AccountKeeper,
bankKeeper bank.Keeper,
authority string,
logger log.Logger,
) *Keeper {
// ensure that authority is a valid AccAddress
if _, err := accountKeeper.AddressCodec().StringToBytes(authority); err != nil {
panic("authority is not a valid acc address")
}
sb := collections.NewSchemaBuilder(storeService)
sb := collections.NewSchemaBuilder(env.KVStoreService)
k := Keeper{
Environment: env,
cdc: cdc,
logger: logger.With(log.ModuleKey, "x/"+auctiontypes.ModuleName),
authority: authority,
accountKeeper: accountKeeper,
bankKeeper: bankKeeper,
@ -132,15 +137,6 @@ func NewKeeper(
return &k
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return logger(ctx)
}
func logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", auctiontypes.ModuleName)
}
func (k *Keeper) SetUsageKeepers(usageKeepers []auctiontypes.AuctionUsageKeeper) {
if k.usageKeepers != nil {
panic("cannot set auction hooks twice")
@ -150,12 +146,12 @@ func (k *Keeper) SetUsageKeepers(usageKeepers []auctiontypes.AuctionUsageKeeper)
}
// SaveAuction - saves a auction to the store.
func (k Keeper) SaveAuction(ctx sdk.Context, auction *auctiontypes.Auction) error {
func (k Keeper) SaveAuction(ctx context.Context, auction *auctiontypes.Auction) error {
return k.Auctions.Set(ctx, auction.Id, *auction)
}
// DeleteAuction - deletes the auction.
func (k Keeper) DeleteAuction(ctx sdk.Context, auction auctiontypes.Auction) error {
func (k Keeper) DeleteAuction(ctx context.Context, auction auctiontypes.Auction) error {
// Delete all bids first.
bids, err := k.GetBids(ctx, auction.Id)
if err != nil {
@ -171,7 +167,7 @@ func (k Keeper) DeleteAuction(ctx sdk.Context, auction auctiontypes.Auction) err
return k.Auctions.Remove(ctx, auction.Id)
}
func (k Keeper) HasAuction(ctx sdk.Context, id string) (bool, error) {
func (k Keeper) HasAuction(ctx context.Context, id string) (bool, error) {
has, err := k.Auctions.Has(ctx, id)
if err != nil {
return false, err
@ -180,17 +176,17 @@ func (k Keeper) HasAuction(ctx sdk.Context, id string) (bool, error) {
return has, nil
}
func (k Keeper) SaveBid(ctx sdk.Context, bid *auctiontypes.Bid) error {
func (k Keeper) SaveBid(ctx context.Context, bid *auctiontypes.Bid) error {
key := collections.Join(bid.AuctionId, bid.BidderAddress)
return k.Bids.Set(ctx, key, *bid)
}
func (k Keeper) DeleteBid(ctx sdk.Context, bid auctiontypes.Bid) error {
func (k Keeper) DeleteBid(ctx context.Context, bid auctiontypes.Bid) error {
key := collections.Join(bid.AuctionId, bid.BidderAddress)
return k.Bids.Remove(ctx, key)
}
func (k Keeper) HasBid(ctx sdk.Context, id string, bidder string) (bool, error) {
func (k Keeper) HasBid(ctx context.Context, id string, bidder string) (bool, error) {
key := collections.Join(id, bidder)
has, err := k.Bids.Has(ctx, key)
if err != nil {
@ -200,7 +196,7 @@ func (k Keeper) HasBid(ctx sdk.Context, id string, bidder string) (bool, error)
return has, nil
}
func (k Keeper) GetBid(ctx sdk.Context, id string, bidder string) (auctiontypes.Bid, error) {
func (k Keeper) GetBid(ctx context.Context, id string, bidder string) (auctiontypes.Bid, error) {
key := collections.Join(id, bidder)
bid, err := k.Bids.Get(ctx, key)
if err != nil {
@ -211,7 +207,7 @@ func (k Keeper) GetBid(ctx sdk.Context, id string, bidder string) (auctiontypes.
}
// GetBids gets the auction bids.
func (k Keeper) GetBids(ctx sdk.Context, id string) ([]*auctiontypes.Bid, error) {
func (k Keeper) GetBids(ctx context.Context, id string) ([]*auctiontypes.Bid, error) {
var bids []*auctiontypes.Bid
err := k.Bids.Walk(ctx,
@ -242,7 +238,7 @@ func (k Keeper) ListAuctions(ctx context.Context) ([]auctiontypes.Auction, error
}
// MatchAuctions - get all matching auctions.
func (k Keeper) MatchAuctions(ctx sdk.Context, matchFn func(*auctiontypes.Auction) (bool, error)) ([]*auctiontypes.Auction, error) {
func (k Keeper) MatchAuctions(ctx context.Context, matchFn func(*auctiontypes.Auction) (bool, error)) ([]*auctiontypes.Auction, error) {
var auctions []*auctiontypes.Auction
err := k.Auctions.Walk(ctx, nil, func(key string, value auctiontypes.Auction) (bool, error) {
@ -265,7 +261,7 @@ func (k Keeper) MatchAuctions(ctx sdk.Context, matchFn func(*auctiontypes.Auctio
}
// GetAuction - gets a record from the store.
func (k Keeper) GetAuctionById(ctx sdk.Context, id string) (auctiontypes.Auction, error) {
func (k Keeper) GetAuctionById(ctx context.Context, id string) (auctiontypes.Auction, error) {
auction, err := k.Auctions.Get(ctx, id)
if err != nil {
if errors.Is(err, collections.ErrNotFound) {
@ -277,7 +273,7 @@ func (k Keeper) GetAuctionById(ctx sdk.Context, id string) (auctiontypes.Auction
return auction, nil
}
func (k Keeper) GetAuctionsByOwner(ctx sdk.Context, owner string) ([]auctiontypes.Auction, error) {
func (k Keeper) GetAuctionsByOwner(ctx context.Context, owner string) ([]auctiontypes.Auction, error) {
iter, err := k.Auctions.Indexes.Owner.MatchExact(ctx, owner)
if err != nil {
return nil, err
@ -287,7 +283,7 @@ func (k Keeper) GetAuctionsByOwner(ctx sdk.Context, owner string) ([]auctiontype
}
// QueryAuctionsByBidder - query auctions by bidder
func (k Keeper) QueryAuctionsByBidder(ctx sdk.Context, bidderAddress string) ([]auctiontypes.Auction, error) {
func (k Keeper) QueryAuctionsByBidder(ctx context.Context, bidderAddress string) ([]auctiontypes.Auction, error) {
auctions := []auctiontypes.Auction{}
iter, err := k.Bids.Indexes.Bidder.MatchExact(ctx, bidderAddress)
@ -313,7 +309,7 @@ func (k Keeper) QueryAuctionsByBidder(ctx sdk.Context, bidderAddress string) ([]
}
// CreateAuction creates a new auction.
func (k Keeper) CreateAuction(ctx sdk.Context, msg auctiontypes.MsgCreateAuction) (*auctiontypes.Auction, error) {
func (k Keeper) CreateAuction(ctx context.Context, msg auctiontypes.MsgCreateAuction) (*auctiontypes.Auction, error) {
// Might be called from another module directly, always validate.
err := msg.ValidateBasic()
if err != nil {
@ -338,7 +334,7 @@ func (k Keeper) CreateAuction(ctx sdk.Context, msg auctiontypes.MsgCreateAuction
}.Generate()
// Compute timestamps.
now := ctx.BlockTime()
now := k.HeaderService.HeaderInfo(ctx).Time
commitsEndTime := now.Add(msg.CommitsDuration)
revealsEndTime := now.Add(msg.CommitsDuration + msg.RevealsDuration)
@ -374,7 +370,7 @@ func (k Keeper) CreateAuction(ctx sdk.Context, msg auctiontypes.MsgCreateAuction
return &auction, nil
}
func (k Keeper) CommitBid(ctx sdk.Context, msg auctiontypes.MsgCommitBid) (*auctiontypes.Bid, error) {
func (k Keeper) CommitBid(ctx context.Context, msg auctiontypes.MsgCommitBid) (*auctiontypes.Bid, error) {
if has, err := k.HasAuction(ctx, msg.AuctionId); !has {
if err != nil {
return nil, err
@ -429,7 +425,7 @@ func (k Keeper) CommitBid(ctx sdk.Context, msg auctiontypes.MsgCommitBid) (*auct
BidderAddress: msg.Signer,
Status: auctiontypes.BidStatusCommitted,
CommitHash: msg.CommitHash,
CommitTime: ctx.BlockTime(),
CommitTime: k.HeaderService.HeaderInfo(ctx).Time,
CommitFee: auction.CommitFee,
RevealFee: auction.RevealFee,
}
@ -441,7 +437,7 @@ func (k Keeper) CommitBid(ctx sdk.Context, msg auctiontypes.MsgCommitBid) (*auct
return &bid, nil
}
func (k Keeper) RevealBid(ctx sdk.Context, msg auctiontypes.MsgRevealBid) (*auctiontypes.Auction, error) {
func (k Keeper) RevealBid(ctx context.Context, msg auctiontypes.MsgRevealBid) (*auctiontypes.Auction, error) {
if has, err := k.HasAuction(ctx, msg.AuctionId); !has {
if err != nil {
return nil, err
@ -502,8 +498,9 @@ func (k Keeper) RevealBid(ctx sdk.Context, msg auctiontypes.MsgRevealBid) (*auct
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Reveal JSON unmarshal error.")
}
headerInfo := k.HeaderService.HeaderInfo(ctx)
chainId, err := utils.GetAttributeAsString(reveal, "chainId")
if err != nil || chainId != ctx.ChainID() {
if err != nil || chainId != headerInfo.ChainID {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid reveal chainID.")
}
@ -549,7 +546,7 @@ func (k Keeper) RevealBid(ctx sdk.Context, msg auctiontypes.MsgRevealBid) (*auct
// Update bid.
bid.BidAmount = bidAmount
bid.RevealTime = ctx.BlockTime()
bid.RevealTime = headerInfo.Time
bid.Status = auctiontypes.BidStatusRevealed
if err = k.SaveBid(ctx, &bid); err != nil {
return nil, err
@ -564,7 +561,7 @@ func (k Keeper) GetAuthority() string {
}
// GetParams gets the auction module's parameters.
func (k Keeper) GetParams(ctx sdk.Context) (*auctiontypes.Params, error) {
func (k Keeper) GetParams(ctx context.Context) (*auctiontypes.Params, error) {
params, err := k.Params.Get(ctx)
if err != nil {
return nil, err
@ -574,19 +571,19 @@ func (k Keeper) GetParams(ctx sdk.Context) (*auctiontypes.Params, error) {
}
// SetParams sets the x/auction module parameters.
func (k Keeper) SetParams(ctx sdk.Context, params auctiontypes.Params) error {
func (k Keeper) SetParams(ctx context.Context, params auctiontypes.Params) error {
return k.Params.Set(ctx, params)
}
// GetAuctionModuleBalances gets the auction module account(s) balances.
func (k Keeper) GetAuctionModuleBalances(ctx sdk.Context) sdk.Coins {
func (k Keeper) GetAuctionModuleBalances(ctx context.Context) sdk.Coins {
moduleAddress := k.accountKeeper.GetModuleAddress(auctiontypes.ModuleName)
balances := k.bankKeeper.GetAllBalances(ctx, moduleAddress)
return balances
}
func (k Keeper) EndBlockerProcessAuctions(ctx sdk.Context) error {
func (k Keeper) EndBlockerProcessAuctions(ctx context.Context) error {
// Transition auction state (commit, reveal, expired, completed).
if err := k.processAuctionPhases(ctx); err != nil {
return err
@ -596,7 +593,7 @@ func (k Keeper) EndBlockerProcessAuctions(ctx sdk.Context) error {
return k.deleteCompletedAuctions(ctx)
}
func (k Keeper) processAuctionPhases(ctx sdk.Context) error {
func (k Keeper) processAuctionPhases(ctx context.Context) error {
auctions, err := k.MatchAuctions(ctx, func(_ *auctiontypes.Auction) (bool, error) {
return true, nil
})
@ -604,25 +601,26 @@ func (k Keeper) processAuctionPhases(ctx sdk.Context) error {
return err
}
now := k.HeaderService.HeaderInfo(ctx).Time
for _, auction := range auctions {
// Commit -> Reveal state.
if auction.Status == auctiontypes.AuctionStatusCommitPhase && ctx.BlockTime().After(auction.CommitsEndTime) {
if auction.Status == auctiontypes.AuctionStatusCommitPhase && now.After(auction.CommitsEndTime) {
auction.Status = auctiontypes.AuctionStatusRevealPhase
if err = k.SaveAuction(ctx, auction); err != nil {
return err
}
k.Logger(ctx).Info(fmt.Sprintf("Moved auction %s to reveal phase.", auction.Id))
k.logger.Info(fmt.Sprintf("Moved auction %s to reveal phase.", auction.Id))
}
// Reveal -> Expired state.
if auction.Status == auctiontypes.AuctionStatusRevealPhase && ctx.BlockTime().After(auction.RevealsEndTime) {
if auction.Status == auctiontypes.AuctionStatusRevealPhase && now.After(auction.RevealsEndTime) {
auction.Status = auctiontypes.AuctionStatusExpired
if err = k.SaveAuction(ctx, auction); err != nil {
return err
}
k.Logger(ctx).Info(fmt.Sprintf("Moved auction %s to expired state.", auction.Id))
k.logger.Info(fmt.Sprintf("Moved auction %s to expired state.", auction.Id))
}
// If auction has expired, pick a winner from revealed bids.
@ -643,17 +641,17 @@ func (k Keeper) processAuctionPhases(ctx sdk.Context) error {
}
// Delete completed stale auctions.
func (k Keeper) deleteCompletedAuctions(ctx sdk.Context) error {
func (k Keeper) deleteCompletedAuctions(ctx context.Context) error {
auctions, err := k.MatchAuctions(ctx, func(auction *auctiontypes.Auction) (bool, error) {
deleteTime := auction.RevealsEndTime.Add(CompletedAuctionDeleteTimeout)
return auction.Status == auctiontypes.AuctionStatusCompleted && ctx.BlockTime().After(deleteTime), nil
return auction.Status == auctiontypes.AuctionStatusCompleted && k.HeaderService.HeaderInfo(ctx).Time.After(deleteTime), nil
})
if err != nil {
return err
}
for _, auction := range auctions {
k.Logger(ctx).Info(fmt.Sprintf("Deleting completed auction %s after timeout.", auction.Id))
k.logger.Info(fmt.Sprintf("Deleting completed auction %s after timeout.", auction.Id))
if err := k.DeleteAuction(ctx, *auction); err != nil {
return err
}
@ -663,8 +661,8 @@ func (k Keeper) deleteCompletedAuctions(ctx sdk.Context) error {
}
// Pick winner for vickrey auction
func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction) error {
k.Logger(ctx).Info(fmt.Sprintf("Picking auction %s winner.", auction.Id))
func (k Keeper) pickAuctionWinner(ctx context.Context, auction *auctiontypes.Auction) error {
k.logger.Info(fmt.Sprintf("Picking auction %s winner.", auction.Id))
var highestBid *auctiontypes.Bid
var secondHighestBid *auctiontypes.Bid
@ -675,38 +673,38 @@ func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction
}
for _, bid := range bids {
k.Logger(ctx).Info(fmt.Sprintf("Processing bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Processing bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
// Only consider revealed bids.
if bid.Status != auctiontypes.BidStatusRevealed {
k.Logger(ctx).Info(fmt.Sprintf("Ignoring unrevealed bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Ignoring unrevealed bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
continue
}
// Init highest bid.
if highestBid == nil {
highestBid = bid
k.Logger(ctx).Info(fmt.Sprintf("Initializing 1st bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Initializing 1st bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
continue
}
//nolint: all
if highestBid.BidAmount.IsLT(bid.BidAmount) {
k.Logger(ctx).Info(fmt.Sprintf("New highest bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("New highest bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
secondHighestBid = highestBid
highestBid = bid
k.Logger(ctx).Info(fmt.Sprintf("Updated 1st bid %s %s", highestBid.BidderAddress, highestBid.BidAmount.String()))
k.Logger(ctx).Info(fmt.Sprintf("Updated 2nd bid %s %s", secondHighestBid.BidderAddress, secondHighestBid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Updated 1st bid %s %s", highestBid.BidderAddress, highestBid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Updated 2nd bid %s %s", secondHighestBid.BidderAddress, secondHighestBid.BidAmount.String()))
} else if secondHighestBid == nil || secondHighestBid.BidAmount.IsLT(bid.BidAmount) {
k.Logger(ctx).Info(fmt.Sprintf("New 2nd highest bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("New 2nd highest bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
secondHighestBid = bid
k.Logger(ctx).Info(fmt.Sprintf("Updated 2nd bid %s %s", secondHighestBid.BidderAddress, secondHighestBid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Updated 2nd bid %s %s", secondHighestBid.BidderAddress, secondHighestBid.BidAmount.String()))
} else {
k.Logger(ctx).Info(fmt.Sprintf("Ignoring bid as it doesn't affect 1st/2nd price %s %s", bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Ignoring bid as it doesn't affect 1st/2nd price %s %s", bid.BidderAddress, bid.BidAmount.String()))
}
}
@ -722,11 +720,11 @@ func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction
if secondHighestBid != nil {
auction.WinningPrice = secondHighestBid.BidAmount
}
k.Logger(ctx).Info(fmt.Sprintf("Auction %s winner %s.", auction.Id, auction.WinnerAddresses[0]))
k.Logger(ctx).Info(fmt.Sprintf("Auction %s winner bid %s.", auction.Id, auction.WinningBids[0].String()))
k.Logger(ctx).Info(fmt.Sprintf("Auction %s winning price %s.", auction.Id, auction.WinningPrice.String()))
k.logger.Info(fmt.Sprintf("Auction %s winner %s.", auction.Id, auction.WinnerAddresses[0]))
k.logger.Info(fmt.Sprintf("Auction %s winner bid %s.", auction.Id, auction.WinningBids[0].String()))
k.logger.Info(fmt.Sprintf("Auction %s winning price %s.", auction.Id, auction.WinningPrice.String()))
} else {
k.Logger(ctx).Info(fmt.Sprintf("Auction %s has no valid revealed bids (no winner).", auction.Id))
k.logger.Info(fmt.Sprintf("Auction %s has no valid revealed bids (no winner).", auction.Id))
}
if err := k.SaveAuction(ctx, auction); err != nil {
@ -738,7 +736,7 @@ func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction
for _, bid := range bids {
bidderAddress, err := addrCodec.StringToBytes(bid.BidderAddress)
if err != nil {
k.Logger(ctx).Error(fmt.Sprintf("Invalid bidderAddress address. %v", err))
k.logger.Error(fmt.Sprintf("Invalid bidderAddress address. %v", err))
panic("Invalid bidder address.")
}
@ -746,7 +744,7 @@ func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction
// Send reveal fee back to bidders that've revealed the bid.
sdkErr := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, auctiontypes.ModuleName, bidderAddress, sdk.NewCoins(bid.RevealFee))
if sdkErr != nil {
k.Logger(ctx).Error(fmt.Sprintf("Auction error returning reveal fee: %v", sdkErr))
k.logger.Error(fmt.Sprintf("Auction error returning reveal fee: %v", sdkErr))
panic(sdkErr)
}
}
@ -754,7 +752,7 @@ func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction
// Send back locked bid amount to all bidders.
sdkErr := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, auctiontypes.ModuleName, bidderAddress, sdk.NewCoins(bid.BidAmount))
if sdkErr != nil {
k.Logger(ctx).Error(fmt.Sprintf("Auction error returning bid amount: %v", sdkErr))
k.logger.Error(fmt.Sprintf("Auction error returning bid amount: %v", sdkErr))
panic(sdkErr)
}
}
@ -763,21 +761,21 @@ func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction
if len(auction.WinnerAddresses) != 0 {
winnerAddress, err := addrCodec.StringToBytes(auction.WinnerAddresses[0])
if err != nil {
k.Logger(ctx).Error(fmt.Sprintf("Invalid winner address. %v", err))
k.logger.Error(fmt.Sprintf("Invalid winner address. %v", err))
panic("Invalid winner address.")
}
// Take 2nd price from winner.
sdkErr := k.bankKeeper.SendCoinsFromAccountToModule(ctx, winnerAddress, auctiontypes.ModuleName, sdk.NewCoins(auction.WinningPrice))
if sdkErr != nil {
k.Logger(ctx).Error(fmt.Sprintf("Auction error taking funds from winner: %v", sdkErr))
k.logger.Error(fmt.Sprintf("Auction error taking funds from winner: %v", sdkErr))
panic(sdkErr)
}
// Burn anything over the min. bid amount.
amountToBurn := auction.WinningPrice.Sub(auction.MinimumBid)
if amountToBurn.IsNegative() {
k.Logger(ctx).Error("Auction coins to burn cannot be negative.")
k.logger.Error("Auction coins to burn cannot be negative.")
panic("Auction coins to burn cannot be negative.")
}
@ -789,24 +787,24 @@ func (k Keeper) pickAuctionWinner(ctx sdk.Context, auction *auctiontypes.Auction
sdk.NewCoins(amountToBurn),
)
if sdkErr != nil {
k.Logger(ctx).Error(fmt.Sprintf("Auction error burning coins: %v", sdkErr))
k.logger.Error(fmt.Sprintf("Auction error burning coins: %v", sdkErr))
panic(sdkErr)
}
}
// Notify other modules (hook).
k.Logger(ctx).Info(fmt.Sprintf("Auction %s notifying %d modules.", auction.Id, len(k.usageKeepers)))
k.logger.Info(fmt.Sprintf("Auction %s notifying %d modules.", auction.Id, len(k.usageKeepers)))
for _, keeper := range k.usageKeepers {
k.Logger(ctx).Info(fmt.Sprintf("Auction %s notifying module %s.", auction.Id, keeper.ModuleName()))
keeper.OnAuctionWinnerSelected(ctx, auction.Id)
k.logger.Info(fmt.Sprintf("Auction %s notifying module %s.", auction.Id, keeper.ModuleName()))
keeper.OnAuctionWinnerSelected(ctx, auction.Id, uint64(k.HeaderService.HeaderInfo(ctx).Height))
}
return nil
}
// Pick winner for provider auction
func (k Keeper) pickProviderAuctionWinners(ctx sdk.Context, auction *auctiontypes.Auction) error {
k.Logger(ctx).Info(fmt.Sprintf("Picking auction %s winners.", auction.Id))
func (k Keeper) pickProviderAuctionWinners(ctx context.Context, auction *auctiontypes.Auction) error {
k.logger.Info(fmt.Sprintf("Picking auction %s winners.", auction.Id))
bids, err := k.GetBids(ctx, auction.Id)
if err != nil {
@ -815,11 +813,11 @@ func (k Keeper) pickProviderAuctionWinners(ctx sdk.Context, auction *auctiontype
revealedBids := make([]*auctiontypes.Bid, 0, len(bids))
for _, bid := range bids {
k.Logger(ctx).Info(fmt.Sprintf("Processing bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Processing bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
// Only consider revealed bids.
if bid.Status != auctiontypes.BidStatusRevealed {
k.Logger(ctx).Info(fmt.Sprintf("Ignoring unrevealed bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Ignoring unrevealed bid %s %s", bid.BidderAddress, bid.BidAmount.String()))
continue
}
@ -860,11 +858,11 @@ func (k Keeper) pickProviderAuctionWinners(ctx sdk.Context, auction *auctiontype
auction.WinningPrice = winnerBids[len(winnerBids)-1].BidAmount
for _, bid := range winnerBids {
k.Logger(ctx).Info(fmt.Sprintf("Auction %s winner address: %s, bid amount: %s.", auction.Id, bid.BidderAddress, bid.BidAmount.String()))
k.logger.Info(fmt.Sprintf("Auction %s winner address: %s, bid amount: %s.", auction.Id, bid.BidderAddress, bid.BidAmount.String()))
}
k.Logger(ctx).Info(fmt.Sprintf("Auction %s winning price %s.", auction.Id, auction.WinningPrice.String()))
k.logger.Info(fmt.Sprintf("Auction %s winning price %s.", auction.Id, auction.WinningPrice.String()))
} else {
k.Logger(ctx).Info(fmt.Sprintf("Auction %s has no valid revealed bids (no winner).", auction.Id))
k.logger.Info(fmt.Sprintf("Auction %s has no valid revealed bids (no winner).", auction.Id))
}
if err := k.SaveAuction(ctx, auction); err != nil {
@ -876,7 +874,7 @@ func (k Keeper) pickProviderAuctionWinners(ctx sdk.Context, auction *auctiontype
for _, bid := range bids {
bidderAddress, err := addrCodec.StringToBytes(bid.BidderAddress)
if err != nil {
k.Logger(ctx).Error(fmt.Sprintf("Invalid bidderAddress address. %v", err))
k.logger.Error(fmt.Sprintf("Invalid bidderAddress address. %v", err))
panic("Invalid bidder address.")
}
@ -884,7 +882,7 @@ func (k Keeper) pickProviderAuctionWinners(ctx sdk.Context, auction *auctiontype
// Send reveal fee back to bidders that've revealed the bid.
sdkErr := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, auctiontypes.ModuleName, bidderAddress, sdk.NewCoins(bid.RevealFee))
if sdkErr != nil {
k.Logger(ctx).Error(fmt.Sprintf("Auction error returning reveal fee: %v", sdkErr))
k.logger.Error(fmt.Sprintf("Auction error returning reveal fee: %v", sdkErr))
panic(sdkErr)
}
}
@ -898,7 +896,7 @@ func (k Keeper) pickProviderAuctionWinners(ctx sdk.Context, auction *auctiontype
ownerAccAddress, err := addrCodec.StringToBytes(auction.OwnerAddress)
if err != nil {
k.Logger(ctx).Error(fmt.Sprintf("Invalid auction owner address. %v", err))
k.logger.Error(fmt.Sprintf("Invalid auction owner address. %v", err))
panic("Invalid auction owner address.")
}
@ -909,21 +907,21 @@ func (k Keeper) pickProviderAuctionWinners(ctx sdk.Context, auction *auctiontype
sdk.NewCoins(creatorLeftOverAmount),
)
if sdkErr != nil {
k.Logger(ctx).Error(fmt.Sprintf("Auction error returning leftover locked amount: %v", sdkErr))
k.logger.Error(fmt.Sprintf("Auction error returning leftover locked amount: %v", sdkErr))
panic(sdkErr)
}
// Notify other modules (hook).
k.Logger(ctx).Info(fmt.Sprintf("Auction %s notifying %d modules.", auction.Id, len(k.usageKeepers)))
k.logger.Info(fmt.Sprintf("Auction %s notifying %d modules.", auction.Id, len(k.usageKeepers)))
for _, keeper := range k.usageKeepers {
k.Logger(ctx).Info(fmt.Sprintf("Auction %s notifying module %s.", auction.Id, keeper.ModuleName()))
keeper.OnAuctionWinnerSelected(ctx, auction.Id)
k.logger.Info(fmt.Sprintf("Auction %s notifying module %s.", auction.Id, keeper.ModuleName()))
keeper.OnAuctionWinnerSelected(ctx, auction.Id, uint64(k.HeaderService.HeaderInfo(ctx).Height))
}
return nil
}
func (k Keeper) ReleaseFunds(ctx sdk.Context, msg auctiontypes.MsgReleaseFunds) (*auctiontypes.Auction, error) {
func (k Keeper) ReleaseFunds(ctx context.Context, msg auctiontypes.MsgReleaseFunds) (*auctiontypes.Auction, error) {
auction, err := k.GetAuctionById(ctx, msg.AuctionId)
if err != nil {
return nil, err
@ -958,7 +956,7 @@ func (k Keeper) ReleaseFunds(ctx sdk.Context, msg auctiontypes.MsgReleaseFunds)
for _, winnerAddress := range auction.WinnerAddresses {
winnerAccAddress, err := addrCodec.StringToBytes(winnerAddress)
if err != nil {
k.Logger(ctx).Error(fmt.Sprintf("Invalid winner address. %v", err))
k.logger.Error(fmt.Sprintf("Invalid winner address. %v", err))
panic("Invalid winner address.")
}
@ -970,7 +968,7 @@ func (k Keeper) ReleaseFunds(ctx sdk.Context, msg auctiontypes.MsgReleaseFunds)
sdk.NewCoins(auction.WinningPrice),
)
if sdkErr != nil {
k.Logger(ctx).Error(fmt.Sprintf("Auction error sending funds to winner: %v", sdkErr))
k.logger.Error(fmt.Sprintf("Auction error sending funds to winner: %v", sdkErr))
panic(sdkErr)
}
}

View File

@ -52,7 +52,7 @@ func (ms msgServer) CreateAuction(c context.Context, msg *auctiontypes.MsgCreate
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "CreateAuction")
utils.LogTxGasConsumed(ctx, ms.k.logger, "CreateAuction")
return &auctiontypes.MsgCreateAuctionResponse{Auction: resp}, nil
}
@ -90,7 +90,7 @@ func (ms msgServer) CommitBid(c context.Context, msg *auctiontypes.MsgCommitBid)
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "CommitBid")
utils.LogTxGasConsumed(ctx, ms.k.logger, "CommitBid")
return &auctiontypes.MsgCommitBidResponse{Bid: resp}, nil
}
@ -128,7 +128,7 @@ func (ms msgServer) RevealBid(c context.Context, msg *auctiontypes.MsgRevealBid)
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "RevealBid")
utils.LogTxGasConsumed(ctx, ms.k.logger, "RevealBid")
return &auctiontypes.MsgRevealBidResponse{Auction: resp}, nil
}
@ -184,7 +184,7 @@ func (ms msgServer) ReleaseFunds(c context.Context, msg *auctiontypes.MsgRelease
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "ReleaseFunds")
utils.LogTxGasConsumed(ctx, ms.k.logger, "ReleaseFunds")
return &auctiontypes.MsgReleaseFundsResponse{Auction: resp}, nil
}

View File

@ -4,7 +4,6 @@ import (
"context"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
auctiontypes "git.vdb.to/cerc-io/laconicd/x/auction"
@ -22,9 +21,7 @@ func NewQueryServerImpl(k *Keeper) auctiontypes.QueryServer {
}
// Params implements the params query command
func (qs queryServer) Params(c context.Context, req *auctiontypes.QueryParamsRequest) (*auctiontypes.QueryParamsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) Params(ctx context.Context, req *auctiontypes.QueryParamsRequest) (*auctiontypes.QueryParamsResponse, error) {
params, err := qs.k.GetParams(ctx)
if err != nil {
return nil, err
@ -34,9 +31,7 @@ func (qs queryServer) Params(c context.Context, req *auctiontypes.QueryParamsReq
}
// Auctions queries all auctions
func (qs queryServer) Auctions(c context.Context, req *auctiontypes.QueryAuctionsRequest) (*auctiontypes.QueryAuctionsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) Auctions(ctx context.Context, req *auctiontypes.QueryAuctionsRequest) (*auctiontypes.QueryAuctionsResponse, error) {
auctions, err := qs.k.ListAuctions(ctx)
if err != nil {
return nil, err
@ -46,9 +41,7 @@ func (qs queryServer) Auctions(c context.Context, req *auctiontypes.QueryAuction
}
// GetAuction queries an auction by id
func (qs queryServer) GetAuction(c context.Context, req *auctiontypes.QueryGetAuctionRequest) (*auctiontypes.QueryGetAuctionResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) GetAuction(ctx context.Context, req *auctiontypes.QueryGetAuctionRequest) (*auctiontypes.QueryGetAuctionResponse, error) {
if req.Id == "" {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "auction id is required")
}
@ -62,9 +55,7 @@ func (qs queryServer) GetAuction(c context.Context, req *auctiontypes.QueryGetAu
}
// GetBid queries an auction bid by auction-id and bidder
func (qs queryServer) GetBid(c context.Context, req *auctiontypes.QueryGetBidRequest) (*auctiontypes.QueryGetBidResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) GetBid(ctx context.Context, req *auctiontypes.QueryGetBidRequest) (*auctiontypes.QueryGetBidResponse, error) {
if req.AuctionId == "" {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "auction id is required")
}
@ -82,9 +73,7 @@ func (qs queryServer) GetBid(c context.Context, req *auctiontypes.QueryGetBidReq
}
// GetBids queries all auction bids
func (qs queryServer) GetBids(c context.Context, req *auctiontypes.QueryGetBidsRequest) (*auctiontypes.QueryGetBidsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) GetBids(ctx context.Context, req *auctiontypes.QueryGetBidsRequest) (*auctiontypes.QueryGetBidsResponse, error) {
if req.AuctionId == "" {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "auction id is required")
}
@ -99,11 +88,9 @@ func (qs queryServer) GetBids(c context.Context, req *auctiontypes.QueryGetBidsR
// AuctionsByBidder queries auctions by bidder
func (qs queryServer) AuctionsByBidder(
c context.Context,
ctx context.Context,
req *auctiontypes.QueryAuctionsByBidderRequest,
) (*auctiontypes.QueryAuctionsByBidderResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
if req.BidderAddress == "" {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "bidder address is required")
}
@ -122,11 +109,9 @@ func (qs queryServer) AuctionsByBidder(
// AuctionsByOwner queries auctions by owner
func (qs queryServer) AuctionsByOwner(
c context.Context,
ctx context.Context,
req *auctiontypes.QueryAuctionsByOwnerRequest,
) (*auctiontypes.QueryAuctionsByOwnerResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
if req.OwnerAddress == "" {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "owner address is required")
}
@ -141,10 +126,9 @@ func (qs queryServer) AuctionsByOwner(
// GetAuctionModuleBalance queries the auction module account balance
func (qs queryServer) GetAuctionModuleBalance(
c context.Context,
ctx context.Context,
req *auctiontypes.QueryGetAuctionModuleBalanceRequest,
) (*auctiontypes.QueryGetAuctionModuleBalanceResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
balances := qs.k.GetAuctionModuleBalances(ctx)
return &auctiontypes.QueryGetAuctionModuleBalanceResponse{Balance: balances}, nil

View File

@ -3,14 +3,10 @@ package module
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
"git.vdb.to/cerc-io/laconicd/x/auction/keeper"
)
// EndBlocker is called every block
func EndBlocker(ctx context.Context, k *keeper.Keeper) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
return k.EndBlockerProcessAuctions(sdkCtx)
return k.EndBlockerProcessAuctions(ctx)
}

View File

@ -2,9 +2,9 @@ package module
import (
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/store"
"cosmossdk.io/depinject"
"cosmossdk.io/depinject/appconfig"
"cosmossdk.io/log"
bank "cosmossdk.io/x/bank/keeper"
govtypes "cosmossdk.io/x/gov/types"
"github.com/cosmos/cosmos-sdk/codec"
@ -35,12 +35,14 @@ func init() {
type ModuleInputs struct {
depinject.In
Config *modulev1.Module
Cdc codec.Codec
StoreService store.KVStoreService
Env appmodule.Environment
Config *modulev1.Module
Cdc codec.Codec
AccountKeeper auth.AccountKeeper
BankKeeper bank.Keeper
Logger log.Logger
}
type ModuleOutputs struct {
@ -61,7 +63,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {
authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority)
}
k := keeper.NewKeeper(in.Cdc, in.StoreService, in.AccountKeeper, in.BankKeeper, authority.String())
k := keeper.NewKeeper(in.Env, in.Cdc, in.AccountKeeper, in.BankKeeper, authority.String(), in.Logger)
m := NewAppModule(in.Cdc, k)
return ModuleOutputs{Module: m, Keeper: k}

View File

@ -9,6 +9,7 @@ import (
"cosmossdk.io/collections"
"cosmossdk.io/collections/indexes"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/store"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
@ -43,8 +44,9 @@ func newBondIndexes(sb *collections.SchemaBuilder) BondsIndexes {
}
type Keeper struct {
// Codecs
cdc codec.BinaryCodec
appmodule.Environment
cdc codec.BinaryCodec
logger log.Logger
authority string
@ -63,11 +65,13 @@ type Keeper struct {
// NewKeeper creates new instances of the bond Keeper
func NewKeeper(
env appmodule.Environment,
cdc codec.BinaryCodec,
storeService store.KVStoreService,
accountKeeper auth.AccountKeeper,
bankKeeper bank.Keeper,
authority string,
logger log.Logger,
) *Keeper {
// ensure that authority is a valid AccAddress
if _, err := accountKeeper.AddressCodec().StringToBytes(authority); err != nil {
@ -76,7 +80,9 @@ func NewKeeper(
sb := collections.NewSchemaBuilder(storeService)
k := Keeper{
Environment: env,
cdc: cdc,
logger: logger.With(log.ModuleKey, "x/"+bondtypes.ModuleName),
authority: authority,
accountKeeper: accountKeeper,
bankKeeper: bankKeeper,
@ -97,11 +103,6 @@ func NewKeeper(
return &k
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", bondtypes.ModuleName)
}
func (k *Keeper) SetUsageKeepers(usageKeepers []bondtypes.BondUsageKeeper) {
if k.usageKeepers != nil {
panic("cannot set bond hooks twice")

View File

@ -4,7 +4,6 @@ import (
"context"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
bondtypes "git.vdb.to/cerc-io/laconicd/x/bond"
@ -22,9 +21,7 @@ func NewQueryServerImpl(k *Keeper) bondtypes.QueryServer {
}
// Params implements bond.QueryServer.
func (qs queryServer) Params(c context.Context, _ *bondtypes.QueryParamsRequest) (*bondtypes.QueryParamsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) Params(ctx context.Context, _ *bondtypes.QueryParamsRequest) (*bondtypes.QueryParamsResponse, error) {
params, err := qs.k.GetParams(ctx)
if err != nil {
return nil, err
@ -34,9 +31,7 @@ func (qs queryServer) Params(c context.Context, _ *bondtypes.QueryParamsRequest)
}
// Bonds implements bond.QueryServer.
func (qs queryServer) Bonds(c context.Context, _ *bondtypes.QueryBondsRequest) (*bondtypes.QueryBondsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) Bonds(ctx context.Context, _ *bondtypes.QueryBondsRequest) (*bondtypes.QueryBondsResponse, error) {
resp, err := qs.k.ListBonds(ctx)
if err != nil {
return nil, err
@ -46,9 +41,7 @@ func (qs queryServer) Bonds(c context.Context, _ *bondtypes.QueryBondsRequest) (
}
// GetBondById implements bond.QueryServer.
func (qs queryServer) GetBondById(c context.Context, req *bondtypes.QueryGetBondByIdRequest) (*bondtypes.QueryGetBondByIdResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) GetBondById(ctx context.Context, req *bondtypes.QueryGetBondByIdRequest) (*bondtypes.QueryGetBondByIdResponse, error) {
bondId := req.GetId()
if len(bondId) == 0 {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "bond id required")
@ -64,11 +57,9 @@ func (qs queryServer) GetBondById(c context.Context, req *bondtypes.QueryGetBond
// GetBondsByOwner implements bond.QueryServer.
func (qs queryServer) GetBondsByOwner(
c context.Context,
ctx context.Context,
req *bondtypes.QueryGetBondsByOwnerRequest,
) (*bondtypes.QueryGetBondsByOwnerResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
owner := req.GetOwner()
if len(owner) == 0 {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest,
@ -86,10 +77,9 @@ func (qs queryServer) GetBondsByOwner(
// GetBondModuleBalance implements bond.QueryServer.
func (qs queryServer) GetBondModuleBalance(
c context.Context,
ctx context.Context,
_ *bondtypes.QueryGetBondModuleBalanceRequest,
) (*bondtypes.QueryGetBondModuleBalanceResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
balances := qs.k.GetBondModuleBalances(ctx)
return &bondtypes.QueryGetBondModuleBalanceResponse{

View File

@ -5,6 +5,7 @@ import (
"cosmossdk.io/core/store"
"cosmossdk.io/depinject"
"cosmossdk.io/depinject/appconfig"
"cosmossdk.io/log"
bank "cosmossdk.io/x/bank/keeper"
govtypes "cosmossdk.io/x/gov/types"
"github.com/cosmos/cosmos-sdk/codec"
@ -35,12 +36,15 @@ func init() {
type ModuleInputs struct {
depinject.In
Env appmodule.Environment
Config *modulev1.Module
Cdc codec.Codec
StoreService store.KVStoreService
AccountKeeper auth.AccountKeeper
BankKeeper bank.Keeper
Logger log.Logger
}
type ModuleOutputs struct {
@ -57,7 +61,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {
authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority)
}
k := keeper.NewKeeper(in.Cdc, in.StoreService, in.AccountKeeper, in.BankKeeper, authority.String())
k := keeper.NewKeeper(in.Env, in.Cdc, in.StoreService, in.AccountKeeper, in.BankKeeper, authority.String(), in.Logger)
m := NewAppModule(in.Cdc, k)
return ModuleOutputs{Module: m, Keeper: k}

View File

@ -1,12 +1,14 @@
package keeper
import (
"context"
"encoding/json"
"errors"
"fmt"
"cosmossdk.io/collections"
"cosmossdk.io/core/address"
"cosmossdk.io/core/appmodule"
storetypes "cosmossdk.io/core/store"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
@ -20,8 +22,10 @@ import (
)
type Keeper struct {
appmodule.Environment
cdc codec.BinaryCodec
addressCodec address.Codec
logger log.Logger
// authority is the address capable of executing a MsgUpdateParams and other authority-gated message.
// typically, this should be the x/gov module account.
@ -34,7 +38,13 @@ type Keeper struct {
}
// NewKeeper creates a new Keeper instance
func NewKeeper(cdc codec.BinaryCodec, addressCodec address.Codec, storeService storetypes.KVStoreService, authority string) *Keeper {
func NewKeeper(
cdc codec.BinaryCodec,
addressCodec address.Codec,
storeService storetypes.KVStoreService,
authority string,
logger log.Logger,
) *Keeper {
if _, err := addressCodec.StringToBytes(authority); err != nil {
panic(fmt.Errorf("invalid authority address: %w", err))
}
@ -43,6 +53,7 @@ func NewKeeper(cdc codec.BinaryCodec, addressCodec address.Codec, storeService s
k := Keeper{
cdc: cdc,
addressCodec: addressCodec,
logger: logger.With(log.ModuleKey, "x/"+onboardingTypes.ModuleName),
authority: authority,
Params: collections.NewItem(sb, onboardingTypes.ParamsPrefix, "params", codec.CollValue[onboardingTypes.Params](cdc)),
Participants: collections.NewMap(
@ -65,12 +76,8 @@ func (k Keeper) GetAuthority() string {
return k.authority
}
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", onboardingTypes.ModuleName)
}
func (k Keeper) OnboardParticipant(
ctx sdk.Context,
ctx context.Context,
msg *onboardingTypes.MsgOnboardParticipant,
signerAddress sdk.AccAddress,
) (*onboardingTypes.MsgOnboardParticipantResponse, error) {
@ -112,13 +119,13 @@ func (k Keeper) OnboardParticipant(
return &onboardingTypes.MsgOnboardParticipantResponse{}, nil
}
func (k Keeper) StoreParticipant(ctx sdk.Context, participant *onboardingTypes.Participant) error {
func (k Keeper) StoreParticipant(ctx context.Context, participant *onboardingTypes.Participant) error {
key := participant.CosmosAddress
return k.Participants.Set(ctx, key, *participant)
}
// ListParticipants - get all participants.
func (k Keeper) ListParticipants(ctx sdk.Context) ([]*onboardingTypes.Participant, error) {
func (k Keeper) ListParticipants(ctx context.Context) ([]*onboardingTypes.Participant, error) {
var participants []*onboardingTypes.Participant
iter, err := k.Participants.Iterate(ctx, nil)
@ -139,7 +146,7 @@ func (k Keeper) ListParticipants(ctx sdk.Context) ([]*onboardingTypes.Participan
}
// GetParticipantByAddress - get participant by cosmos (laconic) address.
func (k Keeper) GetParticipantByAddress(ctx sdk.Context, address string) (onboardingTypes.Participant, error) {
func (k Keeper) GetParticipantByAddress(ctx context.Context, address string) (onboardingTypes.Participant, error) {
participant, err := k.Participants.Get(ctx, address)
if err != nil {
if errors.Is(err, collections.ErrNotFound) {
@ -152,7 +159,7 @@ func (k Keeper) GetParticipantByAddress(ctx sdk.Context, address string) (onboar
}
// GetParticipantByNitroAddress - get participant by nitro address.
func (k Keeper) GetParticipantByNitroAddress(ctx sdk.Context, nitroAddress string) (onboardingTypes.Participant, error) {
func (k Keeper) GetParticipantByNitroAddress(ctx context.Context, nitroAddress string) (onboardingTypes.Participant, error) {
var participant onboardingTypes.Participant
err := k.Participants.Walk(ctx, nil, func(key string, value onboardingTypes.Participant) (bool, error) {

View File

@ -52,7 +52,7 @@ func (ms msgServer) OnboardParticipant(c context.Context, msg *onboarding.MsgOnb
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "OnboardParticipant")
utils.LogTxGasConsumed(ctx, ms.k.logger, "OnboardParticipant")
return &onboarding.MsgOnboardParticipantResponse{}, nil
}

View File

@ -4,7 +4,6 @@ import (
"context"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
onboardingtypes "git.vdb.to/cerc-io/laconicd/x/onboarding"
@ -23,11 +22,9 @@ func NewQueryServerImpl(k *Keeper) onboardingtypes.QueryServer {
// Participants implements Participants.QueryServer.
func (qs queryServer) Participants(
c context.Context,
ctx context.Context,
_ *onboardingtypes.QueryParticipantsRequest,
) (*onboardingtypes.QueryParticipantsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
resp, err := qs.k.ListParticipants(ctx)
if err != nil {
return nil, err
@ -38,11 +35,9 @@ func (qs queryServer) Participants(
// GetParticipantByAddress implements the GetParticipantByAddress query.
func (qs queryServer) GetParticipantByAddress(
c context.Context,
ctx context.Context,
req *onboardingtypes.QueryGetParticipantByAddressRequest,
) (*onboardingtypes.QueryGetParticipantByAddressResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
if req.Address == "" {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "cosmos (laconic) address is required")
}
@ -57,11 +52,9 @@ func (qs queryServer) GetParticipantByAddress(
// GetParticipantByNitroAddress implements the GetParticipantByNitroAddress query.
func (qs queryServer) GetParticipantByNitroAddress(
c context.Context,
ctx context.Context,
req *onboardingtypes.QueryGetParticipantByNitroAddressRequest,
) (*onboardingtypes.QueryGetParticipantByNitroAddressResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
if req.NitroAddress == "" {
return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "nitro address is required")
}

View File

@ -6,6 +6,7 @@ import (
"cosmossdk.io/core/store"
"cosmossdk.io/depinject"
"cosmossdk.io/depinject/appconfig"
"cosmossdk.io/log"
"github.com/cosmos/cosmos-sdk/codec"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -34,6 +35,7 @@ type ModuleInputs struct {
Cdc codec.Codec
StoreService store.KVStoreService
AddressCodec address.Codec
Logger log.Logger
Config *modulev1.Module
}
@ -52,7 +54,7 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {
authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority)
}
k := keeper.NewKeeper(in.Cdc, in.AddressCodec, in.StoreService, authority.String())
k := keeper.NewKeeper(in.Cdc, in.AddressCodec, in.StoreService, authority.String(), in.Logger)
m := NewAppModule(in.Cdc, k)
return ModuleOutputs{Module: m, Keeper: k}

View File

@ -2,21 +2,13 @@ package keeper
import (
"context"
"errors"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"git.vdb.to/cerc-io/laconicd/x/registry"
)
// InitGenesis initializes the module state from a genesis state.
func (k *Keeper) InitGenesis(ctx_ context.Context, data *registry.GenesisState) error {
ctx, ok := sdk.TryUnwrapSDKContext(ctx_)
if !ok {
return errors.New("failed to unwrap sdk.Context")
}
func (k *Keeper) InitGenesis(ctx context.Context, data *registry.GenesisState) error {
if err := k.Params.Set(ctx, data.Params); err != nil {
return err
}
@ -30,7 +22,7 @@ func (k *Keeper) InitGenesis(ctx_ context.Context, data *registry.GenesisState)
if err != nil {
return err
}
if expiryTime.After(ctx.BlockTime()) {
if expiryTime.After(k.HeaderService.HeaderInfo(ctx).Time) {
if err := k.insertRecordExpiryQueue(ctx, record); err != nil {
return err
}
@ -59,12 +51,7 @@ func (k *Keeper) InitGenesis(ctx_ context.Context, data *registry.GenesisState)
}
// ExportGenesis exports the module state to a genesis state.
func (k *Keeper) ExportGenesis(ctx_ context.Context) (*registry.GenesisState, error) {
ctx, ok := sdk.TryUnwrapSDKContext(ctx_)
if !ok {
return nil, errors.New("failed to unwrap sdk.Context")
}
func (k *Keeper) ExportGenesis(ctx context.Context) (*registry.GenesisState, error) {
params, err := k.Params.Get(ctx)
if err != nil {
return nil, err

View File

@ -2,6 +2,7 @@ package keeper
import (
"bytes"
"context"
"errors"
"fmt"
"sort"
@ -9,7 +10,7 @@ import (
"cosmossdk.io/collections"
"cosmossdk.io/collections/indexes"
storetypes "cosmossdk.io/core/store"
"cosmossdk.io/core/appmodule"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
bank "cosmossdk.io/x/bank/keeper"
@ -93,7 +94,9 @@ func newNameRecordIndexes(sb *collections.SchemaBuilder) NameRecordsIndexes {
}
type Keeper struct {
cdc codec.BinaryCodec
appmodule.Environment
cdc codec.BinaryCodec
logger log.Logger
authority string
@ -115,22 +118,25 @@ type Keeper struct {
// NewKeeper creates a new Keeper instance
func NewKeeper(
env appmodule.Environment,
cdc codec.BinaryCodec,
storeService storetypes.KVStoreService,
accountKeeper auth.AccountKeeper,
bankKeeper bank.Keeper,
bondKeeper *bondkeeper.Keeper,
auctionKeeper *auctionkeeper.Keeper,
authority string,
logger log.Logger,
) Keeper {
// ensure that authority is a valid AccAddress
if _, err := accountKeeper.AddressCodec().StringToBytes(authority); err != nil {
panic("authority is not a valid acc address")
}
sb := collections.NewSchemaBuilder(storeService)
sb := collections.NewSchemaBuilder(env.KVStoreService)
k := Keeper{
Environment: env,
cdc: cdc,
logger: logger.With(log.ModuleKey, "x/"+registrytypes.ModuleName),
authority: authority,
accountKeeper: accountKeeper,
bankKeeper: bankKeeper,
@ -176,27 +182,18 @@ func NewKeeper(
return k
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return logger(ctx)
}
func logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", registrytypes.ModuleName)
}
// GetAuthority returns the x/registry module's authority.
func (k Keeper) GetAuthority() string {
return k.authority
}
// SetParams sets the x/registry module parameters.
func (k Keeper) SetParams(ctx sdk.Context, params registrytypes.Params) error {
func (k Keeper) SetParams(ctx context.Context, params registrytypes.Params) error {
return k.Params.Set(ctx, params)
}
// HasRecord - checks if a record by the given id exists.
func (k Keeper) HasRecord(ctx sdk.Context, id string) (bool, error) {
func (k Keeper) HasRecord(ctx context.Context, id string) (bool, error) {
has, err := k.Records.Has(ctx, id)
if err != nil {
return false, err
@ -206,7 +203,7 @@ func (k Keeper) HasRecord(ctx sdk.Context, id string) (bool, error) {
}
// PaginatedListRecords - get all records with optional pagination.
func (k Keeper) PaginatedListRecords(ctx sdk.Context, pagination *query.PageRequest) ([]registrytypes.Record, *query.PageResponse, error) {
func (k Keeper) PaginatedListRecords(ctx context.Context, pagination *query.PageRequest) ([]registrytypes.Record, *query.PageResponse, error) {
var records []registrytypes.Record
var pageResp *query.PageResponse
@ -244,7 +241,7 @@ func (k Keeper) PaginatedListRecords(ctx sdk.Context, pagination *query.PageRequ
}
// GetRecordById - gets a record from the store.
func (k Keeper) GetRecordById(ctx sdk.Context, id string) (registrytypes.Record, error) {
func (k Keeper) GetRecordById(ctx context.Context, id string) (registrytypes.Record, error) {
record, err := k.Records.Get(ctx, id)
if err != nil {
return registrytypes.Record{}, err
@ -258,7 +255,7 @@ func (k Keeper) GetRecordById(ctx sdk.Context, id string) (registrytypes.Record,
}
// GetRecordsByBondId - gets a record from the store.
func (k Keeper) GetRecordsByBondId(ctx sdk.Context, bondId string) ([]registrytypes.Record, error) {
func (k Keeper) GetRecordsByBondId(ctx context.Context, bondId string) ([]registrytypes.Record, error) {
var records []registrytypes.Record
err := k.Records.Indexes.BondId.Walk(ctx, collections.NewPrefixedPairRange[string, string](bondId), func(bondId string, id string) (bool, error) {
@ -284,7 +281,7 @@ func (k Keeper) GetRecordsByBondId(ctx sdk.Context, bondId string) ([]registryty
// PaginatedRecordsFromAttributes gets a list of records whose attributes match all provided values
// with optional pagination.
func (k Keeper) PaginatedRecordsFromAttributes(
ctx sdk.Context,
ctx context.Context,
attributes []*registrytypes.QueryRecordsRequest_KeyValueInput,
all bool,
pagination *query.PageRequest,
@ -385,12 +382,12 @@ func QueryValueToJSON(input *registrytypes.QueryRecordsRequest_ValueInput) ([]by
}
// PutRecord - saves a record to the store.
func (k Keeper) SaveRecord(ctx sdk.Context, record registrytypes.Record) error {
func (k Keeper) SaveRecord(ctx context.Context, record registrytypes.Record) error {
return k.Records.Set(ctx, record.Id, record)
}
// ProcessSetRecord creates a record.
func (k Keeper) SetRecord(ctx sdk.Context, msg registrytypes.MsgSetRecord) (*registrytypes.ReadableRecord, error) {
func (k Keeper) SetRecord(ctx context.Context, msg registrytypes.MsgSetRecord) (*registrytypes.ReadableRecord, error) {
payload := msg.Payload.ToReadablePayload()
record := registrytypes.ReadableRecord{Attributes: payload.RecordAttributes, BondId: msg.BondId}
@ -436,7 +433,7 @@ func (k Keeper) SetRecord(ctx sdk.Context, msg registrytypes.MsgSetRecord) (*reg
return &record, nil
}
func (k Keeper) processRecord(ctx sdk.Context, record *registrytypes.ReadableRecord) error {
func (k Keeper) processRecord(ctx context.Context, record *registrytypes.ReadableRecord) error {
params, err := k.GetParams(ctx)
if err != nil {
return err
@ -449,8 +446,10 @@ func (k Keeper) processRecord(ctx sdk.Context, record *registrytypes.ReadableRec
return err
}
record.CreateTime = ctx.BlockHeader().Time.Format(time.RFC3339)
record.ExpiryTime = ctx.BlockHeader().Time.Add(params.RecordRentDuration).Format(time.RFC3339)
// TODO use HeaderService
createTime := k.HeaderService.HeaderInfo(ctx).Time
record.CreateTime = createTime.Format(time.RFC3339)
record.ExpiryTime = createTime.Add(params.RecordRentDuration).Format(time.RFC3339)
record.Deleted = false
recordObj, err := record.ToRecordObj()
@ -472,7 +471,7 @@ func (k Keeper) processRecord(ctx sdk.Context, record *registrytypes.ReadableRec
return k.insertRecordExpiryQueue(ctx, recordObj)
}
func (k Keeper) processAttributes(ctx sdk.Context, attrs registrytypes.AttributeMap, id string) error {
func (k Keeper) processAttributes(ctx context.Context, attrs registrytypes.AttributeMap, id string) error {
np := basicnode.Prototype.Map
nb := np.NewBuilder()
encAttrs, err := canonicaljson.Marshal(attrs)
@ -494,7 +493,7 @@ func (k Keeper) processAttributes(ctx sdk.Context, attrs registrytypes.Attribute
return k.processAttributeMap(ctx, n, id, "")
}
func (k Keeper) processAttributeMap(ctx sdk.Context, n ipld.Node, id string, prefix string) error {
func (k Keeper) processAttributeMap(ctx context.Context, n ipld.Node, id string, prefix string) error {
for it := n.MapIterator(); !it.Done(); {
//nolint:misspell
keynode, valuenode, err := it.Next()
@ -527,7 +526,7 @@ func (k Keeper) processAttributeMap(ctx sdk.Context, n ipld.Node, id string, pre
return nil
}
func (k Keeper) setAttributeMapping(ctx sdk.Context, key collections.Pair[string, string], recordId string) error {
func (k Keeper) setAttributeMapping(ctx context.Context, key collections.Pair[string, string], recordId string) error {
var recordIds []string
has, err := k.AttributesMap.Has(ctx, key)
@ -547,13 +546,13 @@ func (k Keeper) setAttributeMapping(ctx sdk.Context, key collections.Pair[string
return k.AttributesMap.Set(ctx, key, registrytypes.RecordsList{Value: recordIds})
}
func (k Keeper) getAttributeMapping(ctx sdk.Context, key collections.Pair[string, string]) ([]string, error) {
func (k Keeper) getAttributeMapping(ctx context.Context, key collections.Pair[string, string]) ([]string, error) {
if has, err := k.AttributesMap.Has(ctx, key); !has {
if err != nil {
return []string{}, err
}
k.Logger(ctx).Debug(fmt.Sprintf("store doesn't have key: %v", key))
k.logger.Debug(fmt.Sprintf("store doesn't have key: %v", key))
return []string{}, nil
}
@ -565,7 +564,7 @@ func (k Keeper) getAttributeMapping(ctx sdk.Context, key collections.Pair[string
return value.Value, nil
}
func (k Keeper) populateRecordNames(ctx sdk.Context, record *registrytypes.Record) error {
func (k Keeper) populateRecordNames(ctx context.Context, record *registrytypes.Record) error {
iter, err := k.NameRecords.Indexes.Cid.MatchExact(ctx, record.Id)
if err != nil {
return err
@ -581,7 +580,7 @@ func (k Keeper) populateRecordNames(ctx sdk.Context, record *registrytypes.Recor
}
// GetModuleBalances gets the registry module account(s) balances.
func (k Keeper) GetModuleBalances(ctx sdk.Context) []*registrytypes.AccountBalance {
func (k Keeper) GetModuleBalances(ctx context.Context) []*registrytypes.AccountBalance {
var balances []*registrytypes.AccountBalance
accountNames := []string{
registrytypes.RecordRentModuleAccountName,
@ -605,8 +604,8 @@ func (k Keeper) GetModuleBalances(ctx sdk.Context) []*registrytypes.AccountBalan
}
// ProcessRecordExpiryQueue tries to renew expiring records (by collecting rent) else marks them as deleted.
func (k Keeper) ProcessRecordExpiryQueue(ctx sdk.Context) error {
cids, err := k.getAllExpiredRecords(ctx, ctx.BlockHeader().Time)
func (k Keeper) ProcessRecordExpiryQueue(ctx context.Context) error {
cids, err := k.getAllExpiredRecords(ctx, k.HeaderService.HeaderInfo(ctx).Time)
if err != nil {
return err
}
@ -647,7 +646,7 @@ func (k Keeper) ProcessRecordExpiryQueue(ctx sdk.Context) error {
}
// getAllExpiredRecords returns a concatenated list of all the timeslices before currTime.
func (k Keeper) getAllExpiredRecords(ctx sdk.Context, currTime time.Time) ([]string, error) {
func (k Keeper) getAllExpiredRecords(ctx context.Context, currTime time.Time) ([]string, error) {
var expiredRecordCIDs []string
// Get all the records with expiry time until currTime
@ -664,7 +663,7 @@ func (k Keeper) getAllExpiredRecords(ctx sdk.Context, currTime time.Time) ([]str
}
// insertRecordExpiryQueue inserts a record CID to the appropriate timeslice in the record expiry queue.
func (k Keeper) insertRecordExpiryQueue(ctx sdk.Context, record registrytypes.Record) error {
func (k Keeper) insertRecordExpiryQueue(ctx context.Context, record registrytypes.Record) error {
expiryTime, err := time.Parse(time.RFC3339, record.ExpiryTime)
if err != nil {
return err
@ -688,7 +687,7 @@ func (k Keeper) insertRecordExpiryQueue(ctx sdk.Context, record registrytypes.Re
}
// deleteRecordExpiryQueue deletes a record CID from the record expiry queue.
func (k Keeper) deleteRecordExpiryQueue(ctx sdk.Context, record registrytypes.Record) error {
func (k Keeper) deleteRecordExpiryQueue(ctx context.Context, record registrytypes.Record) error {
expiryTime, err := time.Parse(time.RFC3339, record.ExpiryTime)
if err != nil {
return err
@ -715,7 +714,7 @@ func (k Keeper) deleteRecordExpiryQueue(ctx sdk.Context, record registrytypes.Re
}
// tryTakeRecordRent tries to take rent from the record bond.
func (k Keeper) tryTakeRecordRent(ctx sdk.Context, record registrytypes.Record) error {
func (k Keeper) tryTakeRecordRent(ctx context.Context, record registrytypes.Record) error {
params, err := k.GetParams(ctx)
if err != nil {
return err
@ -738,7 +737,7 @@ func (k Keeper) tryTakeRecordRent(ctx sdk.Context, record registrytypes.Record)
return err
}
record.ExpiryTime = ctx.BlockHeader().Time.Add(params.RecordRentDuration).Format(time.RFC3339)
record.ExpiryTime = k.HeaderService.HeaderInfo(ctx).Time.Add(params.RecordRentDuration).Format(time.RFC3339)
if err := k.insertRecordExpiryQueue(ctx, record); err != nil {
return err
}

View File

@ -55,7 +55,7 @@ func (ms msgServer) SetRecord(c context.Context, msg *registrytypes.MsgSetRecord
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "SetRecord")
utils.LogTxGasConsumed(ctx, ms.k.logger, "SetRecord")
return &registrytypes.MsgSetRecordResponse{Id: record.Id}, nil
}
@ -94,7 +94,7 @@ func (ms msgServer) SetName(c context.Context, msg *registrytypes.MsgSetName) (*
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "SetName")
utils.LogTxGasConsumed(ctx, ms.k.logger, "SetName")
return &registrytypes.MsgSetNameResponse{}, nil
}
@ -136,7 +136,7 @@ func (ms msgServer) ReserveAuthority(c context.Context, msg *registrytypes.MsgRe
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "ReserveAuthority")
utils.LogTxGasConsumed(ctx, ms.k.logger, "ReserveAuthority")
return &registrytypes.MsgReserveAuthorityResponse{}, nil
}
@ -175,7 +175,7 @@ func (ms msgServer) SetAuthorityBond(c context.Context, msg *registrytypes.MsgSe
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "SetAuthorityBond")
utils.LogTxGasConsumed(ctx, ms.k.logger, "SetAuthorityBond")
return &registrytypes.MsgSetAuthorityBondResponse{}, nil
}
@ -212,7 +212,7 @@ func (ms msgServer) DeleteName(c context.Context, msg *registrytypes.MsgDeleteNa
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "DeleteName")
utils.LogTxGasConsumed(ctx, ms.k.logger, "DeleteName")
return &registrytypes.MsgDeleteNameResponse{}, nil
}
@ -231,7 +231,7 @@ func (ms msgServer) RenewRecord(c context.Context, msg *registrytypes.MsgRenewRe
return nil, err
}
err = ms.k.RenewRecord(ctx, *msg)
err = ms.k.RenewRecord(ctx, *msg, ms.k.HeaderService.HeaderInfo(c).Time)
if err != nil {
return nil, err
}
@ -249,7 +249,7 @@ func (ms msgServer) RenewRecord(c context.Context, msg *registrytypes.MsgRenewRe
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "RenewRecord")
utils.LogTxGasConsumed(ctx, ms.k.logger, "RenewRecord")
return &registrytypes.MsgRenewRecordResponse{}, nil
}
@ -288,7 +288,7 @@ func (ms msgServer) AssociateBond(c context.Context, msg *registrytypes.MsgAssoc
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "AssociateBond")
utils.LogTxGasConsumed(ctx, ms.k.logger, "AssociateBond")
return &registrytypes.MsgAssociateBondResponse{}, nil
}
@ -325,7 +325,7 @@ func (ms msgServer) DissociateBond(c context.Context, msg *registrytypes.MsgDiss
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "DissociateBond")
utils.LogTxGasConsumed(ctx, ms.k.logger, "DissociateBond")
return &registrytypes.MsgDissociateBondResponse{}, nil
}
@ -365,7 +365,7 @@ func (ms msgServer) DissociateRecords(
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "DissociateRecords")
utils.LogTxGasConsumed(ctx, ms.k.logger, "DissociateRecords")
return &registrytypes.MsgDissociateRecordsResponse{}, nil
}
@ -403,7 +403,7 @@ func (ms msgServer) ReassociateRecords(c context.Context, msg *registrytypes.Msg
),
})
utils.LogTxGasConsumed(ctx, ms.k.Logger(ctx), "ReassociateRecords")
utils.LogTxGasConsumed(ctx, ms.k.logger, "ReassociateRecords")
return &registrytypes.MsgReassociateRecordsResponse{}, nil
}

View File

@ -1,6 +1,7 @@
package keeper
import (
"context"
"errors"
"fmt"
"net/url"
@ -22,7 +23,7 @@ import (
)
// HasNameAuthority - checks if a name/authority exists.
func (k Keeper) HasNameAuthority(ctx sdk.Context, name string) (bool, error) {
func (k Keeper) HasNameAuthority(ctx context.Context, name string) (bool, error) {
has, err := k.Authorities.Has(ctx, name)
if err != nil {
return false, err
@ -32,7 +33,7 @@ func (k Keeper) HasNameAuthority(ctx sdk.Context, name string) (bool, error) {
}
// GetNameAuthority - gets a name authority from the store.
func (k Keeper) GetNameAuthority(ctx sdk.Context, name string) (registrytypes.NameAuthority, error) {
func (k Keeper) GetNameAuthority(ctx context.Context, name string) (registrytypes.NameAuthority, error) {
authority, err := k.Authorities.Get(ctx, name)
if err != nil {
if errors.Is(err, collections.ErrNotFound) {
@ -46,7 +47,7 @@ func (k Keeper) GetNameAuthority(ctx sdk.Context, name string) (registrytypes.Na
// ListNameAuthorityRecords - get all name authority records for given owner
// Returns all authorities if owner set to ""
func (k Keeper) ListNameAuthorityRecords(ctx sdk.Context, owner string) ([]registrytypes.AuthorityEntry, error) {
func (k Keeper) ListNameAuthorityRecords(ctx context.Context, owner string) ([]registrytypes.AuthorityEntry, error) {
authorityEntries := []registrytypes.AuthorityEntry{}
err := k.Authorities.Walk(ctx, nil, func(key string, value registrytypes.NameAuthority) (bool, error) {
@ -71,12 +72,12 @@ func (k Keeper) ListNameAuthorityRecords(ctx sdk.Context, owner string) ([]regis
}
// HasNameRecord - checks if a name record exists.
func (k Keeper) HasNameRecord(ctx sdk.Context, lrn string) (bool, error) {
func (k Keeper) HasNameRecord(ctx context.Context, lrn string) (bool, error) {
return k.NameRecords.Has(ctx, lrn)
}
// GetNameRecord - gets a name record from the store.
func (k Keeper) GetNameRecord(ctx sdk.Context, lrn string) (*registrytypes.NameRecord, error) {
func (k Keeper) GetNameRecord(ctx context.Context, lrn string) (*registrytypes.NameRecord, error) {
nameRecord, err := k.NameRecords.Get(ctx, lrn)
if err != nil {
if errors.Is(err, collections.ErrNotFound) {
@ -89,7 +90,7 @@ func (k Keeper) GetNameRecord(ctx sdk.Context, lrn string) (*registrytypes.NameR
}
// LookupNameRecord - gets a name record which is not stale and under active authority.
func (k Keeper) LookupNameRecord(ctx sdk.Context, lrn string) (*registrytypes.NameRecord, error) {
func (k Keeper) LookupNameRecord(ctx context.Context, lrn string) (*registrytypes.NameRecord, error) {
_, _, authority, err := k.getAuthority(ctx, lrn)
if err != nil || authority.Status != registrytypes.AuthorityActive {
// If authority is not active (or any other error), lookup fails.
@ -113,7 +114,7 @@ func (k Keeper) LookupNameRecord(ctx sdk.Context, lrn string) (*registrytypes.Na
}
// ListNameRecords - get all name records.
func (k Keeper) ListNameRecords(ctx sdk.Context) ([]registrytypes.NameEntry, error) {
func (k Keeper) ListNameRecords(ctx context.Context) ([]registrytypes.NameEntry, error) {
var nameEntries []registrytypes.NameEntry
err := k.NameRecords.Walk(ctx, nil, func(key string, value registrytypes.NameRecord) (stop bool, err error) {
@ -129,7 +130,7 @@ func (k Keeper) ListNameRecords(ctx sdk.Context) ([]registrytypes.NameEntry, err
}
// SaveNameRecord - sets a name record.
func (k Keeper) SaveNameRecord(ctx sdk.Context, lrn string, id string) error {
func (k Keeper) SaveNameRecord(ctx context.Context, lrn string, id string) error {
var nameRecord registrytypes.NameRecord
existingNameRecord, err := k.GetNameRecord(ctx, lrn)
if err != nil {
@ -143,14 +144,14 @@ func (k Keeper) SaveNameRecord(ctx sdk.Context, lrn string, id string) error {
nameRecord.Latest = &registrytypes.NameRecordEntry{
Id: id,
Height: uint64(ctx.BlockHeight()),
Height: uint64(k.HeaderService.HeaderInfo(ctx).Height),
}
return k.NameRecords.Set(ctx, lrn, nameRecord)
}
// SetName creates a LRN -> Record ID mapping.
func (k Keeper) SetName(ctx sdk.Context, msg registrytypes.MsgSetName) error {
func (k Keeper) SetName(ctx context.Context, msg registrytypes.MsgSetName) error {
signerAddress, err := utils.NewAddressCodec().StringToBytes(msg.Signer)
if err != nil {
return err
@ -172,12 +173,12 @@ func (k Keeper) SetName(ctx sdk.Context, msg registrytypes.MsgSetName) error {
}
// SaveNameAuthority creates the NameAuthority record.
func (k Keeper) SaveNameAuthority(ctx sdk.Context, name string, authority *registrytypes.NameAuthority) error {
func (k Keeper) SaveNameAuthority(ctx context.Context, name string, authority *registrytypes.NameAuthority) error {
return k.Authorities.Set(ctx, name, *authority)
}
// ReserveAuthority reserves a name authority.
func (k Keeper) ReserveAuthority(ctx sdk.Context, msg registrytypes.MsgReserveAuthority) error {
func (k Keeper) ReserveAuthority(ctx context.Context, msg registrytypes.MsgReserveAuthority) error {
lrn := fmt.Sprintf("lrn://%s", msg.GetName())
parsedLrn, err := url.Parse(lrn)
if err != nil {
@ -202,7 +203,7 @@ func (k Keeper) ReserveAuthority(ctx sdk.Context, msg registrytypes.MsgReserveAu
}
// ReserveSubAuthority reserves a sub-authority.
func (k Keeper) ReserveSubAuthority(ctx sdk.Context, name string, msg registrytypes.MsgReserveAuthority) error {
func (k Keeper) ReserveSubAuthority(ctx context.Context, name string, msg registrytypes.MsgReserveAuthority) error {
// Get parent authority name.
names := strings.Split(name, ".")
parent := strings.Join(names[1:], ".")
@ -240,7 +241,7 @@ func (k Keeper) ReserveSubAuthority(ctx sdk.Context, name string, msg registryty
return nil
}
func (k Keeper) createAuthority(ctx sdk.Context, name string, owner string, isRoot bool) error {
func (k Keeper) createAuthority(ctx context.Context, name string, owner string, isRoot bool) error {
moduleParams, err := k.GetParams(ctx)
if err != nil {
return err
@ -270,14 +271,15 @@ func (k Keeper) createAuthority(ctx sdk.Context, name string, owner string, isRo
return errorsmod.Wrap(sdkerrors.ErrUnknownAddress, "Owner account not found.")
}
headerInfo := k.HeaderService.HeaderInfo(ctx)
authority := registrytypes.NameAuthority{
OwnerPublicKey: getAuthorityPubKey(ownerAccount.GetPubKey()),
OwnerAddress: owner,
Height: uint64(ctx.BlockHeight()),
Height: uint64(headerInfo.Height),
Status: registrytypes.AuthorityActive,
AuctionId: "",
BondId: "",
ExpiryTime: ctx.BlockTime().Add(moduleParams.AuthorityGracePeriod),
ExpiryTime: headerInfo.Time.Add(moduleParams.AuthorityGracePeriod),
}
if isRoot && moduleParams.AuthorityAuctionEnabled {
@ -319,7 +321,7 @@ func (k Keeper) createAuthority(ctx sdk.Context, name string, owner string, isRo
return k.insertAuthorityExpiryQueue(ctx, name, authority.ExpiryTime)
}
func (k Keeper) SetAuthorityBond(ctx sdk.Context, msg registrytypes.MsgSetAuthorityBond) error {
func (k Keeper) SetAuthorityBond(ctx context.Context, msg registrytypes.MsgSetAuthorityBond) error {
name := msg.GetName()
signer := msg.GetSigner()
@ -369,7 +371,7 @@ func (k Keeper) SetAuthorityBond(ctx sdk.Context, msg registrytypes.MsgSetAuthor
}
// DeleteName removes a LRN -> Record ID mapping.
func (k Keeper) DeleteName(ctx sdk.Context, msg registrytypes.MsgDeleteName) error {
func (k Keeper) DeleteName(ctx context.Context, msg registrytypes.MsgDeleteName) error {
signerAddress, err := utils.NewAddressCodec().StringToBytes(msg.Signer)
if err != nil {
return err
@ -392,7 +394,7 @@ func (k Keeper) DeleteName(ctx sdk.Context, msg registrytypes.MsgDeleteName) err
}
// ResolveLRN resolves a LRN to a record.
func (k Keeper) ResolveLRN(ctx sdk.Context, lrn string) (*registrytypes.Record, error) {
func (k Keeper) ResolveLRN(ctx context.Context, lrn string) (*registrytypes.Record, error) {
_, _, authority, err := k.getAuthority(ctx, lrn)
if err != nil || authority.Status != registrytypes.AuthorityActive {
// If authority is not active (or any other error), resolution fails.
@ -412,7 +414,7 @@ func (k Keeper) ResolveLRN(ctx sdk.Context, lrn string) (*registrytypes.Record,
return record, nil
}
func (k Keeper) resolveLRNRecord(ctx sdk.Context, lrn string) (*registrytypes.Record, *registrytypes.NameRecord, error) {
func (k Keeper) resolveLRNRecord(ctx context.Context, lrn string) (*registrytypes.Record, *registrytypes.NameRecord, error) {
nameRecord, err := k.GetNameRecord(ctx, lrn)
if nameRecord == nil {
return nil, nil, err
@ -439,7 +441,7 @@ func (k Keeper) resolveLRNRecord(ctx sdk.Context, lrn string) (*registrytypes.Re
return &record, nameRecord, nil
}
func (k Keeper) getAuthority(ctx sdk.Context, lrn string) (string, *url.URL, *registrytypes.NameAuthority, error) {
func (k Keeper) getAuthority(ctx context.Context, lrn string) (string, *url.URL, *registrytypes.NameAuthority, error) {
parsedLRN, err := url.Parse(lrn)
if err != nil {
return "", nil, nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Invalid LRN.")
@ -462,7 +464,7 @@ func (k Keeper) getAuthority(ctx sdk.Context, lrn string) (string, *url.URL, *re
return name, parsedLRN, &authority, nil
}
func (k Keeper) checkLRNAccess(ctx sdk.Context, signer sdk.AccAddress, lrn string) error {
func (k Keeper) checkLRNAccess(ctx context.Context, signer sdk.AccAddress, lrn string) error {
name, parsedLRN, authority, err := k.getAuthority(ctx, lrn)
if err != nil {
return err
@ -502,8 +504,8 @@ func (k Keeper) checkLRNAccess(ctx sdk.Context, signer sdk.AccAddress, lrn strin
}
// ProcessAuthorityExpiryQueue tries to renew expiring authorities (by collecting rent) else marks them as expired.
func (k Keeper) ProcessAuthorityExpiryQueue(ctx sdk.Context) error {
names, err := k.getAllExpiredAuthorities(ctx, ctx.BlockHeader().Time)
func (k Keeper) ProcessAuthorityExpiryQueue(ctx context.Context) error {
names, err := k.getAllExpiredAuthorities(ctx, k.HeaderService.HeaderInfo(ctx).Time)
if err != nil {
return err
}
@ -533,7 +535,7 @@ func (k Keeper) ProcessAuthorityExpiryQueue(ctx sdk.Context) error {
return err
}
k.Logger(ctx).Info(fmt.Sprintf("Marking authority expired as no bond present: %s", name))
k.logger.Info(fmt.Sprintf("Marking authority expired as no bond present: %s", name))
// Continue with the loop
continue
@ -549,7 +551,7 @@ func (k Keeper) ProcessAuthorityExpiryQueue(ctx sdk.Context) error {
}
// getAllExpiredAuthorities returns a concatenated list of all the timeslices before currTime.
func (k Keeper) getAllExpiredAuthorities(ctx sdk.Context, currTime time.Time) ([]string, error) {
func (k Keeper) getAllExpiredAuthorities(ctx context.Context, currTime time.Time) ([]string, error) {
var expiredAuthorityNames []string
// Get all the authorities with expiry time until currTime
@ -565,7 +567,7 @@ func (k Keeper) getAllExpiredAuthorities(ctx sdk.Context, currTime time.Time) ([
return expiredAuthorityNames, nil
}
func (k Keeper) insertAuthorityExpiryQueue(ctx sdk.Context, name string, expiryTime time.Time) error {
func (k Keeper) insertAuthorityExpiryQueue(ctx context.Context, name string, expiryTime time.Time) error {
existingNamesList, err := k.AuthorityExpiryQueue.Get(ctx, expiryTime)
if err != nil {
if errors.Is(err, collections.ErrNotFound) {
@ -583,7 +585,7 @@ func (k Keeper) insertAuthorityExpiryQueue(ctx sdk.Context, name string, expiryT
}
// deleteAuthorityExpiryQueue deletes an authority name from the authority expiry queue.
func (k Keeper) deleteAuthorityExpiryQueue(ctx sdk.Context, name string, authority registrytypes.NameAuthority) error {
func (k Keeper) deleteAuthorityExpiryQueue(ctx context.Context, name string, authority registrytypes.NameAuthority) error {
expiryTime := authority.ExpiryTime
existingNamesList, err := k.AuthorityExpiryQueue.Get(ctx, expiryTime)
@ -611,8 +613,8 @@ func (k Keeper) deleteAuthorityExpiryQueue(ctx sdk.Context, name string, authori
}
// tryTakeAuthorityRent tries to take rent from the authority bond.
func (k Keeper) tryTakeAuthorityRent(ctx sdk.Context, name string, authority registrytypes.NameAuthority) error {
k.Logger(ctx).Info(fmt.Sprintf("Trying to take rent for authority: %s", name))
func (k Keeper) tryTakeAuthorityRent(ctx context.Context, name string, authority registrytypes.NameAuthority) error {
k.logger.Info(fmt.Sprintf("Trying to take rent for authority: %s", name))
params, err := k.GetParams(ctx)
if err != nil {
@ -628,7 +630,7 @@ func (k Keeper) tryTakeAuthorityRent(ctx sdk.Context, name string, authority reg
return err
}
k.Logger(ctx).Info(fmt.Sprintf("Insufficient funds in owner account to pay authority rent, marking as expired: %s", name))
k.logger.Info(fmt.Sprintf("Insufficient funds in owner account to pay authority rent, marking as expired: %s", name))
return k.deleteAuthorityExpiryQueue(ctx, name, authority)
}
@ -638,7 +640,7 @@ func (k Keeper) tryTakeAuthorityRent(ctx sdk.Context, name string, authority reg
return err
}
authority.ExpiryTime = ctx.BlockTime().Add(params.AuthorityRentDuration)
authority.ExpiryTime = k.HeaderService.HeaderInfo(ctx).Time.Add(params.AuthorityRentDuration)
if err := k.insertAuthorityExpiryQueue(ctx, name, authority.ExpiryTime); err != nil {
return err
}
@ -646,7 +648,7 @@ func (k Keeper) tryTakeAuthorityRent(ctx sdk.Context, name string, authority reg
// Save authority.
authority.Status = registrytypes.AuthorityActive
k.Logger(ctx).Info(fmt.Sprintf("Authority rent paid successfully: %s", name))
k.logger.Info(fmt.Sprintf("Authority rent paid successfully: %s", name))
return k.SaveNameAuthority(ctx, name, &authority)
}

View File

@ -4,7 +4,6 @@ import (
"context"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/query"
@ -22,9 +21,7 @@ func NewQueryServerImpl(k Keeper) registrytypes.QueryServer {
return queryServer{k}
}
func (qs queryServer) Params(c context.Context, _ *registrytypes.QueryParamsRequest) (*registrytypes.QueryParamsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) Params(ctx context.Context, _ *registrytypes.QueryParamsRequest) (*registrytypes.QueryParamsResponse, error) {
params, err := qs.k.GetParams(ctx)
if err != nil {
return nil, err
@ -33,9 +30,7 @@ func (qs queryServer) Params(c context.Context, _ *registrytypes.QueryParamsRequ
return &registrytypes.QueryParamsResponse{Params: params}, nil
}
func (qs queryServer) Records(c context.Context, req *registrytypes.QueryRecordsRequest) (*registrytypes.QueryRecordsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) Records(ctx context.Context, req *registrytypes.QueryRecordsRequest) (*registrytypes.QueryRecordsResponse, error) {
attributes := req.GetAttributes()
all := req.GetAll()
@ -57,8 +52,7 @@ func (qs queryServer) Records(c context.Context, req *registrytypes.QueryRecords
return &registrytypes.QueryRecordsResponse{Records: records, Pagination: pageResp}, nil
}
func (qs queryServer) GetRecord(c context.Context, req *registrytypes.QueryGetRecordRequest) (*registrytypes.QueryGetRecordResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) GetRecord(ctx context.Context, req *registrytypes.QueryGetRecordRequest) (*registrytypes.QueryGetRecordResponse, error) {
id := req.GetId()
if has, err := qs.k.HasRecord(ctx, req.Id); !has {
@ -78,11 +72,9 @@ func (qs queryServer) GetRecord(c context.Context, req *registrytypes.QueryGetRe
}
func (qs queryServer) GetRecordsByBondId(
c context.Context,
ctx context.Context,
req *registrytypes.QueryGetRecordsByBondIdRequest,
) (*registrytypes.QueryGetRecordsByBondIdResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
records, err := qs.k.GetRecordsByBondId(ctx, req.GetId())
if err != nil {
return nil, err
@ -91,11 +83,9 @@ func (qs queryServer) GetRecordsByBondId(
return &registrytypes.QueryGetRecordsByBondIdResponse{Records: records}, nil
}
func (qs queryServer) GetRegistryModuleBalance(c context.Context,
func (qs queryServer) GetRegistryModuleBalance(ctx context.Context,
_ *registrytypes.QueryGetRegistryModuleBalanceRequest,
) (*registrytypes.QueryGetRegistryModuleBalanceResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
balances := qs.k.GetModuleBalances(ctx)
return &registrytypes.QueryGetRegistryModuleBalanceResponse{
@ -103,9 +93,7 @@ func (qs queryServer) GetRegistryModuleBalance(c context.Context,
}, nil
}
func (qs queryServer) NameRecords(c context.Context, _ *registrytypes.QueryNameRecordsRequest) (*registrytypes.QueryNameRecordsResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) NameRecords(ctx context.Context, _ *registrytypes.QueryNameRecordsRequest) (*registrytypes.QueryNameRecordsResponse, error) {
nameRecords, err := qs.k.ListNameRecords(ctx)
if err != nil {
return nil, err
@ -114,9 +102,7 @@ func (qs queryServer) NameRecords(c context.Context, _ *registrytypes.QueryNameR
return &registrytypes.QueryNameRecordsResponse{Names: nameRecords}, nil
}
func (qs queryServer) Whois(c context.Context, req *registrytypes.QueryWhoisRequest) (*registrytypes.QueryWhoisResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) Whois(ctx context.Context, req *registrytypes.QueryWhoisRequest) (*registrytypes.QueryWhoisResponse, error) {
nameAuthority, err := qs.k.GetNameAuthority(ctx, req.GetName())
if err != nil {
return nil, err
@ -125,9 +111,7 @@ func (qs queryServer) Whois(c context.Context, req *registrytypes.QueryWhoisRequ
return &registrytypes.QueryWhoisResponse{NameAuthority: nameAuthority}, nil
}
func (qs queryServer) Authorities(c context.Context, req *registrytypes.QueryAuthoritiesRequest) (*registrytypes.QueryAuthoritiesResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) Authorities(ctx context.Context, req *registrytypes.QueryAuthoritiesRequest) (*registrytypes.QueryAuthoritiesResponse, error) {
authorityEntries, err := qs.k.ListNameAuthorityRecords(ctx, req.GetOwner())
if err != nil {
return nil, err
@ -136,8 +120,7 @@ func (qs queryServer) Authorities(c context.Context, req *registrytypes.QueryAut
return &registrytypes.QueryAuthoritiesResponse{Authorities: authorityEntries}, nil
}
func (qs queryServer) LookupLrn(c context.Context, req *registrytypes.QueryLookupLrnRequest) (*registrytypes.QueryLookupLrnResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) LookupLrn(ctx context.Context, req *registrytypes.QueryLookupLrnRequest) (*registrytypes.QueryLookupLrnResponse, error) {
lrn := req.GetLrn()
lrnExists, err := qs.k.HasNameRecord(ctx, lrn)
@ -160,9 +143,7 @@ func (qs queryServer) LookupLrn(c context.Context, req *registrytypes.QueryLooku
return &registrytypes.QueryLookupLrnResponse{Name: nameRecord}, nil
}
func (qs queryServer) ResolveLrn(c context.Context, req *registrytypes.QueryResolveLrnRequest) (*registrytypes.QueryResolveLrnResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
func (qs queryServer) ResolveLrn(ctx context.Context, req *registrytypes.QueryResolveLrnRequest) (*registrytypes.QueryResolveLrnResponse, error) {
lrn := req.GetLrn()
record, err := qs.k.ResolveLRN(ctx, lrn)
if record == nil {

View File

@ -8,8 +8,8 @@ import (
"cosmossdk.io/collections"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/log"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
auctiontypes "git.vdb.to/cerc-io/laconicd/x/auction"
@ -29,14 +29,21 @@ type RecordKeeper struct {
cdc codec.BinaryCodec // The wire codec for binary encoding/decoding.
k *Keeper
auctionKeeper *auctionkeeper.Keeper
logger log.Logger
}
// NewRecordKeeper creates new instances of the registry RecordKeeper
func NewRecordKeeper(cdc codec.BinaryCodec, k *Keeper, auctionKeeper *auctionkeeper.Keeper) RecordKeeper {
func NewRecordKeeper(
cdc codec.BinaryCodec,
k *Keeper,
auctionKeeper *auctionkeeper.Keeper,
logger log.Logger,
) RecordKeeper {
return RecordKeeper{
cdc: cdc,
k: k,
auctionKeeper: auctionKeeper,
logger: logger.With(log.ModuleKey, "x/"+registrytypes.ModuleName),
}
}
@ -45,7 +52,7 @@ func (rk RecordKeeper) ModuleName() string {
return registrytypes.ModuleName
}
func (rk RecordKeeper) UsesAuction(ctx sdk.Context, auctionId string) bool {
func (rk RecordKeeper) UsesAuction(ctx context.Context, auctionId string) bool {
iter, err := rk.k.Authorities.Indexes.AuctionId.MatchExact(ctx, auctionId)
if err != nil {
panic(err)
@ -54,7 +61,7 @@ func (rk RecordKeeper) UsesAuction(ctx sdk.Context, auctionId string) bool {
return iter.Valid()
}
func (rk RecordKeeper) OnAuctionWinnerSelected(ctx sdk.Context, auctionId string) {
func (rk RecordKeeper) OnAuctionWinnerSelected(ctx context.Context, auctionId string, blockHeight uint64) {
// Update authority status based on auction status/winner.
iter, err := rk.k.Authorities.Indexes.AuctionId.MatchExact(ctx, auctionId)
if err != nil && !errors.Is(err, collections.ErrNotFound) {
@ -67,7 +74,7 @@ func (rk RecordKeeper) OnAuctionWinnerSelected(ctx sdk.Context, auctionId string
if len(names) == 0 {
// We don't know about this auction, ignore.
logger(ctx).Info(fmt.Sprintf("Ignoring auction notification, name mapping not found: %s", auctionId))
rk.logger.Info(fmt.Sprintf("Ignoring auction notification, name mapping not found: %s", auctionId))
return
}
@ -80,7 +87,7 @@ func (rk RecordKeeper) OnAuctionWinnerSelected(ctx sdk.Context, auctionId string
}
// We don't know about this authority, ignore.
logger(ctx).Info(fmt.Sprintf("Ignoring auction notification, authority not found: %s", auctionId))
rk.logger.Info(fmt.Sprintf("Ignoring auction notification, authority not found: %s", auctionId))
return
}
@ -105,17 +112,17 @@ func (rk RecordKeeper) OnAuctionWinnerSelected(ctx sdk.Context, auctionId string
// Update height for updated/changed authority (owner).
// Can be used to check if names are older than the authority itself (stale names).
authority.Height = uint64(ctx.BlockHeight())
authority.Height = blockHeight
logger(ctx).Info(fmt.Sprintf("Winner selected, marking authority as active: %s", name))
rk.logger.Info(fmt.Sprintf("Winner selected, marking authority as active: %s", name))
} else {
// Mark as expired.
authority.Status = registrytypes.AuthorityExpired
logger(ctx).Info(fmt.Sprintf("No winner, marking authority as expired: %s", name))
rk.logger.Info(fmt.Sprintf("No winner, marking authority as expired: %s", name))
logger(ctx).Info(fmt.Sprintf("Deleting the expiry queue entry: %s", name))
rk.logger.Info(fmt.Sprintf("Deleting the expiry queue entry: %s", name))
if err = rk.k.deleteAuthorityExpiryQueue(ctx, name, authority); err != nil {
logger(ctx).Error("Unable to delete expiry queue entry", err)
rk.logger.Error("Unable to delete expiry queue entry", err)
}
}
@ -126,7 +133,7 @@ func (rk RecordKeeper) OnAuctionWinnerSelected(ctx sdk.Context, auctionId string
panic(err)
}
} else {
logger(ctx).Info(fmt.Sprintf("Ignoring auction notification, status: %s", auctionObj.Status))
rk.logger.Info(fmt.Sprintf("Ignoring auction notification, status: %s", auctionObj.Status))
}
}
@ -141,7 +148,7 @@ func (rk RecordKeeper) UsesBond(ctx context.Context, bondId string) bool {
}
// RenewRecord renews a record.
func (k Keeper) RenewRecord(ctx sdk.Context, msg registrytypes.MsgRenewRecord) error {
func (k Keeper) RenewRecord(ctx context.Context, msg registrytypes.MsgRenewRecord, now time.Time) error {
if has, err := k.HasRecord(ctx, msg.RecordId); !has {
if err != nil {
return err
@ -160,7 +167,7 @@ func (k Keeper) RenewRecord(ctx sdk.Context, msg registrytypes.MsgRenewRecord) e
return err
}
if !record.Deleted || expiryTime.After(ctx.BlockTime()) {
if !record.Deleted || expiryTime.After(now) {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "Renewal not required.")
}
@ -169,7 +176,7 @@ func (k Keeper) RenewRecord(ctx sdk.Context, msg registrytypes.MsgRenewRecord) e
}
// AssociateBond associates a record with a bond.
func (k Keeper) AssociateBond(ctx sdk.Context, msg registrytypes.MsgAssociateBond) error {
func (k Keeper) AssociateBond(ctx context.Context, msg registrytypes.MsgAssociateBond) error {
if has, err := k.HasRecord(ctx, msg.RecordId); !has {
if err != nil {
return err
@ -217,7 +224,7 @@ func (k Keeper) AssociateBond(ctx sdk.Context, msg registrytypes.MsgAssociateBon
}
// DissociateBond dissociates a record from its bond.
func (k Keeper) DissociateBond(ctx sdk.Context, msg registrytypes.MsgDissociateBond) error {
func (k Keeper) DissociateBond(ctx context.Context, msg registrytypes.MsgDissociateBond) error {
if has, err := k.HasRecord(ctx, msg.RecordId); !has {
if err != nil {
return err
@ -251,7 +258,7 @@ func (k Keeper) DissociateBond(ctx sdk.Context, msg registrytypes.MsgDissociateB
}
// DissociateRecords dissociates all records associated with a given bond.
func (k Keeper) DissociateRecords(ctx sdk.Context, msg registrytypes.MsgDissociateRecords) error {
func (k Keeper) DissociateRecords(ctx context.Context, msg registrytypes.MsgDissociateRecords) error {
if has, err := k.bondKeeper.HasBond(ctx, msg.BondId); !has {
if err != nil {
return err
@ -286,7 +293,7 @@ func (k Keeper) DissociateRecords(ctx sdk.Context, msg registrytypes.MsgDissocia
}
// ReassociateRecords switches records from and old to new bond.
func (k Keeper) ReassociateRecords(ctx sdk.Context, msg registrytypes.MsgReassociateRecords) error {
func (k Keeper) ReassociateRecords(ctx context.Context, msg registrytypes.MsgReassociateRecords) error {
if has, err := k.bondKeeper.HasBond(ctx, msg.OldBondId); !has {
if err != nil {
return err

View File

@ -3,20 +3,16 @@ package module
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
"git.vdb.to/cerc-io/laconicd/x/registry/keeper"
)
// EndBlocker is called every block
func EndBlocker(ctx context.Context, k keeper.Keeper) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
if err := k.ProcessRecordExpiryQueue(sdkCtx); err != nil {
if err := k.ProcessRecordExpiryQueue(ctx); err != nil {
return err
}
if err := k.ProcessAuthorityExpiryQueue(sdkCtx); err != nil {
if err := k.ProcessAuthorityExpiryQueue(ctx); err != nil {
return err
}

View File

@ -2,9 +2,9 @@ package module
import (
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/store"
"cosmossdk.io/depinject"
"cosmossdk.io/depinject/appconfig"
"cosmossdk.io/log"
bank "cosmossdk.io/x/bank/keeper"
govtypes "cosmossdk.io/x/gov/types"
"github.com/cosmos/cosmos-sdk/codec"
@ -37,9 +37,10 @@ func init() {
type ModuleInputs struct {
depinject.In
Config *modulev1.Module
Cdc codec.Codec
StoreService store.KVStoreService
Env appmodule.Environment
Config *modulev1.Module
Cdc codec.Codec
Logger log.Logger
AccountKeeper auth.AccountKeeper
BankKeeper bank.Keeper
@ -65,17 +66,18 @@ func ProvideModule(in ModuleInputs) ModuleOutputs {
authority = authtypes.NewModuleAddressOrBech32Address(in.Config.Authority)
}
k := keeper.NewKeeper(
in.Env,
in.Cdc,
in.StoreService,
in.AccountKeeper,
in.BankKeeper,
in.BondKeeper,
in.AuctionKeeper,
authority.String(),
in.Logger,
)
m := NewAppModule(in.Cdc, k)
recordKeeper := keeper.NewRecordKeeper(in.Cdc, &k, in.AuctionKeeper)
recordKeeper := keeper.NewRecordKeeper(in.Cdc, &k, in.AuctionKeeper, in.Logger)
return ModuleOutputs{
Module: m, Keeper: k,