Cosmos Hub 백서

Cosmos Hub

원문

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

down in genesis, so that when difficult questions come up, the constitution can provide guidance to the community. ### Proposals `Proposal` objects are used to tally votes and generally track the proposal's state. They contain an array of arbitrary `sdk.Msg`'s which the governance module will attempt to resolve and then execute if the proposal passes. `Proposal`'s are identified by a unique id and contains a series of timestamps: `submit_time`, `deposit_end_time`, `voting_start_time`, `voting_end_time` which track the lifecycle of a proposal ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/gov/v1/gov.proto#L50-L101 ``` A proposal will generally require more than just a set of messages to explain its purpose but need some greater justification and allow a means for interested participants to discuss and debate the proposal. In most cases, **it is encouraged to have an off-chain system that supports the on-chain governance process**. To accommodate for this, a proposal contains a special **`metadata`** field, a string, which can be used to add context to the proposal. The `metadata` field allows custom use for networks, however, it is expected that the field contains a URL or some form of CID using a system such as [IPFS](https://docs.ipfs.io/concepts/content-addressing/). To support the case of interoperability across networks, the SDK recommends that the `metadata` represents the following `JSON` template: ```json theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} { "title": "...", "description": "...", "forum": "...", // a link to the discussion platform (i.e. Discord) "other": "..." // any extra data that doesn't correspond to the other fields } ``` This makes it far easier for clients to support multiple networks. The metadata has a maximum length that is chosen by the app developer, and passed into the gov keeper as a config. The default maximum length in the SDK is 255 characters. #### Writing a module that uses governance There are many aspects of a chain, or of the individual modules that you may want to use governance to perform such as changing various parameters. This is very simple to do. First, write out your message types and `MsgServer` implementation. Add an `authority` field to the keeper which will be populated in the constructor with the governance module account: `govKeeper.GetGovernanceAccount().GetAddress()`. Then for the methods in the `msg_server.go`, perform a check on the message that the signer matches `authority`. This will prevent any user from executing that message. ### Parameters and base types `Parameters` define the rules according to which votes are run. There can only be one active parameter set at any given time. If governance wants to change a parameter set, either to modify a value or add/remove a parameter field, a new parameter set has to be created and the previous one rendered inactive. #### Params ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/gov/v1/gov.proto#L193-L255 ``` Additionally, we introduce some basic types: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type Vote byte const ( VoteYes = 0x1 VoteNo = 0x2 VoteNoWithVeto = 0x3 VoteAbstain = 0x4 ) type ProposalType string const ( ProposalTypePlainText = "Text" ProposalTypeSoftwareUpgrade = "SoftwareUpgrade" ) type ProposalStatus byte const ( StatusNil ProposalStatus = 0x00 StatusDepositPeriod ProposalStatus = 0x01 // Proposal is submitted. Participants can deposit on it but not vote StatusVotingPeriod ProposalStatus = 0x02 // MinDeposit is reached, participants can vote StatusPassed ProposalStatus = 0x03 // Proposal passed and successfully executed StatusRejected ProposalStatus = 0x04 // Proposal has been rejected StatusFailed ProposalStatus = 0x05 // Proposal passed but failed execution ) ``` ### Deposit ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/gov/v1/gov.proto#L37-L48 ``` ### ValidatorGovInfo This type is used in a temp map when tallying ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type ValidatorGovInfo struct { Minus sdk.Dec Vote Vote } ``` ## Stores <Note> Stores are KVStores in the multi-store. The key to find the store is the first parameter in the list </Note> We will use one KVStore `Governance` to store four mappings: * A mapping from `proposalID|'proposal'` to `Proposal`. * A mapping from `proposalID|'addresses'|address` to `Vote`. This mapping allows us to query all addresses that voted on the proposal along with their vote by doing a range query on `proposalID:addresses`. * A mapping from `ParamsKey|'Params'` to `Params`. This map allows to query all x/gov params. * A mapping from `VotingPeriodProposalKeyPrefix|proposalID` to a single byte. This allows us to know if a proposal is in the voting period or not with very low gas cost. For pseudocode purposes, here are the two function we will use to read or write in stores: * `load(StoreKey, Key)`: Retrieve item stored at key `Key` in store found at key `StoreKey` in the multistore * `store(StoreKey, Key, value)`: Write value `Value` at key `Key` in store found at key `StoreKey` in the multistore ### Proposal Processing Queue **Store:** * `ProposalProcessingQueue`: A queue `queue[proposalID]` containing all the `ProposalIDs` of proposals that reached `MinDeposit`. During each `EndBlock`, all the proposals that have reached the end of their voting period are processed. To process a finished proposal, the application tallies the votes, computes the votes of each validator and checks if every validator in the validator set has voted. If the proposal is accepted, deposits are refunded. Finally, the proposal content `Handler` is executed. And the pseudocode for the `ProposalProcessingQueue`: ```go expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} in EndBlock do for finishedProposalID in GetAllFinishedProposalIDs(block.Time) proposal = load(Governance, <proposalID|'proposal'>) // proposal is a const key validators = Keeper.getAllValidators() tmpValMap := map(sdk.AccAddress) ValidatorGovInfo // Initiate mapping at 0. This is the amount of shares of the validator's vote that will be overridden by their delegator's votes for each validator in validators tmpValMap(validator.OperatorAddr).Minus = 0 // Tally voterIterator = rangeQuery(Governance, <proposalID|'addresses'>) //return all the addresses that voted on the proposal for each (voterAddress, vote) in voterIterator delegations = stakingKeeper.getDelegations(voterAddress) // get all delegations for current voter for each delegation in delegations // make sure delegation.Shares does NOT include shares being unbonded tmpValMap(delegation.ValidatorAddr).Minus += delegation.Shares proposal.updateTally(vote, delegation.Shares) _, isVal = stakingKeeper.getValidator(voterAddress) if (isVal) tmpValMap(voterAddress).Vote = vote tallyingParam = load(Params, 'TallyingParam') // Update tally if validator voted for each validator in validators if tmpValMap(validator).HasVoted proposal.updateTally(tmpValMap(validator).Vote, (validator.TotalShares - tmpValMap(validator).Minus)) // Check if proposal is accepted or rejected totalNonAbstain := proposal.YesVotes + proposal.NoVotes + proposal.NoWithVetoVotes if (proposal.Votes.YesVotes/totalNonAbstain > tallyingParam.Threshold AND proposal.Votes.NoWithVetoVotes/totalNonAbstain < tallyingParam.Veto) // proposal was accepted at the end of the voting period // refund deposits (non-voters already punished) for each (amount, depositor) in proposal.Deposits depositor.AtomBalance += amount stateWriter, err := proposal.Handler() if err != nil // proposal passed but failed during state execution proposal.CurrentStatus = ProposalStatusFailed else // proposal pass and state is persisted proposal.CurrentStatus = ProposalStatusAccepted stateWriter.save() else // proposal was rejected proposal.CurrentStatus = ProposalStatusRejected store(Governance, <proposalID|'proposal'>, proposal) ``` ### Legacy Proposal <Warning> Legacy proposals are deprecated. Use the new proposal flow by granting the governance module the right to execute the message. </Warning> A legacy proposal is the old implementation of governance proposal. Contrary to proposal that can contain any messages, a legacy proposal allows to submit a set of pre-defined proposals. These proposals are defined by their types and handled by handlers that are registered in the gov v1beta1 router. More information on how to submit proposals in the [client section](#client). ## Messages ### Proposal Submission Proposals can be submitted by any account via a `MsgSubmitProposal` transaction. ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/gov/v1/tx.proto#L57-L88 ``` All `sdk.Msgs` passed into the `messages` field of a `MsgSubmitProposal` message must be registered in the app's `MsgServiceRouter`. Each of these messages must have one signer, namely the gov module account. And finally, the metadata length must not be larger than the `maxMetadataLen` config passed into the gov keeper. The `initialDeposit` must be strictly positive and conform to the accepted denom of the `MinDeposit` param. **State modifications:** * Generate new `proposalID` * Create new `Proposal` * Initialize `Proposal`'s attributes * Decrease balance of sender by `InitialDeposit` * If `MinDeposit` is reached: * Push `proposalID` in `ProposalProcessingQueue` * Transfer `InitialDeposit` from the `Proposer` to the governance `ModuleAccount` ### Deposit Once a proposal is submitted, if `Proposal.TotalDeposit < ActiveParam.MinDeposit`, Atom holders can send `MsgDeposit` transactions to increase the proposal's deposit. A deposit is accepted iff: * The proposal exists * The proposal is not in the voting period * The deposited coins are conform to the accepted denom from the `MinDeposit` param ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/gov/v1/tx.proto#L153-L166 ``` **State modifications:** * Decrease balance of sender by `deposit` * Add `deposit` of sender in `proposal.Deposits` * Increase `proposal.TotalDeposit` by sender's `deposit` * If `MinDeposit` is reached: * Push `proposalID` in `ProposalProcessingQueueEnd` * Transfer `Deposit` from the `proposer` to the governance `ModuleAccount` ### Vote Once `ActiveParam.MinDeposit` is reached, voting period starts. From there, bonded Atom holders are able to send `MsgVote` transactions to cast their vote on the proposal. ```protobuf theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} // Reference: https://github.com/cosmos/cosmos-sdk/blob/release/v0.55.x/proto/cosmos/gov/v1/tx.proto#L111-L127 ``` **State modifications:** * Record `Vote` of sender <Note> Gas cost for this message has to take into account the future tallying of the vote in EndBlocker. </Note> ## Events The governance module emits the following events: ### EndBlocker | Type | Attribute Key | Attribute Value | | - | - | - | | inactive\_proposal | proposal\_id | `{proposalID}` | | inactive\_proposal | proposal\_result | `{proposalResult}` | | active\_proposal | proposal\_id | `{proposalID}` | | active\_proposal | proposal\_result | `{proposalResult}` | ### Handlers #### MsgSubmitProposal | Type | Attribute Key | Attribute Value | | - | - | - | | submit\_proposal | proposal\_id | `{proposalID}` | | submit\_proposal \[0] | voting\_period\_start | `{proposalID}` | | proposal\_deposit | amount | `{depositAmount}` | | proposal\_deposit | proposal\_id | `{proposalID}` | | message | module | governance | | message | action | submit\_proposal | | message | sender | `{senderAddress}` | * \[0] Event only emitted if the voting period starts during the submission. #### MsgVote | Type | Attribute Key | Attribute Value | | - | - | - | | proposal\_vote | option | `{voteOption}` | | proposal\_vote | proposal\_id | `{proposalID}` | | message | module | governance | | message | action | vote | | message | sender | `{senderAddress}` | #### MsgVoteWeighted | Type | Attribute Key | Attribute Value | | - | - | - | | proposal\_vote | option | `{weightedVoteOptions}` | | proposal\_vote | proposal\_id | `{proposalID}` | | message | module | governance | | message | action | vote | | message | sender | `{senderAddress}` | #### MsgDeposit | Type | Attribute Key | Attribute Value | | - | - | - | | proposal\_deposit | amount | `{depositAmount}` | | proposal\_deposit | proposal\_id | `{proposalID}` | | proposal\_deposit \[0] | voting\_period\_start | `{proposalID}` | | message | module | governance | | message | action | deposit | | message | sender | `{senderAddress}` | * \[0] Event only emitted if the voting period starts during the submission. ## Hooks The governance module exposes a `GovHooks` interface that allows other modules to react to governance events. ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} type GovHooks interface { AfterProposalSubmission(ctx context.Context, proposalID uint64, proposerAddr sdk.AccAddress) error AfterProposalDeposit(ctx context.Context, proposalID uint64, depositorAddr sdk.AccAddress) error AfterProposalVote(ctx context.Context, proposalID uint64, voterAddr sdk.AccAddress) error AfterProposalFailedMinDeposit(ctx context.Context, proposalID uint64) error AfterProposalVotingPeriodEnded(ctx context.Context, proposalID uint64) error } ``` ### AfterProposalSubmission Called after a proposal is submitted. The hook receives the proposal ID and the proposer's address. **Note:** The `proposerAddr` parameter was added in a recent release. If you are implementing `GovHooks`, you must update your `AfterProposalSubmission` method signature to include `proposerAddr sdk.AccAddress` as a third parameter. **Before:** ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (h MyGovHooks) AfterProposalSubmission(ctx context.Context, proposalID uint64) error { // implementation } ``` **After:** ```go theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} func (h MyGovHooks) AfterProposalSubmission(ctx context.Context, proposalID uint64, proposerAddr sdk.AccAddress) error { // implementation } ``` ### AfterProposalDeposit Called after a deposit is made on a proposal. ### AfterProposalVote Called after a vote is cast on a proposal. ### AfterProposalFailedMinDeposit Called when a proposal fails to reach the minimum deposit within the deposit period. ### AfterProposalVotingPeriodEnded Called when a proposal's voting period ends. ## Parameters The governance module contains the following parameters: | Key | Type | Example | | - | - | - | | min\_deposit | array (coins) | \[`{"denom":"uatom","amount":"10000000"}`] | | max\_deposit\_period | string (time ns) | "172800000000000" (17280s) | | voting\_period | string (time ns) | "172800000000000" (17280s) | | quorum | string (dec) | "0.334000000000000000" | | threshold | string (dec) | "0.500000000000000000" | | veto | string (dec) | "0.334000000000000000" | | expedited\_threshold | string (time ns) | "0.667000000000000000" | | expedited\_voting\_period | string (time ns) | "86400000000000" (8600s) | | expedited\_min\_deposit | array (coins) | \[`{"denom":"uatom","amount":"50000000"}`] | | burn\_proposal\_deposit\_prevote | bool | false | | burn\_vote\_quorum | bool | false | | burn\_vote\_veto | bool | true | | min\_initial\_deposit\_ratio | string | "0.1" | **NOTE**: The governance module contains parameters that are objects unlike other modules. If only a subset of parameters are desired to be changed, only they need to be included and not the entire parameter object structure. ## Client ### CLI A user can query and interact with the `gov` module using the CLI. #### Query The `query` commands allow users to query `gov` state. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov --help ``` ##### deposit The `deposit` command allows users to query a deposit for a given proposal from a given depositor. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov deposit [proposal-id] [depositer-addr] [flags] ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov deposit 1 cosmos1.. ``` Example Output: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} amount: - amount: "100" denom: stake depositor: cosmos1.. proposal_id: "1" ``` ##### deposits The `deposits` command allows users to query all deposits for a given proposal. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov deposits [proposal-id] [flags] ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov deposits 1 ``` Example Output: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} deposits: - amount: - amount: "100" denom: stake depositor: cosmos1.. proposal_id: "1" pagination: next_key: null total: "0" ``` ##### param The `param` command allows users to query a given parameter for the `gov` module. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov param [param-type] [flags] ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov param voting ``` Example Output: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} voting_period: "172800000000000" ``` ##### params The `params` command allows users to query all parameters for the `gov` module. ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov params [flags] ``` Example: ```bash theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} simd query gov params ``` Example Output: ```bash expandable theme={"theme":{"light":"github-light-high-contrast","dark":"github-dark-high-contrast"}} deposit_params: max_deposit_period: 172800s min_deposit: - amount: "10000000" denom: stake params: expedited_min_deposit: - amount: "50000000" denom: stake expedited_threshold: "0.670000000000000000" expedited_voting_period: 86400s max_deposit_period: 172800s min_deposit: - amount: "10000000" denom: stake min_initial_deposit_ratio: "0.000000000000000000" proposal_cancel_burn_rate: "0.500000000000000000" quorum: "0.334000000000000000" threshold: "0.500000000000000000" veto_threshold: "0.334000000000000000" voting_period: 172800s tally_params: quorum: "0.334000000000000000" threshold: "0.500000000000000000" veto_threshold: "0.334000000000000000" voting_params: voting_period: 172800s ``` ##### proposal The `proposal` command allows users to query a given proposal. ```bash theme={"theme":{"light":"gith
프로젝트로 돌아가기