Cosmos Hub 백서

Cosmos Hub

원문

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

llection type we instantiate in our keeper, in our case the `AllowList`. After creating all collections, call `sb.Build()` to validate prefix uniqueness and finalize the schema. Store the returned `collections.Schema` in the keeper's `Schema` field: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} k := Keeper{ AllowList: collections.NewKeySet(sb, AllowListPrefix, "allow_list", collections.StringKey), } schema, err := sb.Build() if err != nil { panic(err) } k.Schema = schema return k ``` The code examples in this document show the collection instantiation patterns but omit the `sb.Build()` call for brevity. In production code, `sb.Build()` is required. ### Prefix The second argument passed to our `KeySet` is a `collections.Prefix`, a prefix represents a partition of the module's `KVStore` where all the state of a specific collection will be saved. Since a module can have multiple collections, the following is expected: * module params will become a `collections.Item` * the `AllowList` is a `collections.KeySet` We don't want a collection to write over the state of the other collection so we pass it a prefix, which defines a storage partition owned by the collection. If you already built modules, the prefix translates to the items you were creating in your `types/keys.go` file, example: [Link](https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/x/feegrant/key.go#L16-L22) your old: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} var ( // FeeAllowanceKeyPrefix is the set of the kvstore for fee allowance data // - 0x00<allowance_key_bytes>: allowance FeeAllowanceKeyPrefix = []byte{0x00 } // FeeAllowanceQueueKeyPrefix is the set of the kvstore for fee allowance keys data // - 0x01<allowance_prefix_queue_key_bytes>: <empty value> FeeAllowanceQueueKeyPrefix = []byte{0x01 } ) ``` becomes: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} var ( // FeeAllowanceKeyPrefix is the set of the kvstore for fee allowance data // - 0x00<allowance_key_bytes>: allowance FeeAllowanceKeyPrefix = collections.NewPrefix(0) // FeeAllowanceQueueKeyPrefix is the set of the kvstore for fee allowance keys data // - 0x01<allowance_prefix_queue_key_bytes>: <empty value> FeeAllowanceQueueKeyPrefix = collections.NewPrefix(1) ) ``` #### Rules `collections.NewPrefix` accepts either `int`, `string` or `[]byte`. It is good practice to use a monotonically increasing `int` (values 0–255) for disk space efficiency. A collection **MUST NOT** share the same prefix as another collection in the same module, and a collection prefix **MUST NEVER** start with the same prefix as another, examples: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} prefix1 := collections.NewPrefix("prefix") prefix2 := collections.NewPrefix("prefix") // THIS IS BAD! ``` ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} prefix1 := collections.NewPrefix("a") prefix2 := collections.NewPrefix("aa") // prefix2 starts with the same as prefix1: BAD!!! ``` ### Human-Readable Name The third parameter we pass to a collection is a string, which is a human-readable name. It is needed to make the role of a collection understandable by clients who have no clue about what a module is storing in state. #### Rules Each collection in a module **MUST** have a unique humanized name. ## Key and Value Codecs A collection is generic over the type you can use as keys or values. This makes collections dumb, but also means that hypothetically we can store everything that can be a go type into a collection. We are not bounded to any type of encoding (be it proto, json or whatever) So a collection needs to be given a way to understand how to convert your keys and values to bytes. This is achieved through `KeyCodec` and `ValueCodec`, which are arguments that you pass to your collections when you're instantiating them using the `collections.NewMap/collections.NewItem/...` instantiation functions. NOTE: Generally speaking you will never be required to implement your own `Key/ValueCodec` as the SDK and collections libraries already come with default, safe and fast implementation of those. You might need to implement them only if you're migrating to collections and there are state layout incompatibilities. Let's explore an example: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package collections import ( "cosmossdk.io/collections" store "cosmossdk.io/core/store" sdk "github.com/cosmos/cosmos-sdk/types" ) var IDsPrefix = collections.NewPrefix(0) type Keeper struct { Schema collections.Schema IDs collections.Map[string, uint64] } func NewKeeper(storeService store.KVStoreService) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ IDs: collections.NewMap(sb, IDsPrefix, "ids", collections.StringKey, collections.Uint64Value), } } ``` We're now instantiating a map where the key is string and the value is `uint64`. We already know the first three arguments of the `NewMap` function. The fourth parameter is our `KeyCodec`, we know that the `Map` has `string` as key so we pass it a `KeyCodec` that handles strings as keys. The fifth parameter is our `ValueCodec`, we know that the `Map` has a `uint64` as value so we pass it a `ValueCodec` that handles uint64. Collections already comes with all the required implementations for golang primitive types. Let's make another example, this falls closer to what we build using cosmos SDK, let's say we want to create a `collections.Map` that maps account addresses to their base account. So we want to map an `sdk.AccAddress` to an `auth.BaseAccount` (which is a proto): ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package collections 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, authtypes.BaseAccount] } func NewKeeper(storeService store.KVStoreService, cdc codec.BinaryCodec) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Accounts: collections.NewMap(sb, AccountsPrefix, "accounts", sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc)), } } ``` As we can see here since our `collections.Map` maps `sdk.AccAddress` to `authtypes.BaseAccount`, we use the `sdk.AccAddressKey` which is the `KeyCodec` implementation for `AccAddress` and we use `codec.CollValue` to encode our proto type `BaseAccount`. Generally speaking you will always find the respective key and value codecs for types in the `go.mod` path you're using to import that type. If you want to encode proto values refer to the codec `codec.CollValue` function, which allows you to encode any type implement the `proto.Message` interface. ## Map We analyze the first and most important collection type, the `collections.Map`. This is the type that everything else builds on top of. ### Use case A `collections.Map` is used to map arbitrary keys with arbitrary values. ### Example It's easier to explain a `collections.Map` capabilities through an example: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package collections import ( "cosmossdk.io/collections" store "cosmossdk.io/core/store" "fmt" "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, authtypes.BaseAccount] } func NewKeeper(storeService store.KVStoreService, cdc codec.BinaryCodec) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Accounts: collections.NewMap(sb, AccountsPrefix, "accounts", sdk.AccAddressKey, codec.CollValue[authtypes.BaseAccount](cdc)), } } func (k Keeper) CreateAccount(ctx sdk.Context, addr sdk.AccAddress, account authtypes.BaseAccount) error { has, err := k.Accounts.Has(ctx, addr) if err != nil { return err } if has { return fmt.Errorf("account already exists: %s", addr) } err = k.Accounts.Set(ctx, addr, account) if err != nil { return err } return nil } func (k Keeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) (authtypes.BaseAccount, error) { acc, err := k.Accounts.Get(ctx, addr) if err != nil { return authtypes.BaseAccount{ }, err } return acc, nil } func (k Keeper) RemoveAccount(ctx sdk.Context, addr sdk.AccAddress) error { err := k.Accounts.Remove(ctx, addr) if err != nil { return err } return nil } ``` #### Set method Set maps with the provided `AccAddress` (the key) to the `auth.BaseAccount` (the value). Under the hood the `collections.Map` will convert the key and value to bytes using the [key and value codec](#key-and-value-codecs). It will prepend to our bytes key the [prefix](#prefix) and store it in the KVStore of the module. #### Has method The has method reports if the provided key exists in the store. #### Get method The get method accepts the `AccAddress` and returns the associated `auth.BaseAccount` if it exists, otherwise it errors. #### Remove method The remove method accepts the `AccAddress` and removes it from the store. It won't report errors if it does not exist, to check for existence before removal use the `Has` method. #### Iteration Iteration has a separate section. ## KeySet The second type of collection is `collections.KeySet`, as the word suggests it maintains only a set of keys without values. #### Implementation curiosity A `collections.KeySet` is just a `collections.Map` with a `key` but no value. The value internally is always the same and is represented as an empty byte slice `[]byte{}`. ### Example As always we explore the collection type through an example: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package collections import ( "cosmossdk.io/collections" store "cosmossdk.io/core/store" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" ) var ValidatorsSetPrefix = collections.NewPrefix(0) type Keeper struct { Schema collections.Schema ValidatorsSet collections.KeySet[sdk.ValAddress] } func NewKeeper(storeService store.KVStoreService) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ ValidatorsSet: collections.NewKeySet(sb, ValidatorsSetPrefix, "validators_set", sdk.ValAddressKey), } } func (k Keeper) AddValidator(ctx sdk.Context, validator sdk.ValAddress) error { has, err := k.ValidatorsSet.Has(ctx, validator) if err != nil { return err } if has { return fmt.Errorf("validator already in set: %s", validator) } err = k.ValidatorsSet.Set(ctx, validator) if err != nil { return err } return nil } func (k Keeper) RemoveValidator(ctx sdk.Context, validator sdk.ValAddress) error { err := k.ValidatorsSet.Remove(ctx, validator) if err != nil { return err } return nil } ``` The first difference we notice is that `KeySet` needs use to specify only one type parameter: the key (`sdk.ValAddress` in this case). The second difference we notice is that `KeySet` in its `NewKeySet` function does not require us to specify a `ValueCodec` but only a `KeyCodec`. This is because a `KeySet` only saves keys and not values. Let's explore the methods. #### Has method Has allows us to understand if a key is present in the `collections.KeySet` or not, functions in the same way as `collections.Map.Has ` #### Set method Set inserts the provided key in the `KeySet`. #### Remove method Remove removes the provided key from the `KeySet`, it does not error if the key does not exist, if existence check before removal is required it needs to be coupled with the `Has` method. ## Item The third type of collection is the `collections.Item`. It stores only one single item, it's useful for example for parameters, there's only one instance of parameters in state always. #### implementation curiosity A `collections.Item` is just a `collections.Map` with no key but just a value. The key is the prefix of the collection! ### Example ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package collections import ( "cosmossdk.io/collections" store "cosmossdk.io/core/store" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "cosmossdk.io/x/staking/types" ) var ParamsPrefix = collections.NewPrefix(0) type Keeper struct { Schema collections.Schema Params collections.Item[stakingtypes.Params] } func NewKeeper(storeService store.KVStoreService, cdc codec.BinaryCodec) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Params: collections.NewItem(sb, ParamsPrefix, "params", codec.CollValue[stakingtypes.Params](cdc)), } } func (k Keeper) UpdateParams(ctx sdk.Context, params stakingtypes.Params) error { err := k.Params.Set(ctx, params) if err != nil { return err } return nil } func (k Keeper) GetParams(ctx sdk.Context) (stakingtypes.Params, error) { return k.Params.Get(ctx) } ``` The first key difference we notice is that we specify only one type parameter, which is the value we're storing. The second key difference is that we don't specify the `KeyCodec`, since we store only one item we already know the key and the fact that it is constant. ## Iteration One of the key features of the `KVStore` is iterating over keys. Collections which deal with keys (so `Map`, `KeySet` and `IndexedMap`) allow you to iterate over keys in a safe and typed way. They all share the same API, the only difference being that `KeySet` returns a different type of `Iterator` because `KeySet` only deals with keys. <Note> Every collection shares the same `Iterator` semantics. </Note> Let's have a look at the `Map.Iterate` method: ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (m Map[K, V]) Iterate(ctx context.Context, ranger Ranger[K]) (Iterator[K, V], error) ``` It accepts a `collections.Ranger[K]`, which is an API that instructs map on how to iterate over keys. As always we don't need to implement anything here as `collections` already provides some generic `Ranger` implementers that expose all you need to work with ranges. ### Example We have a `collections.Map` that maps accounts using `uint64` IDs. ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package collections 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[uint64, authtypes.BaseAccount] } func NewKeeper(storeService store.KVStoreService, cdc codec.BinaryCodec) Keeper { sb := collections.NewSchemaBuilder(storeService) return Keeper{ Accounts: collections.NewMap(sb, AccountsPrefix, "accounts", collections.Uint64Key, codec.CollValue[authtypes.BaseAccount](cdc)), } } func (k Keeper) GetAllAccounts(ctx sdk.Context) ([]authtypes.BaseAccount, error) { // passing a nil Ranger equals to: iterate over every possible key iter, err := k.Accounts.Iterate(ctx, nil) if err != nil { return nil, err } accounts, err := iter.Values() if err != nil { return nil, err } return accounts, err } func (k Keeper) IterateAccountsBetween(ctx sdk.Context, start, end uint64) ([]authtypes.BaseAccount, error) { // The collections.Range API offers a lot of capabilities // like defining where the iteration starts or ends. rng := new(collections.Range[uint64]). StartInclusive(start). EndExclusive(end). Descending() iter, err := k.Accounts.Iterate(ctx, rng) if err != nil { return nil, err } accounts, err := iter.Values() if err != nil { return nil, err } return accounts, nil } func (k Keeper) IterateAccounts(ctx sdk.Context, do func(id uint64, acc authtypes.BaseAccount) (stop bool)) error { iter, err := k.Accounts.Iterate(ctx, nil) if err != nil { return err } defer iter.Close() for ; iter.Valid(); iter.Next() { kv, err := iter.KeyValue() if err != nil { return err } if do(kv.Key, kv.Value) { break } } return nil } ``` Let's analyze each method in the example and how it makes use of the `Iterate` and the returned `Iterator` API. #### GetAllAccounts In `GetAllAccounts` we pass to our `Iterate` a nil `Ranger`. This means that the returned `Iterator` will include all the existing keys within the collection. Then we use the `Values` method from the returned `Iterator` API to collect all the values into a slice. `Iterator` offers other methods such as `Keys()` to collect only the keys and not the values and `KeyValues` to collect all the keys and values. #### IterateAccountsBetween Here we make use of the `collections.Range` helper to specialize our range. We make it start in a point through `StartInclusive` and end in the other with `EndExclusive`, then we instruct it to report us results in reverse order through `Descending` Then we pass the range instruction to `Iterate` and get an `Iterator`, which will contain only the results we specified in the range. Then we use again the `Values` method of the `Iterator` to collect all the results. `collections.Range` also offers a `Prefix` API which is not applicable to all keys types, for example uint64 cannot be prefix because it is of constant size, but a `string` key can be prefixed. #### IterateAccounts Here we showcase how to lazily collect values from an Iterator. <Note> `Keys/Values/KeyValues` fully consume and close the `Iterator`, here we need to explicitly do a `defer iterator.Close()` call. </Note> `Iterator` also exposes a `Value` and `Key` method to collect only the current value or key, if collecting both is not needed. <Note> For this `callback` pattern, collections expose a `Walk` API. </Note> ## Composite keys So far we've worked only with simple keys, like `uint64`, the account address, etc. There are some more complex cases in, which we need to deal with composite keys. A key is composite when it is composed of multiple keys, for example bank balances as stored as the composite key `(AccAddress, string)` where the first part is the address holding the coins and the second part is the denom. Example, let's say address `BOB` holds `10atom,15osmo`, this is how it is stored in state: ```javascript theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} (bob, atom) => 10 (bob, osmos) => 15 ``` Now this allows to efficiently get a specific denom balance of an address, by simply `getting` `(address, denom)`, or getting all the balances of an address by prefixing over `(address)`. Let's see now how we can work with composite keys using collections. ### Example In our example we will showcase how we can use collections when we are dealing with balances, similar to bank, a balance is a mapping between `(address, denom) => math.Int` the composite key in our case is `(address, denom)`. ## Instantiation of a composite key collection ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} package collections import ( "cosmossdk.io/collections" "cosmossdk.io/math" store "cosmossdk.io/core/store" sdk "github.com/cosmos/cosmos-sdk/types" ) var BalancesPrefix = collections.NewPrefix(1
프로젝트로 돌아가기