Cosmos Hub 백서

Cosmos Hub

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 7쪽

) type Keeper struct { Schema collections.Schema Balances collections.Map[collections.Pair[sdk.AccAddress, string], math.Int] } func NewKeeper(storeService store.KVStoreService) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Balances: collections.NewMap( sb, BalancesPrefix, "balances", collections.PairKeyCodec(sdk.AccAddressKey, collections.StringKey), sdk.IntValue, ), } } ``` #### The Map Key definition First of all we can see that in order to define a composite key of two elements we use the `collections.Pair` type: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} collections.Map[collections.Pair[sdk.AccAddress, string], math.Int] ``` `collections.Pair` defines a key composed of two other keys, in our case the first part is `sdk.AccAddress`, the second part is `string`. #### The Key Codec instantiation The arguments to instantiate are always the same, the only thing that changes is how we instantiate the `KeyCodec`, since this key is composed of two keys we use `collections.PairKeyCodec`, which generates a `KeyCodec` composed of two key codecs. The first one will encode the first part of the key, the second one will encode the second part of the key. ### Working with composite key collections Let's expand on the example we used before: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} var BalancesPrefix = collections.NewPrefix(1) type Keeper struct { Schema collections.Schema Balances collections.Map[collections.Pair[sdk.AccAddress, string], math.Int] } func NewKeeper(storeService store.KVStoreService) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Balances: collections.NewMap( sb, BalancesPrefix, "balances", collections.PairKeyCodec(sdk.AccAddressKey, collections.StringKey), sdk.IntValue, ), } } func (k Keeper) SetBalance(ctx sdk.Context, address sdk.AccAddress, denom string, amount math.Int) error { key := collections.Join(address, denom) return k.Balances.Set(ctx, key, amount) } func (k Keeper) GetBalance(ctx sdk.Context, address sdk.AccAddress, denom string) (math.Int, error) { return k.Balances.Get(ctx, collections.Join(address, denom)) } func (k Keeper) GetAllAddressBalances(ctx sdk.Context, address sdk.AccAddress) (sdk.Coins, error) { balances := sdk.NewCoins() rng := collections.NewPrefixedPairRange[sdk.AccAddress, string](address) iter, err := k.Balances.Iterate(ctx, rng) if err != nil { return nil, err } kvs, err := iter.KeyValues() if err != nil { return nil, err } for _, kv := range kvs { balances = balances.Add(sdk.NewCoin(kv.Key.K2(), kv.Value)) } return balances, nil } func (k Keeper) GetAllAddressBalancesBetween(ctx sdk.Context, address sdk.AccAddress, startDenom, endDenom string) (sdk.Coins, error) { rng := collections.NewPrefixedPairRange[sdk.AccAddress, string](address). StartInclusive(startDenom). EndInclusive(endDenom) iter, err := k.Balances.Iterate(ctx, rng) if err != nil { return nil, err } ... } ``` #### SetBalance As we can see here we're setting the balance of an address for a specific denom. We use the `collections.Join` function to generate the composite key. `collections.Join` returns a `collections.Pair` (which is the key of our `collections.Map`) `collections.Pair` contains the two keys we have joined, it also exposes two methods: `K1` to fetch the 1st part of the key and `K2` to fetch the second part. As always, we use the `collections.Map.Set` method to map the composite key to our value (`math.Int` in this case) #### GetBalance To get a value in composite key collection, we simply use `collections.Join` to compose the key. #### GetAllAddressBalances We use `collections.PrefixedPairRange` to iterate over all the keys starting with the provided address. Concretely the iteration will report all the balances belonging to the provided address. The first part is that we instantiate a `PrefixedPairRange`, which is a `Ranger` implementer aimed to help in `Pair` keys iterations. ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} rng := collections.NewPrefixedPairRange[sdk.AccAddress, string](address) ``` As we can see here we're passing the type parameters of the `collections.Pair` because golang type inference with respect to generics is not as permissive as other languages, so we need to explicitly say what are the types of the pair key. #### GetAllAddressesBalancesBetween This showcases how we can further specialize our range to limit the results further, by specifying the range between the second part of the key (in our case the denoms, which are strings). ## IndexedMap `collections.IndexedMap` is a collection that uses under the hood a `collections.Map`, and has a struct, which contains the indexes that we need to define. ### Example Let's say we have an `auth.BaseAccount` struct which looks like the following: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type BaseAccount struct { AccountNumber uint64 `protobuf:"varint,3,opt,name=account_number,json=accountNumber,proto3" json:"account_number,omitempty"` Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` } ``` First of all, when we save our accounts in state we map them using a primary key `sdk.AccAddress`. If it were to be a `collections.Map` it would be `collections.Map[sdk.AccAddress, authtypes.BaseAccount]`. Then we also want to be able to get an account not only by its `sdk.AccAddress`, but also by its `AccountNumber`. So we can say we want to create an `Index` that maps our `BaseAccount` to its `AccountNumber`. We also know that this `Index` is unique. Unique means that there can only be one `BaseAccount` that maps to a specific `AccountNumber`. First of all, we start by defining the object that contains our index: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} var AccountsNumberIndexPrefix = collections.NewPrefix(1) type AccountsIndexes struct { Number *indexes.Unique[uint64, sdk.AccAddress, authtypes.BaseAccount] } func NewAccountIndexes(sb *collections.SchemaBuilder) AccountsIndexes { return AccountsIndexes{ Number: indexes.NewUnique( sb, AccountsNumberIndexPrefix, "accounts_by_number", collections.Uint64Key, sdk.AccAddressKey, func(_ sdk.AccAddress, v authtypes.BaseAccount) (uint64, error) { return v.AccountNumber, nil }, ), } } ``` We create an `AccountIndexes` struct which contains a field: `Number`. This field represents our `AccountNumber` index. `AccountNumber` is a field of `authtypes.BaseAccount` and it's a `uint64`. Then we can see in our `AccountIndexes` struct the `Number` field is defined as: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} *indexes.Unique[uint64, sdk.AccAddress, authtypes.BaseAccount] ``` Where the first type parameter is `uint64`, which is the field type of our index. The second type parameter is the primary key `sdk.AccAddress`. And the third type parameter is the actual object we're storing `authtypes.BaseAccount`. Then we create a `NewAccountIndexes` function that instantiates and returns the `AccountsIndexes` struct. The function takes a `SchemaBuilder`. Then we instantiate our `indexes.Unique`, let's analyze the arguments we pass to `indexes.NewUnique`. #### NOTE: indexes list The `AccountsIndexes` struct contains the indexes, the `NewIndexedMap` function will infer the indexes form that struct using reflection, this happens only at init and is not computationally expensive. In case you want to explicitly declare indexes: implement the `Indexes` interface in the `AccountsIndexes` struct: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (a AccountsIndexes) IndexesList() []collections.Index[sdk.AccAddress, authtypes.BaseAccount] { return []collections.Index[sdk.AccAddress, authtypes.BaseAccount]{ a.Number } } ``` #### Instantiating a `indexes.Unique` The first three arguments, we already know them, they are: `SchemaBuilder`, `Prefix` which is our index prefix (the partition where index keys relationship for the `Number` index will be maintained), and the human name for the `Number` index. The second argument is a `collections.Uint64Key` which is a key codec to deal with `uint64` keys, we pass that because the key we're trying to index is a `uint64` key (the account number), and then we pass as fifth argument the primary key codec, which in our case is `sdk.AccAddress` (remember: we're mapping `sdk.AccAddress` => `BaseAccount`). Then as last parameter we pass a function that: given the `BaseAccount` returns its `AccountNumber`. After this we can proceed instantiating our `IndexedMap`. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} var AccountsPrefix = collections.NewPrefix(0) type Keeper struct { Schema collections.Schema Accounts *collections.IndexedMap[sdk.AccAddress, authtypes.BaseAccount, AccountsIndexes] } func NewKeeper(storeService store.KVStoreService, cdc codec.BinaryCodec) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Accounts: collections.NewIndexedMap( sb, AccountsPrefix, "accounts", sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc), NewAccountIndexes(sb), ), } } ``` As we can see here what we do, for now, is the same thing as we did for `collections.Map`. We pass it the `SchemaBuilder`, the `Prefix` where we plan to store the mapping between `sdk.AccAddress` and `authtypes.BaseAccount`, the human name and the respective `sdk.AccAddress` key codec and `authtypes.BaseAccount` value codec. Then we pass the instantiation of our `AccountIndexes` through `NewAccountIndexes`. Full example: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package docs import ( "cosmossdk.io/collections" "cosmossdk.io/collections/indexes" store "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var AccountsNumberIndexPrefix = collections.NewPrefix(1) type AccountsIndexes struct { Number *indexes.Unique[uint64, sdk.AccAddress, authtypes.BaseAccount] } func (a AccountsIndexes) IndexesList() []collections.Index[sdk.AccAddress, authtypes.BaseAccount] { return []collections.Index[sdk.AccAddress, authtypes.BaseAccount]{ a.Number } } func NewAccountIndexes(sb *collections.SchemaBuilder) AccountsIndexes { return AccountsIndexes{ Number: indexes.NewUnique( sb, AccountsNumberIndexPrefix, "accounts_by_number", collections.Uint64Key, sdk.AccAddressKey, func(_ sdk.AccAddress, v authtypes.BaseAccount) (uint64, error) { return v.AccountNumber, nil }, ), } } var AccountsPrefix = collections.NewPrefix(0) type Keeper struct { Schema collections.Schema Accounts *collections.IndexedMap[sdk.AccAddress, authtypes.BaseAccount, AccountsIndexes] } func NewKeeper(storeService store.KVStoreService, cdc codec.BinaryCodec) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Accounts: collections.NewIndexedMap( sb, AccountsPrefix, "accounts", sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc), NewAccountIndexes(sb), ), } } ``` ### Working with IndexedMaps While instantiating `collections.IndexedMap` is tedious, working with them is extremely smooth. Let's take the full example, and expand it with some use-cases. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package docs import ( "cosmossdk.io/collections" "cosmossdk.io/collections/indexes" store "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var AccountsNumberIndexPrefix = collections.NewPrefix(1) type AccountsIndexes struct { Number *indexes.Unique[uint64, sdk.AccAddress, authtypes.BaseAccount] } func (a AccountsIndexes) IndexesList() []collections.Index[sdk.AccAddress, authtypes.BaseAccount] { return []collections.Index[sdk.AccAddress, authtypes.BaseAccount]{ a.Number } } func NewAccountIndexes(sb *collections.SchemaBuilder) AccountsIndexes { return AccountsIndexes{ Number: indexes.NewUnique( sb, AccountsNumberIndexPrefix, "accounts_by_number", collections.Uint64Key, sdk.AccAddressKey, func(_ sdk.AccAddress, v authtypes.BaseAccount) (uint64, error) { return v.AccountNumber, nil }, ), } } var AccountsPrefix = collections.NewPrefix(0) type Keeper struct { Schema collections.Schema Accounts *collections.IndexedMap[sdk.AccAddress, authtypes.BaseAccount, AccountsIndexes] } func NewKeeper(storeService store.KVStoreService, cdc codec.BinaryCodec) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Accounts: collections.NewIndexedMap( sb, AccountsPrefix, "accounts", sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc), NewAccountIndexes(sb), ), } } func (k Keeper) CreateAccount(ctx sdk.Context, addr sdk.AccAddress) error { nextAccountNumber := k.getNextAccountNumber() newAcc := authtypes.BaseAccount{ AccountNumber: nextAccountNumber, Sequence: 0, } return k.Accounts.Set(ctx, addr, newAcc) } func (k Keeper) RemoveAccount(ctx sdk.Context, addr sdk.AccAddress) error { return k.Accounts.Remove(ctx, addr) } func (k Keeper) GetAccountByNumber(ctx sdk.Context, accNumber uint64) (sdk.AccAddress, authtypes.BaseAccount, error) { accAddress, err := k.Accounts.Indexes.Number.MatchExact(ctx, accNumber) if err != nil { return nil, authtypes.BaseAccount{ }, err } acc, err := k.Accounts.Get(ctx, accAddress) return accAddress, acc, nil } func (k Keeper) GetAccountsByNumber(ctx sdk.Context, startAccNum, endAccNum uint64) ([]authtypes.BaseAccount, error) { rng := new(collections.Range[uint64]). StartInclusive(startAccNum). EndInclusive(endAccNum) iter, err := k.Accounts.Indexes.Number.Iterate(ctx, rng) if err != nil { return nil, err } return indexes.CollectValues(ctx, k.Accounts, iter) } func (k Keeper) getNextAccountNumber() uint64 { return 0 } ``` ## Collections with interfaces as values Although cosmos-sdk is shifting away from the usage of interface registry, there are still some places where it is used. In order to support old code, we have to support collections with interface values. The generic `codec.CollValue` is not able to handle interface values, so we need to use a special type `codec.CollInterfaceValue`. `codec.CollInterfaceValue` takes a `codec.BinaryCodec` as an argument, and uses it to marshal and unmarshal values as interfaces. The `codec.CollInterfaceValue` lives in the `codec` package, whose import path is `github.com/cosmos/cosmos-sdk/codec`. ### Instantiating Collections with interface values In order to instantiate a collection with interface values, we need to use `codec.CollInterfaceValue` instead of `codec.CollValue`. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package example import ( "cosmossdk.io/collections" store "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var AccountsPrefix = collections.NewPrefix(0) type Keeper struct { Schema collections.Schema Accounts *collections.Map[sdk.AccAddress, sdk.AccountI] } func NewKeeper(cdc codec.BinaryCodec, storeService store.KVStoreService) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Accounts: collections.NewMap( sb, AccountsPrefix, "accounts", sdk.AccAddressKey, codec.CollInterfaceValue[sdk.AccountI](cdc), ), } } func (k Keeper) SaveBaseAccount(ctx sdk.Context, account authtypes.BaseAccount) error { return k.Accounts.Set(ctx, account.GetAddress(), account) } func (k Keeper) SaveModuleAccount(ctx sdk.Context, account authtypes.ModuleAccount) error { return k.Accounts.Set(ctx, account.GetAddress(), account) } func (k Keeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) (sdk.AccountI, error) { return k.Accounts.Get(ctx, addr) } ``` ## Triple key The `collections.Triple` is a special type of key composed of three keys, it's identical to `collections.Pair`. Let's see an example. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package example import ( "context" "cosmossdk.io/collections" store "cosmossdk.io/core/store" ) type AccAddress = string type ValAddress = string type Keeper struct { // let's simulate we have redelegations which are stored as a triple key composed of // the delegator, the source validator and the destination validator. Redelegations collections.KeySet[collections.Triple[AccAddress, ValAddress, ValAddress]] } func NewKeeper(storeService store.KVStoreService) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Redelegations: collections.NewKeySet(sb, collections.NewPrefix(0), "redelegations", collections.TripleKeyCodec(collections.StringKey, collections.StringKey, collections.StringKey) } } // RedelegationsByDelegator iterates over all the redelegations of a given delegator and calls onResult providing // each redelegation from source validator towards the destination validator. func (k Keeper) RedelegationsByDelegator(ctx context.Context, delegator AccAddress, onResult func(src, dst ValAddress) (stop bool, err error)) error { rng := collections.NewPrefixedTripleRange[AccAddress, ValAddress, ValAddress](delegator) return k.Redelegations.Walk(ctx, rng, func(key collections.Triple[AccAddress, ValAddress, ValAddress]) (stop bool, err error) { return onResult(key.K2(), key.K3()) }) } // RedelegationsByDelegatorAndValidator iterates over all the redelegations of a given delegator and its source validator and calls onResult for each // destination validator. func (k Keeper) RedelegationsByDelegatorAndValidator(ctx context.Context, delegator AccAddress, validator ValAddress, onResult func(dst ValAddress) (stop bool, err error)) error { rng := collections.NewSuperPrefixedTripleRange[AccAddress, ValAddress, ValAddress](delegator, validator) return k.Redelegations.Walk(ctx, rng, func(key collections.Triple[AccAddress, ValAddress, ValAddress]) (stop bool, err error) { return onResult(key.K3()) }) } ``` ## Advanced Usages ### Alternative Value Codec The `codec.AltValueCodec` allows a collection to decode values using a different codec than the one used to encode them. Basically it enables to decode two different byte representations of the same concrete value. It can be used to lazily migrate values from one bytes representation to another, as long as the new representation is not able to decode the old one. A concrete example can be found in `x/bank` where the balance was initially stored as `Coin` and then migrated to `Int`. ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} var BankBalanceValueCodec = codec.NewAltValueCodec(sdk.IntValue, func(b []byte) (sdk.Int, error) { coin := sdk.Coin{ } err := coin.Unmarshal(b) if err != nil { return sdk.Int{ }, err } return coin.Amount, nil }) ``` The above example shows how to create an `AltValueCodec` that can decode both `sdk.Int` and `sdk.Coin` values. The provided decoder function will be used as a fallback in case the default decoder fails. When the value will be encoded back into state it will use the default encoder. This allows to lazily migrate values to a new bytes representation. # Module Store Internals Source: https://docs.cosmos.network/sdk/latest/guides/state/store The store package defines the
프로젝트로 돌아가기