github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/x/supply/internal/keeper/keeper.go (about) 1 package keeper 2 3 import ( 4 "fmt" 5 6 "github.com/fibonacci-chain/fbc/libs/tendermint/libs/log" 7 8 "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/codec" 9 sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types" 10 "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/supply/exported" 11 "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/x/supply/internal/types" 12 ) 13 14 // Keeper of the supply store 15 type Keeper struct { 16 cdc *codec.Codec 17 storeKey sdk.StoreKey 18 ak types.AccountKeeper 19 bk types.BankKeeper 20 permAddrs map[string]types.PermissionsForAddress 21 } 22 23 // NewKeeper creates a new Keeper instance 24 func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, ak types.AccountKeeper, bk types.BankKeeper, maccPerms map[string][]string) Keeper { 25 // set the addresses 26 permAddrs := make(map[string]types.PermissionsForAddress) 27 for name, perms := range maccPerms { 28 permAddrs[name] = types.NewPermissionsForAddress(name, perms) 29 } 30 31 return Keeper{ 32 cdc: cdc, 33 storeKey: key, 34 ak: ak, 35 bk: bk, 36 permAddrs: permAddrs, 37 } 38 } 39 40 // Logger returns a module-specific logger. 41 func (k Keeper) Logger(ctx sdk.Context) log.Logger { 42 return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) 43 } 44 45 // GetSupply retrieves the Supply from store 46 func (k Keeper) GetSupply(ctx sdk.Context) (supply exported.SupplyI) { 47 store := ctx.KVStore(k.storeKey) 48 iterator := sdk.KVStorePrefixIterator(store, SupplyKey) 49 defer iterator.Close() 50 51 var totalSupply types.Supply 52 for ; iterator.Valid(); iterator.Next() { 53 var amount sdk.Dec 54 k.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &amount) 55 totalSupply.Total = append(totalSupply.Total, sdk.NewCoin(string(iterator.Key()[1:]), amount)) 56 } 57 58 return totalSupply 59 } 60 61 // SetSupply sets the Supply to store 62 func (k Keeper) SetSupply(ctx sdk.Context, supply exported.SupplyI) { 63 tokensSupply := supply.GetTotal() 64 for i := 0; i < len(tokensSupply); i++ { 65 k.setTokenSupplyAmount(ctx, tokensSupply[i].Denom, tokensSupply[i].Amount) 66 } 67 } 68 69 // ValidatePermissions validates that the module account has been granted 70 // permissions within its set of allowed permissions. 71 func (k Keeper) ValidatePermissions(macc exported.ModuleAccountI) error { 72 permAddr := k.permAddrs[macc.GetName()] 73 for _, perm := range macc.GetPermissions() { 74 if !permAddr.HasPermission(perm) { 75 return fmt.Errorf("invalid module permission %s", perm) 76 } 77 } 78 return nil 79 } 80 81 // setTokenSupplyAmount sets the supply amount of a token to the store 82 func (k Keeper) setTokenSupplyAmount(ctx sdk.Context, tokenSymbol string, supplyAmount sdk.Dec) { 83 ctx.KVStore(k.storeKey).Set(getTokenSupplyKey(tokenSymbol), k.cdc.MustMarshalBinaryLengthPrefixed(supplyAmount)) 84 }