staking

Abstract

This paper specifies the Staking module of the Cosmos SDK that was first described in the Cosmos Whitepaper in June 2016.

The module enables Cosmos SDK-based blockchain to support an advanced Proof-of-Stake (PoS) system. In this system, holders of the native staking token of the chain can become validators and can delegate tokens to validators, ultimately determining the effective validator set for the system.

State

Pool

Pool is used for tracking bonded and not-bonded token supply of the bond denomination.

LastTotalPower

LastTotalPower tracks the total amounts of bonded tokens recorded during the previous end block. Store entries prefixed with "Last" must remain unchanged until EndBlock.

  • LastTotalPower: 0x12 -> ProtocolBuffer(math.Int)

ValidatorUpdates

ValidatorUpdates contains the validator updates returned to ABCI at the end of every block. The values are overwritten in every block.

  • ValidatorUpdates 0x61 -> []abci.ValidatorUpdate

UnbondingID

UnbondingID stores the ID of the latest unbonding operation. It enables creating unique IDs for unbonding operations, i.e., UnbondingID is incremented every time a new unbonding operation (validator unbonding, unbonding delegation, redelegation) is initiated.

  • UnbondingID: 0x37 -> uint64

Params

The staking module stores its params in state with the prefix of 0x51, it can be updated with governance or the address with authority.

  • Params: 0x51 | ProtocolBuffer(Params)

proto/cosmos/staking/v1beta1/staking.proto

// Params defines the parameters for the x/staking module.
message Params {
  option (amino.name)                 = "cosmos-sdk/x/staking/Params";
  option (gogoproto.equal)            = true;
  option (gogoproto.goproto_stringer) = false;

  // unbonding_time is the time duration of unbonding.
  google.protobuf.Duration unbonding_time = 1
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true, (gogoproto.stdduration) = true];
  // max_validators is the maximum number of validators.
  uint32 max_validators = 2;
  // max_entries is the max entries for either unbonding delegation or redelegation (per pair/trio).
  uint32 max_entries = 3;
  // historical_entries is the number of historical entries to persist.
  uint32 historical_entries = 4;
  // bond_denom defines the bondable coin denomination.
  string bond_denom = 5;
  // min_commission_rate is the chain-wide minimum commission rate that a validator can charge their delegators
  string min_commission_rate = 6 [
    (gogoproto.moretags)   = "yaml:\"min_commission_rate\"",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
    (gogoproto.nullable)   = false
  ];
}

See full example on GitHub

Validator

Validators can have one of three statuses

  • Unbonded: The validator is not in the active set. They cannot sign blocks and do not earn rewards. They can receive delegations.

  • Bonded: Once the validator receives sufficient bonded tokens they automatically join the active set during EndBlock and their status is updated to Bonded. They are signing blocks and receiving rewards. They can receive further delegations. They can be slashed for misbehavior. Delegators to this validator who unbond their delegation must wait the duration of the UnbondingTime, a chain-specific param, during which time they are still slashable for offences of the source validator if those offences were committed during the period of time that the tokens were bonded.

  • Unbonding: When a validator leaves the active set, either by choice or due to slashing, jailing or tombstoning, an unbonding of all their delegations begins. All delegations must then wait the UnbondingTime before their tokens are moved to their accounts from the BondedPool.

danger

Tombstoning is permanent, once tombstoned a validator's consensus key can not be reused within the chain where the tombstoning happened.

Validators objects should be primarily stored and accessed by the OperatorAddr, an SDK validator address for the operator of the validator. Two additional indices are maintained per validator object in order to fulfill required lookups for slashing and validator-set updates. A third special index (LastValidatorPower) is also maintained which however remains constant throughout each block, unlike the first two indices which mirror the validator records within a block.

  • Validators: 0x21 | OperatorAddrLen (1 byte) | OperatorAddr -> ProtocolBuffer(validator)

  • ValidatorsByConsAddr: 0x22 | ConsAddrLen (1 byte) | ConsAddr -> OperatorAddr

  • ValidatorsByPower: 0x23 | BigEndian(ConsensusPower) | OperatorAddrLen (1 byte) | OperatorAddr -> OperatorAddr

  • LastValidatorsPower: 0x11 | OperatorAddrLen (1 byte) | OperatorAddr -> ProtocolBuffer(ConsensusPower)

  • ValidatorsByUnbondingID: 0x38 | UnbondingID -> 0x21 | OperatorAddrLen (1 byte) | OperatorAddr

Validators is the primary index - it ensures that each operator can have only one associated validator, where the public key of that validator can change in the future. Delegators can refer to the immutable operator of the validator, without concern for the changing public key.

ValidatorsByUnbondingID is an additional index that enables lookups for validators by the unbonding IDs corresponding to their current unbonding.

ValidatorByConsAddr is an additional index that enables lookups for slashing. When CometBFT reports evidence, it provides the validator address, so this map is needed to find the operator. Note that the ConsAddr corresponds to the address which can be derived from the validator's ConsPubKey.

ValidatorsByPower is an additional index that provides a sorted list of potential validators to quickly determine the current active set. Here ConsensusPower is validator.Tokens/10^6 by default. Note that all validators where Jailed is true are not stored within this index.

LastValidatorsPower is a special index that provides a historical list of the last-block's bonded validators. This index remains constant during a block but is updated during the validator set update process which takes place in EndBlock.

Each validator's state is stored in a Validator struct:

proto/cosmos/staking/v1beta1/staking.proto

// Validator defines a validator, together with the total amount of the
// Validator's bond shares and their exchange rate to coins. Slashing results in
// a decrease in the exchange rate, allowing correct calculation of future
// undelegations without iterating over delegators. When coins are delegated to
// this validator, the validator is credited with a delegation whose number of
// bond shares is based on the amount of coins delegated divided by the current
// exchange rate. Voting power can be calculated as total bonded shares
// multiplied by exchange rate.
message Validator {
  option (gogoproto.equal)            = false;
  option (gogoproto.goproto_stringer) = false;
  option (gogoproto.goproto_getters)  = false;

  // operator_address defines the address of the validator's operator; bech encoded in JSON.
  string operator_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // consensus_pubkey is the consensus public key of the validator, as a Protobuf Any.
  google.protobuf.Any consensus_pubkey = 2 [(cosmos_proto.accepts_interface) = "cosmos.crypto.PubKey"];
  // jailed defined whether the validator has been jailed from bonded status or not.
  bool jailed = 3;
  // status is the validator status (bonded/unbonding/unbonded).
  BondStatus status = 4;
  // tokens define the delegated tokens (incl. self-delegation).
  string tokens = 5 [
    (cosmos_proto.scalar)  = "cosmos.Int",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
    (gogoproto.nullable)   = false
  ];
  // delegator_shares defines total shares issued to a validator's delegators.
  string delegator_shares = 6 [
    (cosmos_proto.scalar)  = "cosmos.Dec",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
    (gogoproto.nullable)   = false
  ];
  // description defines the description terms for the validator.
  Description description = 7 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
  // unbonding_height defines, if unbonding, the height at which this validator has begun unbonding.
  int64 unbonding_height = 8;
  // unbonding_time defines, if unbonding, the min time for the validator to complete unbonding.
  google.protobuf.Timestamp unbonding_time = 9
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true, (gogoproto.stdtime) = true];
  // commission defines the commission parameters.
  Commission commission = 10 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
  // min_self_delegation is the validator's self declared minimum self delegation.
  //
  // Since: cosmos-sdk 0.46
  string min_self_delegation = 11 [
    (cosmos_proto.scalar)  = "cosmos.Int",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
    (gogoproto.nullable)   = false
  ];

  // strictly positive if this validator's unbonding has been stopped by external modules
  int64 unbonding_on_hold_ref_count = 12;

  // list of unbonding ids, each uniquely identifing an unbonding of this validator
  repeated uint64 unbonding_ids = 13;
}

See full example on GitHubproto/cosmos/staking/v1beta1/staking.proto

// CommissionRates defines the initial commission rates to be used for creating
// a validator.
message CommissionRates {
  option (gogoproto.equal)            = true;
  option (gogoproto.goproto_stringer) = false;

  // rate is the commission rate charged to delegators, as a fraction.
  string rate = 1 [
    (cosmos_proto.scalar)  = "cosmos.Dec",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
    (gogoproto.nullable)   = false
  ];
  // max_rate defines the maximum commission rate which validator can ever charge, as a fraction.
  string max_rate = 2 [
    (cosmos_proto.scalar)  = "cosmos.Dec",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
    (gogoproto.nullable)   = false
  ];
  // max_change_rate defines the maximum daily increase of the validator commission, as a fraction.
  string max_change_rate = 3 [
    (cosmos_proto.scalar)  = "cosmos.Dec",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
    (gogoproto.nullable)   = false
  ];
}

// Commission defines commission parameters for a given validator.
message Commission {
  option (gogoproto.equal)            = true;
  option (gogoproto.goproto_stringer) = false;

  // commission_rates defines the initial commission rates to be used for creating a validator.
  CommissionRates commission_rates = 1
      [(gogoproto.embed) = true, (gogoproto.nullable) = false, (amino.dont_omitempty) = true];
  // update_time is the last time the commission rate was changed.
  google.protobuf.Timestamp update_time = 2
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true, (gogoproto.stdtime) = true];
}

// Description defines a validator description.
message Description {
  option (gogoproto.equal)            = true;
  option (gogoproto.goproto_stringer) = false;

  // moniker defines a human-readable name for the validator.
  string moniker = 1;
  // identity defines an optional identity signature (ex. UPort or Keybase).
  string identity = 2;
  // website defines an optional website link.
  string website = 3;
  // security_contact defines an optional email for security contact.
  string security_contact = 4;
  // details define other optional details.
  string details = 5;
}

See full example on GitHub

Delegation

Delegations are identified by combining DelegatorAddr (the address of the delegator) with the ValidatorAddr Delegators are indexed in the store as follows:

  • Delegation: 0x31 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddr -> ProtocolBuffer(delegation)

Stake holders may delegate coins to validators; under this circumstance their funds are held in a Delegation data structure. It is owned by one delegator, and is associated with the shares for one validator. The sender of the transaction is the owner of the bond.

proto/cosmos/staking/v1beta1/staking.proto

// Delegation represents the bond with tokens held by an account. It is
// owned by one delegator, and is associated with the voting power of one
// validator.
message Delegation {
  option (gogoproto.equal)            = false;
  option (gogoproto.goproto_getters)  = false;
  option (gogoproto.goproto_stringer) = false;

  // delegator_address is the bech32-encoded address of the delegator.
  string delegator_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // validator_address is the bech32-encoded address of the validator.
  string validator_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // shares define the delegation shares received.
  string shares = 3 [
    (cosmos_proto.scalar)  = "cosmos.Dec",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
    (gogoproto.nullable)   = false
  ];
}

See full example on GitHub

Delegator Shares

When one delegates tokens to a Validator, they are issued a number of delegator shares based on a dynamic exchange rate, calculated as follows from the total number of tokens delegated to the validator and the number of shares issued so far:

Shares per Token = validator.TotalShares() / validator.Tokens()

Only the number of shares received is stored on the DelegationEntry. When a delegator then Undelegates, the token amount they receive is calculated from the number of shares they currently hold and the inverse exchange rate:

Tokens per Share = validator.Tokens() / validatorShares()

These Shares are simply an accounting mechanism. They are not a fungible asset. The reason for this mechanism is to simplify the accounting around slashing. Rather than iteratively slashing the tokens of every delegation entry, instead the Validator's total bonded tokens can be slashed, effectively reducing the value of each issued delegator share.

UnbondingDelegation

Shares in a Delegation can be unbonded, but they must for some time exist as an UnbondingDelegation, where shares can be reduced if Byzantine behavior is detected.

UnbondingDelegation are indexed in the store as:

  • UnbondingDelegation: 0x32 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddr -> ProtocolBuffer(unbondingDelegation)

  • UnbondingDelegationsFromValidator: 0x33 | ValidatorAddrLen (1 byte) | ValidatorAddr | DelegatorAddrLen (1 byte) | DelegatorAddr -> nil

  • UnbondingDelegationByUnbondingId: 0x38 | UnbondingId -> 0x32 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorAddrUnbondingDelegation is used in queries, to lookup all unbonding delegations for a given delegator.

UnbondingDelegationsFromValidator is used in slashing, to lookup all unbonding delegations associated with a given validator that need to be slashed.

UnbondingDelegationByUnbondingId is an additional index that enables lookups for unbonding delegations by the unbonding IDs of the containing unbonding delegation entries.

A UnbondingDelegation object is created every time an unbonding is initiated.

proto/cosmos/staking/v1beta1/staking.proto

// UnbondingDelegation stores all of a single delegator's unbonding bonds
// for a single validator in an time-ordered list.
message UnbondingDelegation {
  option (gogoproto.equal)            = false;
  option (gogoproto.goproto_getters)  = false;
  option (gogoproto.goproto_stringer) = false;

  // delegator_address is the bech32-encoded address of the delegator.
  string delegator_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // validator_address is the bech32-encoded address of the validator.
  string validator_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // entries are the unbonding delegation entries.
  repeated UnbondingDelegationEntry entries = 3
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; // unbonding delegation entries
}

// UnbondingDelegationEntry defines an unbonding object with relevant metadata.
message UnbondingDelegationEntry {
  option (gogoproto.equal)            = true;
  option (gogoproto.goproto_stringer) = false;

  // creation_height is the height which the unbonding took place.
  int64 creation_height = 1;
  // completion_time is the unix time for unbonding completion.
  google.protobuf.Timestamp completion_time = 2
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true, (gogoproto.stdtime) = true];
  // initial_balance defines the tokens initially scheduled to receive at completion.
  string initial_balance = 3 [
    (cosmos_proto.scalar)  = "cosmos.Int",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
    (gogoproto.nullable)   = false
  ];
  // balance defines the tokens to receive at completion.
  string balance = 4 [
    (cosmos_proto.scalar)  = "cosmos.Int",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
    (gogoproto.nullable)   = false
  ];
  // Incrementing id that uniquely identifies this entry
  uint64 unbonding_id = 5;

  // Strictly positive if this entry's unbonding has been stopped by external modules
  int64 unbonding_on_hold_ref_count = 6;
}

See full example on GitHub

Redelegation

The bonded tokens worth of a Delegation may be instantly redelegated from a source validator to a different validator (destination validator). However when this occurs they must be tracked in a Redelegation object, whereby their shares can be slashed if their tokens have contributed to a Byzantine fault committed by the source validator.

Redelegation are indexed in the store as:

  • Redelegations: 0x34 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorSrcAddr | ValidatorDstAddr -> ProtocolBuffer(redelegation)

  • RedelegationsBySrc: 0x35 | ValidatorSrcAddrLen (1 byte) | ValidatorSrcAddr | ValidatorDstAddrLen (1 byte) | ValidatorDstAddr | DelegatorAddrLen (1 byte) | DelegatorAddr -> nil

  • RedelegationsByDst: 0x36 | ValidatorDstAddrLen (1 byte) | ValidatorDstAddr | ValidatorSrcAddrLen (1 byte) | ValidatorSrcAddr | DelegatorAddrLen (1 byte) | DelegatorAddr -> nil

  • RedelegationByUnbondingId: 0x38 | UnbondingId -> 0x34 | DelegatorAddrLen (1 byte) | DelegatorAddr | ValidatorAddrLen (1 byte) | ValidatorSrcAddr | ValidatorDstAddr

    Redelegations is used for queries, to lookup all redelegations for a given delegator.

    RedelegationsBySrc is used for slashing based on the ValidatorSrcAddr.

    RedelegationsByDst is used for slashing based on the ValidatorDstAddr

The first map here is used for queries, to lookup all redelegations for a given delegator. The second map is used for slashing based on the ValidatorSrcAddr, while the third map is for slashing based on the ValidatorDstAddr.

RedelegationByUnbondingId is an additional index that enables lookups for redelegations by the unbonding IDs of the containing redelegation entries.

A redelegation object is created every time a redelegation occurs. To prevent "redelegation hopping" redelegations may not occur under the situation that:

  • the (re)delegator already has another immature redelegation in progress with a destination to a validator (let's call it Validator X)

  • and, the (re)delegator is attempting to create a new redelegation where the source validator for this new redelegation is Validator X.

proto/cosmos/staking/v1beta1/staking.proto

// RedelegationEntry defines a redelegation object with relevant metadata.
message RedelegationEntry {
  option (gogoproto.equal)            = true;
  option (gogoproto.goproto_stringer) = false;

  // creation_height  defines the height which the redelegation took place.
  int64 creation_height = 1;
  // completion_time defines the unix time for redelegation completion.
  google.protobuf.Timestamp completion_time = 2
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true, (gogoproto.stdtime) = true];
  // initial_balance defines the initial balance when redelegation started.
  string initial_balance = 3 [
    (cosmos_proto.scalar)  = "cosmos.Int",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
    (gogoproto.nullable)   = false
  ];
  // shares_dst is the amount of destination-validator shares created by redelegation.
  string shares_dst = 4 [
    (cosmos_proto.scalar)  = "cosmos.Dec",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
    (gogoproto.nullable)   = false
  ];
  // Incrementing id that uniquely identifies this entry
  uint64 unbonding_id = 5;

  // Strictly positive if this entry's unbonding has been stopped by external modules
  int64 unbonding_on_hold_ref_count = 6;
}

// Redelegation contains the list of a particular delegator's redelegating bonds
// from a particular source validator to a particular destination validator.
message Redelegation {
  option (gogoproto.equal)            = false;
  option (gogoproto.goproto_getters)  = false;
  option (gogoproto.goproto_stringer) = false;

  // delegator_address is the bech32-encoded address of the delegator.
  string delegator_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // validator_src_address is the validator redelegation source operator address.
  string validator_src_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // validator_dst_address is the validator redelegation destination operator address.
  string validator_dst_address = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // entries are the redelegation entries.
  repeated RedelegationEntry entries = 4
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true]; // redelegation entries
}

See full example on GitHub

Queues

All queue objects are sorted by timestamp. The time used within any queue is firstly converted to UTC, rounded to the nearest nanosecond then sorted. The sortable time format used is a slight modification of the RFC3339Nano and uses the format string "2006-01-02T15:04:05.000000000". Notably this format:

  • right pads all zeros

  • drops the time zone info (we already use UTC)

In all cases, the stored timestamp represents the maturation time of the queue element.

UnbondingDelegationQueue

For the purpose of tracking progress of unbonding delegations the unbonding delegations queue is kept.

  • UnbondingDelegation: 0x41 | format(time) -> []DVPair

proto/cosmos/staking/v1beta1/staking.proto

// DVPair is struct that just has a delegator-validator pair with no other data.
// It is intended to be used as a marshalable pointer. For example, a DVPair can
// be used to construct the key to getting an UnbondingDelegation from state.
message DVPair {
  option (gogoproto.equal)            = false;
  option (gogoproto.goproto_getters)  = false;
  option (gogoproto.goproto_stringer) = false;

  string delegator_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string validator_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
}

See full example on GitHub

RedelegationQueue

For the purpose of tracking progress of redelegations the redelegation queue is kept.

  • RedelegationQueue: 0x42 | format(time) -> []DVVTriplet

proto/cosmos/staking/v1beta1/staking.proto

// DVVTriplet is struct that just has a delegator-validator-validator triplet
// with no other data. It is intended to be used as a marshalable pointer. For
// example, a DVVTriplet can be used to construct the key to getting a
// Redelegation from state.
message DVVTriplet {
  option (gogoproto.equal)            = false;
  option (gogoproto.goproto_getters)  = false;
  option (gogoproto.goproto_stringer) = false;

  string delegator_address     = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string validator_src_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string validator_dst_address = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"];
}

See full example on GitHub

ValidatorQueue

For the purpose of tracking progress of unbonding validators the validator queue is kept.

  • ValidatorQueueTime: 0x43 | format(time) -> []sdk.ValAddress

The stored object by each key is an array of validator operator addresses from which the validator object can be accessed. Typically it is expected that only a single validator record will be associated with a given timestamp however it is possible that multiple validators exist in the queue at the same location.

HistoricalInfo

HistoricalInfo objects are stored and pruned at each block such that the staking keeper persists the n most recent historical info defined by staking module parameter: HistoricalEntries.

proto/cosmos/staking/v1beta1/staking.proto

// HistoricalInfo contains header and validator information for a given block.
// It is stored as part of staking module's state, which persists the `n` most
// recent HistoricalInfo
// (`n` is set by the staking module's `historical_entries` parameter).
message HistoricalInfo {
  tendermint.types.Header header = 1 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
  repeated Validator      valset = 2 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
}

See full example on GitHub

At each BeginBlock, the staking keeper will persist the current Header and the Validators that committed the current block in a HistoricalInfo object. The Validators are sorted on their address to ensure that they are in a deterministic order. The oldest HistoricalEntries will be pruned to ensure that there only exist the parameter-defined number of historical entries.

State Transitions

Validators

State transitions in validators are performed on every EndBlock in order to check for changes in the active ValidatorSet.

A validator can be Unbonded, Unbonding or Bonded. Unbonded and Unbonding are collectively called Not Bonded. A validator can move directly between all the states, except for from Bonded to Unbonded.

Not bonded to Bonded

The following transition occurs when a validator's ranking in the ValidatorPowerIndex surpasses that of the LastValidator.

  • set validator.Status to Bonded

  • send the validator.Tokens from the NotBondedTokens to the BondedPool ModuleAccount

  • delete the existing record from ValidatorByPowerIndex

  • add a new updated record to the ValidatorByPowerIndex

  • update the Validator object for this validator

  • if it exists, delete any ValidatorQueue record for this validator

Bonded to Unbonding

When a validator begins the unbonding process the following operations occur:

  • send the validator.Tokens from the BondedPool to the NotBondedTokens ModuleAccount

  • set validator.Status to Unbonding

  • delete the existing record from ValidatorByPowerIndex

  • add a new updated record to the ValidatorByPowerIndex

  • update the Validator object for this validator

  • insert a new record into the ValidatorQueue for this validator

Unbonding to Unbonded

A validator moves from unbonding to unbonded when the ValidatorQueue object moves from bonded to unbonded

  • update the Validator object for this validator

  • set validator.Status to Unbonded

Jail/Unjail

when a validator is jailed it is effectively removed from the CometBFT set. this process may be also be reversed. the following operations occur:

  • set Validator.Jailed and update object

  • if jailed delete record from ValidatorByPowerIndex

  • if unjailed add record to ValidatorByPowerIndex

Jailed validators are not present in any of the following stores:

  • the power store (from consensus power to address)

Delegations

Delegate

When a delegation occurs both the validator and the delegation objects are affected

  • determine the delegators shares based on tokens delegated and the validator's exchange rate

  • remove tokens from the sending account

  • add shares the delegation object or add them to a created validator object

  • add new delegator shares and update the Validator object

  • transfer the delegation.Amount from the delegator's account to the BondedPool or the NotBondedPool ModuleAccount depending if the validator.Status is Bonded or not

  • delete the existing record from ValidatorByPowerIndex

  • add an new updated record to the ValidatorByPowerIndex

Begin Unbonding

As a part of the Undelegate and Complete Unbonding state transitions Unbond Delegation may be called.

  • subtract the unbonded shares from delegator

  • add the unbonded tokens to an UnbondingDelegationEntry

  • update the delegation or remove the delegation if there are no more shares

  • if the delegation is the operator of the validator and no more shares exist then trigger a jail validator

  • update the validator with removed the delegator shares and associated coins

  • if the validator state is Bonded, transfer the Coins worth of the unbonded shares from the BondedPool to the NotBondedPool ModuleAccount

  • remove the validator if it is unbonded and there are no more delegation shares.

  • remove the validator if it is unbonded and there are no more delegation shares

  • get a unique unbondingId and map it to the UnbondingDelegationEntry in UnbondingDelegationByUnbondingId

  • call the AfterUnbondingInitiated(unbondingId) hook

  • add the unbonding delegation to UnbondingDelegationQueue with the completion time set to UnbondingTime

Cancel an UnbondingDelegation Entry

When a cancel unbond delegation occurs both the validator, the delegation and an UnbondingDelegationQueue state will be updated.

  • if cancel unbonding delegation amount equals to the UnbondingDelegation entry balance, then the UnbondingDelegation entry deleted from UnbondingDelegationQueue.

  • if the cancel unbonding delegation amount is less than the UnbondingDelegationentry balance, then theUnbondingDelegationentry will be updated with new balance in theUnbondingDelegationQueue`.

  • cancel amount is Delegated back to the original validator.

Complete Unbonding

For undelegations which do not complete immediately, the following operations occur when the unbonding delegation queue element matures:

  • remove the entry from the UnbondingDelegation object

  • transfer the tokens from the NotBondedPool ModuleAccount to the delegator Account

Begin Redelegation

Redelegations affect the delegation, source and destination validators.

  • perform an unbond delegation from the source validator to retrieve the tokens worth of the unbonded shares

  • using the unbonded tokens, Delegate them to the destination validator

  • if the sourceValidator.Status is Bonded, and the destinationValidator is not, transfer the newly delegated tokens from the BondedPool to the NotBondedPool ModuleAccount

  • otherwise, if the sourceValidator.Status is not Bonded, and the destinationValidator is Bonded, transfer the newly delegated tokens from the NotBondedPool to the BondedPool ModuleAccount

  • record the token amount in an new entry in the relevant Redelegation

From when a redelegation begins until it completes, the delegator is in a state of "pseudo-unbonding", and can still be slashed for infractions that occurred before the redelegation began.

Complete Redelegation

When a redelegations complete the following occurs:

  • remove the entry from the Redelegation object

Slashing

Slash Validator

When a Validator is slashed, the following occurs:

  • The total slashAmount is calculated as the slashFactor (a chain parameter) * TokensFromConsensusPower, the total number of tokens bonded to the validator at the time of the infraction.

  • Every unbonding delegation and pseudo-unbonding redelegation such that the infraction occured before the unbonding or redelegation began from the validator are slashed by the slashFactor percentage of the initialBalance.

  • Each amount slashed from redelegations and unbonding delegations is subtracted from the total slash amount.

  • The remaingSlashAmount is then slashed from the validator's tokens in the BondedPool or NonBondedPool depending on the validator's status. This reduces the total supply of tokens.

In the case of a slash due to any infraction that requires evidence to submitted (for example double-sign), the slash occurs at the block where the evidence is included, not at the block where the infraction occured. Put otherwise, validators are not slashed retroactively, only when they are caught.

Slash Unbonding Delegation

When a validator is slashed, so are those unbonding delegations from the validator that began unbonding after the time of the infraction. Every entry in every unbonding delegation from the validator is slashed by slashFactor. The amount slashed is calculated from the InitialBalance of the delegation and is capped to prevent a resulting negative balance. Completed (or mature) unbondings are not slashed.

Slash Redelegation

When a validator is slashed, so are all redelegations from the validator that began after the infraction. Redelegations are slashed by slashFactor. Redelegations that began before the infraction are not slashed. The amount slashed is calculated from the InitialBalance of the delegation and is capped to prevent a resulting negative balance. Mature redelegations (that have completed pseudo-unbonding) are not slashed.

How Shares are calculated

At any given point in time, each validator has a number of tokens, T, and has a number of shares issued, S. Each delegator, i, holds a number of shares, S_i. The number of tokens is the sum of all tokens delegated to the validator, plus the rewards, minus the slashes.

The delegator is entitled to a portion of the underlying tokens proportional to their proportion of shares. So delegator i is entitled to T * S_i / S of the validator's tokens.

When a delegator delegates new tokens to the validator, they receive a number of shares proportional to their contribution. So when delegator j delegates T_j tokens, they receive S_j = S * T_j / T shares. The total number of tokens is now T + T_j, and the total number of shares is S + S_j. js proportion of the shares is the same as their proportion of the total tokens contributed: (S + S_j) / S = (T + T_j) / T.

A special case is the initial delegation, when T = 0 and S = 0, so T_j / T is undefined. For the initial delegation, delegator j who delegates T_j tokens receive S_j = T_j shares. So a validator that hasn't received any rewards and has not been slashed will have T = S.

Messages

In this section we describe the processing of the staking messages and the corresponding updates to the state. All created/modified state objects specified by each message are defined within the state section.

MsgCreateValidator

A validator is created using the MsgCreateValidator message. The validator must be created with an initial delegation from the operator.

proto/cosmos/staking/v1beta1/tx.proto

// CreateValidator defines a method for creating a new validator.
rpc CreateValidator(MsgCreateValidator) returns (MsgCreateValidatorResponse);

See full example on GitHubproto/cosmos/staking/v1beta1/tx.proto

// MsgCreateValidator defines a SDK message for creating a new validator.
message MsgCreateValidator {
  // NOTE(fdymylja): this is a particular case in which
  // if validator_address == delegator_address then only one
  // is expected to sign, otherwise both are.
  option (cosmos.msg.v1.signer) = "delegator_address";
  option (cosmos.msg.v1.signer) = "validator_address";
  option (amino.name)           = "cosmos-sdk/MsgCreateValidator";

  option (gogoproto.equal)           = false;
  option (gogoproto.goproto_getters) = false;

  Description     description         = 1 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
  CommissionRates commission          = 2 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
  string          min_self_delegation = 3 [
    (cosmos_proto.scalar)  = "cosmos.Int",
    (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
    (gogoproto.nullable)   = false
  ];
  string                   delegator_address = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string                   validator_address = 5 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  google.protobuf.Any      pubkey            = 6 [(cosmos_proto.accepts_interface) = "cosmos.crypto.PubKey"];
  cosmos.base.v1beta1.Coin value             = 7 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
}

See full example on GitHub

This message is expected to fail if:

  • another validator with this operator address is already registered

  • another validator with this pubkey is already registered

  • the initial self-delegation tokens are of a denom not specified as the bonding denom

  • the commission parameters are faulty, namely:

    • MaxRate is either > 1 or < 0

    • the initial Rate is either negative or > MaxRate

    • the initial MaxChangeRate is either negative or > MaxRate

  • the description fields are too large

This message creates and stores the Validator object at appropriate indexes. Additionally a self-delegation is made with the initial tokens delegation tokens Delegation. The validator always starts as unbonded but may be bonded in the first end-block.

MsgEditValidator

The Description, CommissionRate of a validator can be updated using the MsgEditValidator message.

proto/cosmos/staking/v1beta1/tx.proto

// EditValidator defines a method for editing an existing validator.
rpc EditValidator(MsgEditValidator) returns (MsgEditValidatorResponse);

See full example on GitHubproto/cosmos/staking/v1beta1/tx.proto

// MsgEditValidator defines a SDK message for editing an existing validator.
message MsgEditValidator {
  option (cosmos.msg.v1.signer) = "validator_address";
  option (amino.name)           = "cosmos-sdk/MsgEditValidator";

  option (gogoproto.equal)           = false;
  option (gogoproto.goproto_getters) = false;

  Description description       = 1 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
  string      validator_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];

  // We pass a reference to the new commission rate and min self delegation as
  // it's not mandatory to update. If not updated, the deserialized rate will be
  // zero with no way to distinguish if an update was intended.
  // REF: #2373
  string commission_rate = 3
      [(cosmos_proto.scalar) = "cosmos.Dec", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec"];
  string min_self_delegation = 4
      [(cosmos_proto.scalar) = "cosmos.Int", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int"];
}

See full example on GitHub

This message is expected to fail if:

  • the initial CommissionRate is either negative or > MaxRate

  • the CommissionRate has already been updated within the previous 24 hours

  • the CommissionRate is > MaxChangeRate

  • the description fields are too large

This message stores the updated Validator object.

MsgDelegate

Within this message the delegator provides coins, and in return receives some amount of their validator's (newly created) delegator-shares that are assigned to Delegation.Shares.

proto/cosmos/staking/v1beta1/tx.proto

// Delegate defines a method for performing a delegation of coins
// from a delegator to a validator.
rpc Delegate(MsgDelegate) returns (MsgDelegateResponse);

See full example on GitHubproto/cosmos/staking/v1beta1/tx.proto

// MsgDelegate defines a SDK message for performing a delegation of coins
// from a delegator to a validator.
message MsgDelegate {
  option (cosmos.msg.v1.signer) = "delegator_address";
  option (amino.name)           = "cosmos-sdk/MsgDelegate";

  option (gogoproto.equal)           = false;
  option (gogoproto.goproto_getters) = false;

  string                   delegator_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string                   validator_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  cosmos.base.v1beta1.Coin amount            = 3 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
}

See full example on GitHub

This message is expected to fail if:

  • the validator does not exist

  • the Amount Coin has a denomination different than one defined by params.BondDenom

  • the exchange rate is invalid, meaning the validator has no tokens (due to slashing) but there are outstanding shares

  • the amount delegated is less than the minimum allowed delegation

If an existing Delegation object for provided addresses does not already exist then it is created as part of this message otherwise the existing Delegation is updated to include the newly received shares.

The delegator receives newly minted shares at the current exchange rate. The exchange rate is the number of existing shares in the validator divided by the number of currently delegated tokens.

The validator is updated in the ValidatorByPower index, and the delegation is tracked in validator object in the Validators index.

It is possible to delegate to a jailed validator, the only difference being it will not be added to the power index until it is unjailed.

MsgUndelegate

The MsgUndelegate message allows delegators to undelegate their tokens from validator.

proto/cosmos/staking/v1beta1/tx.proto

// Undelegate defines a method for performing an undelegation from a
// delegate and a validator.
rpc Undelegate(MsgUndelegate) returns (MsgUndelegateResponse);

See full example on GitHubproto/cosmos/staking/v1beta1/tx.proto

// MsgUndelegate defines a SDK message for performing an undelegation from a
// delegate and a validator.
message MsgUndelegate {
  option (cosmos.msg.v1.signer) = "delegator_address";
  option (amino.name)           = "cosmos-sdk/MsgUndelegate";

  option (gogoproto.equal)           = false;
  option (gogoproto.goproto_getters) = false;

  string                   delegator_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string                   validator_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  cosmos.base.v1beta1.Coin amount            = 3 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
}

See full example on GitHub

This message returns a response containing the completion time of the undelegation:

proto/cosmos/staking/v1beta1/tx.proto

// MsgUndelegateResponse defines the Msg/Undelegate response type.
message MsgUndelegateResponse {
  google.protobuf.Timestamp completion_time = 1
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true, (gogoproto.stdtime) = true];
}

See full example on GitHub

This message is expected to fail if:

  • the delegation doesn't exist

  • the validator doesn't exist

  • the delegation has less shares than the ones worth of Amount

  • existing UnbondingDelegation has maximum entries as defined by params.MaxEntries

  • the Amount has a denomination different than one defined by params.BondDenom

When this message is processed the following actions occur:

  • validator's DelegatorShares and the delegation's Shares are both reduced by the message SharesAmount

  • calculate the token worth of the shares remove that amount tokens held within the validator

  • with those removed tokens, if the validator is:

    • Bonded - add them to an entry in UnbondingDelegation (create UnbondingDelegation if it doesn't exist) with a completion time a full unbonding period from the current time. Update pool shares to reduce BondedTokens and increase NotBondedTokens by token worth of the shares.

    • Unbonding - add them to an entry in UnbondingDelegation (create UnbondingDelegation if it doesn't exist) with the same completion time as the validator (UnbondingMinTime).

    • Unbonded - then send the coins the message DelegatorAddr

  • if there are no more Shares in the delegation, then the delegation object is removed from the store

    • under this situation if the delegation is the validator's self-delegation then also jail the validator.

MsgCancelUnbondingDelegation

The MsgCancelUnbondingDelegation message allows delegators to cancel the unbondingDelegation entry and delegate back to a previous validator.

proto/cosmos/staking/v1beta1/tx.proto

// CancelUnbondingDelegation defines a method for performing canceling the unbonding delegation
// and delegate back to previous validator.
//
// Since: cosmos-sdk 0.46
rpc CancelUnbondingDelegation(MsgCancelUnbondingDelegation) returns (MsgCancelUnbondingDelegationResponse);

See full example on GitHubproto/cosmos/staking/v1beta1/tx.proto

// MsgCancelUnbondingDelegation defines the SDK message for performing a cancel unbonding delegation for delegator
//
// Since: cosmos-sdk 0.46
message MsgCancelUnbondingDelegation {
  option (cosmos.msg.v1.signer)      = "delegator_address";
  option (amino.name)                = "cosmos-sdk/MsgCancelUnbondingDelegation";
  option (gogoproto.equal)           = false;
  option (gogoproto.goproto_getters) = false;

  string delegator_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string validator_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // amount is always less than or equal to unbonding delegation entry balance
  cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
  // creation_height is the height which the unbonding took place.
  int64 creation_height = 4;
}

See full example on GitHub

This message is expected to fail if:

  • the unbondingDelegation entry is already processed.

  • the cancel unbonding delegation amount is greater than the unbondingDelegation entry balance.

  • the cancel unbonding delegation height doesn't exist in the unbondingDelegationQueue of the delegator.

When this message is processed the following actions occur:

  • if the unbondingDelegation Entry balance is zero

    • in this condition unbondingDelegation entry will be removed from unbondingDelegationQueue.

    • otherwise unbondingDelegationQueue will be updated with new unbondingDelegation entry balance and initial balance

  • the validator's DelegatorShares and the delegation's Shares are both increased by the message Amount.

MsgBeginRedelegate

The redelegation command allows delegators to instantly switch validators. Once the unbonding period has passed, the redelegation is automatically completed in the EndBlocker.

proto/cosmos/staking/v1beta1/tx.proto

// BeginRedelegate defines a method for performing a redelegation
// of coins from a delegator and source validator to a destination validator.
rpc BeginRedelegate(MsgBeginRedelegate) returns (MsgBeginRedelegateResponse);

See full example on GitHubproto/cosmos/staking/v1beta1/tx.proto

// MsgBeginRedelegate defines a SDK message for performing a redelegation
// of coins from a delegator and source validator to a destination validator.
message MsgBeginRedelegate {
  option (cosmos.msg.v1.signer) = "delegator_address";
  option (amino.name)           = "cosmos-sdk/MsgBeginRedelegate";

  option (gogoproto.equal)           = false;
  option (gogoproto.goproto_getters) = false;

  string                   delegator_address     = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string                   validator_src_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  string                   validator_dst_address = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  cosmos.base.v1beta1.Coin amount                = 4 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
}

See full example on GitHub

This message returns a response containing the completion time of the redelegation:

proto/cosmos/staking/v1beta1/tx.proto


// MsgBeginRedelegateResponse defines the Msg/BeginRedelegate response type.
message MsgBeginRedelegateResponse {
  google.protobuf.Timestamp completion_time = 1
      [(gogoproto.nullable) = false, (amino.dont_omitempty) = true, (gogoproto.stdtime) = true];
}

See full example on GitHub

This message is expected to fail if:

  • the delegation doesn't exist

  • the source or destination validators don't exist

  • the delegation has less shares than the ones worth of Amount

  • the source validator has a receiving redelegation which is not matured (aka. the redelegation may be transitive)

  • existing Redelegation has maximum entries as defined by params.MaxEntries

  • the Amount Coin has a denomination different than one defined by params.BondDenom

When this message is processed the following actions occur:

  • the source validator's DelegatorShares and the delegations Shares are both reduced by the message SharesAmount

  • calculate the token worth of the shares remove that amount tokens held within the source validator.

  • if the source validator is:

    • Bonded - add an entry to the Redelegation (create Redelegation if it doesn't exist) with a completion time a full unbonding period from the current time. Update pool shares to reduce BondedTokens and increase NotBondedTokens by token worth of the shares (this may be effectively reversed in the next step however).

    • Unbonding - add an entry to the Redelegation (create Redelegation if it doesn't exist) with the same completion time as the validator (UnbondingMinTime).

    • Unbonded - no action required in this step

  • Delegate the token worth to the destination validator, possibly moving tokens back to the bonded state.

  • if there are no more Shares in the source delegation, then the source delegation object is removed from the store

    • under this situation if the delegation is the validator's self-delegation then also jail the validator.

MsgUpdateParams

The MsgUpdateParams update the staking module parameters. The params are updated through a governance proposal where the signer is the gov module account address.

proto/cosmos/staking/v1beta1/tx.proto

// MsgUpdateParams is the Msg/UpdateParams request type.
//
// Since: cosmos-sdk 0.47
message MsgUpdateParams {
  option (cosmos.msg.v1.signer) = "authority";
  option (amino.name)           = "cosmos-sdk/x/staking/MsgUpdateParams";

  // authority is the address that controls the module (defaults to x/gov unless overwritten).
  string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
  // params defines the x/staking parameters to update.
  //
  // NOTE: All parameters must be supplied.
  Params params = 2 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];
};

See full example on GitHub

The message handling can fail if:

  • signer is not the authority defined in the staking keeper (usually the gov module account).

Begin-Block

Each abci begin block call, the historical info will get stored and pruned according to the HistoricalEntries parameter.

Historical Info Tracking

If the HistoricalEntries parameter is 0, then the BeginBlock performs a no-op.

Otherwise, the latest historical info is stored under the key historicalInfoKey|height, while any entries older than height - HistoricalEntries is deleted. In most cases, this results in a single entry being pruned per block. However, if the parameter HistoricalEntries has changed to a lower value there will be multiple entries in the store that must be pruned.

End-Block

Each abci end block call, the operations to update queues and validator set changes are specified to execute.

Validator Set Changes

The staking validator set is updated during this process by state transitions that run at the end of every block. As a part of this process any updated validators are also returned back to CometBFT for inclusion in the CometBFT validator set which is responsible for validating CometBFT messages at the consensus layer. Operations are as following:

  • the new validator set is taken as the top params.MaxValidators number of validators retrieved from the ValidatorsByPower index

  • the previous validator set is compared with the new validator set:

    • missing validators begin unbonding and their Tokens are transferred from the BondedPool to the NotBondedPool ModuleAccount

    • new validators are instantly bonded and their Tokens are transferred from the NotBondedPool to the BondedPool ModuleAccount

In all cases, any validators leaving or entering the bonded validator set or changing balances and staying within the bonded validator set incur an update message reporting their new consensus power which is passed back to CometBFT.

The LastTotalPower and LastValidatorsPower hold the state of the total power and validator power from the end of the last block, and are used to check for changes that have occurred in ValidatorsByPower and the total new power, which is calculated during EndBlock.

Queues

Within staking, certain state-transitions are not instantaneous but take place over a duration of time (typically the unbonding period). When these transitions are mature certain operations must take place in order to complete the state operation. This is achieved through the use of queues which are checked/processed at the end of each block.

Unbonding Validators

When a validator is kicked out of the bonded validator set (either through being jailed, or not having sufficient bonded tokens) it begins the unbonding process along with all its delegations begin unbonding (while still being delegated to this validator). At this point the validator is said to be an "unbonding validator", whereby it will mature to become an "unbonded validator" after the unbonding period has passed.

Each block the validator queue is to be checked for mature unbonding validators (namely with a completion time <= current time and completion height <= current block height). At this point any mature validators which do not have any delegations remaining are deleted from state. For all other mature unbonding validators that still have remaining delegations, the validator.Status is switched from types.Unbonding to types.Unbonded.

Unbonding operations can be put on hold by external modules via the PutUnbondingOnHold(unbondingId) method. As a result, an unbonding operation (e.g., an unbonding delegation) that is on hold, cannot complete even if it reaches maturity. For an unbonding operation with unbondingId to eventually complete (after it reaches maturity), every call to PutUnbondingOnHold(unbondingId) must be matched by a call to UnbondingCanComplete(unbondingId).

Unbonding Delegations

Complete the unbonding of all mature UnbondingDelegations.Entries within the UnbondingDelegations queue with the following procedure:

  • transfer the balance coins to the delegator's wallet address

  • remove the mature entry from UnbondingDelegation.Entries

  • remove the UnbondingDelegation object from the store if there are no remaining entries.

Redelegations

Complete the unbonding of all mature Redelegation.Entries within the Redelegations queue with the following procedure:

  • remove the mature entry from Redelegation.Entries

  • remove the Redelegation object from the store if there are no remaining entries.

Hooks

Other modules may register operations to execute when a certain event has occurred within staking. These events can be registered to execute either right Before or After the staking event (as per the hook name). The following hooks can registered with staking:

  • AfterValidatorCreated(Context, ValAddress) error

    • called when a validator is created

  • BeforeValidatorModified(Context, ValAddress) error

    • called when a validator's state is changed

  • AfterValidatorRemoved(Context, ConsAddress, ValAddress) error

    • called when a validator is deleted

  • AfterValidatorBonded(Context, ConsAddress, ValAddress) error

    • called when a validator is bonded

  • AfterValidatorBeginUnbonding(Context, ConsAddress, ValAddress) error

    • called when a validator begins unbonding

  • BeforeDelegationCreated(Context, AccAddress, ValAddress) error

    • called when a delegation is created

  • BeforeDelegationSharesModified(Context, AccAddress, ValAddress) error

    • called when a delegation's shares are modified

  • AfterDelegationModified(Context, AccAddress, ValAddress) error

    • called when a delegation is created or modified

  • BeforeDelegationRemoved(Context, AccAddress, ValAddress) error

    • called when a delegation is removed

  • AfterUnbondingInitiated(Context, UnbondingID)

    • called when an unbonding operation (validator unbonding, unbonding delegation, redelegation) was initiated

Events

The staking module emits the following events:

EndBlocker

Msg's

MsgCreateValidator

MsgEditValidator

MsgDelegate

MsgUndelegate

  • [0] Time is formatted in the RFC3339 standard

MsgCancelUnbondingDelegation

MsgBeginRedelegate

  • [0] Time is formatted in the RFC3339 standard

Parameters

The staking module contains the following parameters:

Client

CLI

A user can query and interact with the staking module using the CLI.

Query

The query commands allows users to query staking state.

simd query staking --help

delegation

The delegation command allows users to query delegations for an individual delegator on an individual validator.

Usage:

simd query staking delegation [delegator-addr] [validator-addr] [flags]

Example:

simd query staking delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

Example Output:

balance:
  amount: "10000000000"
  denom: stake
delegation:
  delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
  shares: "10000000000.000000000000000000"
  validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

delegations

The delegations command allows users to query delegations for an individual delegator on all validators.

Usage:

simd query staking delegations [delegator-addr] [flags]

Example:

simd query staking delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p

Example Output:

delegation_responses:
- balance:
    amount: "10000000000"
    denom: stake
  delegation:
    delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
    shares: "10000000000.000000000000000000"
    validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj
- balance:
    amount: "10000000000"
    denom: stake
  delegation:
    delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
    shares: "10000000000.000000000000000000"
    validator_address: cosmosvaloper1x20lytyf6zkcrv5edpkfkn8sz578qg5sqfyqnp
pagination:
  next_key: null
  total: "0"

delegations-to

The delegations-to command allows users to query delegations on an individual validator.

Usage:

simd query staking delegations-to [validator-addr] [flags]

Example:

simd query staking delegations-to cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

Example Output:

- balance:
    amount: "504000000"
    denom: stake
  delegation:
    delegator_address: cosmos1q2qwwynhv8kh3lu5fkeex4awau9x8fwt45f5cp
    shares: "504000000.000000000000000000"
    validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj
- balance:
    amount: "78125000000"
    denom: uixo
  delegation:
    delegator_address: cosmos1qvppl3479hw4clahe0kwdlfvf8uvjtcd99m2ca
    shares: "78125000000.000000000000000000"
    validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj
pagination:
  next_key: null
  total: "0"

historical-info

The historical-info command allows users to query historical information at given height.

Usage:

simd query staking historical-info [height] [flags]

Example:

simd query staking historical-info 10

Example Output:

header:
  app_hash: Lbx8cXpI868wz8sgp4qPYVrlaKjevR5WP/IjUxwp3oo=
  chain_id: testnet
  consensus_hash: BICRvH3cKD93v7+R1zxE2ljD34qcvIZ0Bdi389qtoi8=
  data_hash: 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
  evidence_hash: 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
  height: "10"
  last_block_id:
    hash: RFbkpu6pWfSThXxKKl6EZVDnBSm16+U0l0xVjTX08Fk=
    part_set_header:
      hash: vpIvXD4rxD5GM4MXGz0Sad9I7//iVYLzZsEU4BVgWIU=
      total: 1
  last_commit_hash: Ne4uXyx4QtNp4Zx89kf9UK7oG9QVbdB6e7ZwZkhy8K0=
  last_results_hash: 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
  next_validators_hash: nGBgKeWBjoxeKFti00CxHsnULORgKY4LiuQwBuUrhCs=
  proposer_address: mMEP2c2IRPLr99LedSRtBg9eONM=
  time: "2021-10-01T06:00:49.785790894Z"
  validators_hash: nGBgKeWBjoxeKFti00CxHsnULORgKY4LiuQwBuUrhCs=
  version:
    app: "0"
    block: "11"
valset:
- commission:
    commission_rates:
      max_change_rate: "0.010000000000000000"
      max_rate: "0.200000000000000000"
      rate: "0.100000000000000000"
    update_time: "2021-10-01T05:52:50.380144238Z"
  consensus_pubkey:
    '@type': /cosmos.crypto.ed25519.PubKey
    key: Auxs3865HpB/EfssYOzfqNhEJjzys2Fo6jD5B8tPgC8=
  delegator_shares: "10000000.000000000000000000"
  description:
    details: ""
    identity: ""
    moniker: myvalidator
    security_contact: ""
    website: ""
  jailed: false
  min_self_delegation: "1"
  operator_address: cosmosvaloper1rne8lgs98p0jqe82sgt0qr4rdn4hgvmgp9ggcc
  status: BOND_STATUS_BONDED
  tokens: "10000000"
  unbonding_height: "0"
  unbonding_time: "1970-01-01T00:00:00Z"

params

The params command allows users to query values set as staking parameters.

Usage:

simd query staking params [flags]

Example:

simd query staking params

Example Output:

bond_denom: stake
historical_entries: 10000
max_entries: 7
max_validators: 50
unbonding_time: 1814400s

pool

The pool command allows users to query values for amounts stored in the staking pool.

Usage:

simd q staking pool [flags]

Example:

simd q staking pool

Example Output:

bonded_tokens: "10000000"
not_bonded_tokens: "0"

redelegation

The redelegation command allows users to query a redelegation record based on delegator and a source and destination validator address.

Usage:

simd query staking redelegation [delegator-addr] [src-validator-addr] [dst-validator-addr] [flags]

Example:

simd query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

Example Output:

pagination: null
redelegation_responses:
- entries:
  - balance: "50000000"
    redelegation_entry:
      completion_time: "2021-10-24T20:33:21.960084845Z"
      creation_height: 2.382847e+06
      initial_balance: "50000000"
      shares_dst: "50000000.000000000000000000"
  - balance: "5000000000"
    redelegation_entry:
      completion_time: "2021-10-25T21:33:54.446846862Z"
      creation_height: 2.397271e+06
      initial_balance: "5000000000"
      shares_dst: "5000000000.000000000000000000"
  redelegation:
    delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
    entries: null
    validator_dst_address: cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm
    validator_src_address: cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm

redelegations

The redelegations command allows users to query all redelegation records for an individual delegator.

Usage:

simd query staking redelegations [delegator-addr] [flags]

Example:

simd query staking redelegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p

Example Output:

pagination:
  next_key: null
  total: "0"
redelegation_responses:
- entries:
  - balance: "50000000"
    redelegation_entry:
      completion_time: "2021-10-24T20:33:21.960084845Z"
      creation_height: 2.382847e+06
      initial_balance: "50000000"
      shares_dst: "50000000.000000000000000000"
  - balance: "5000000000"
    redelegation_entry:
      completion_time: "2021-10-25T21:33:54.446846862Z"
      creation_height: 2.397271e+06
      initial_balance: "5000000000"
      shares_dst: "5000000000.000000000000000000"
  redelegation:
    delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
    entries: null
    validator_dst_address: cosmosvaloper1uccl5ugxrm7vqlzwqr04pjd320d2fz0z3hc6vm
    validator_src_address: cosmosvaloper1zppjyal5emta5cquje8ndkpz0rs046m7zqxrpp
- entries:
  - balance: "562770000000"
    redelegation_entry:
      completion_time: "2021-10-25T21:42:07.336911677Z"
      creation_height: 2.39735e+06
      initial_balance: "562770000000"
      shares_dst: "562770000000.000000000000000000"
  redelegation:
    delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
    entries: null
    validator_dst_address: cosmosvaloper1uccl5ugxrm7vqlzwqr04pjd320d2fz0z3hc6vm
    validator_src_address: cosmosvaloper1zppjyal5emta5cquje8ndkpz0rs046m7zqxrpp

redelegations-from

The redelegations-from command allows users to query delegations that are redelegating from a validator.

Usage:

simd query staking redelegations-from [validator-addr] [flags]

Example:

simd query staking redelegations-from cosmosvaloper1y4rzzrgl66eyhzt6gse2k7ej3zgwmngeleucjy

Example Output:

pagination:
  next_key: null
  total: "0"
redelegation_responses:
- entries:
  - balance: "50000000"
    redelegation_entry:
      completion_time: "2021-10-24T20:33:21.960084845Z"
      creation_height: 2.382847e+06
      initial_balance: "50000000"
      shares_dst: "50000000.000000000000000000"
  - balance: "5000000000"
    redelegation_entry:
      completion_time: "2021-10-25T21:33:54.446846862Z"
      creation_height: 2.397271e+06
      initial_balance: "5000000000"
      shares_dst: "5000000000.000000000000000000"
  redelegation:
    delegator_address: cosmos1pm6e78p4pgn0da365plzl4t56pxy8hwtqp2mph
    entries: null
    validator_dst_address: cosmosvaloper1uccl5ugxrm7vqlzwqr04pjd320d2fz0z3hc6vm
    validator_src_address: cosmosvaloper1y4rzzrgl66eyhzt6gse2k7ej3zgwmngeleucjy
- entries:
  - balance: "221000000"
    redelegation_entry:
      completion_time: "2021-10-05T21:05:45.669420544Z"
      creation_height: 2.120693e+06
      initial_balance: "221000000"
      shares_dst: "221000000.000000000000000000"
  redelegation:
    delegator_address: cosmos1zqv8qxy2zgn4c58fz8jt8jmhs3d0attcussrf6
    entries: null
    validator_dst_address: cosmosvaloper10mseqwnwtjaqfrwwp2nyrruwmjp6u5jhah4c3y
    validator_src_address: cosmosvaloper1y4rzzrgl66eyhzt6gse2k7ej3zgwmngeleucjy

unbonding-delegation

The unbonding-delegation command allows users to query unbonding delegations for an individual delegator on an individual validator.

Usage:

simd query staking unbonding-delegation [delegator-addr] [validator-addr] [flags]

Example:

simd query staking unbonding-delegation cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

Example Output:

delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
entries:
- balance: "52000000"
  completion_time: "2021-11-02T11:35:55.391594709Z"
  creation_height: "55078"
  initial_balance: "52000000"
validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

unbonding-delegations

The unbonding-delegations command allows users to query all unbonding-delegations records for one delegator.

Usage:

simd query staking unbonding-delegations [delegator-addr] [flags]

Example:

simd query staking unbonding-delegations cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p

Example Output:

pagination:
  next_key: null
  total: "0"
unbonding_responses:
- delegator_address: cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p
  entries:
  - balance: "52000000"
    completion_time: "2021-11-02T11:35:55.391594709Z"
    creation_height: "55078"
    initial_balance: "52000000"
  validator_address: cosmosvaloper1t8ehvswxjfn3ejzkjtntcyrqwvmvuknzmvtaaa

unbonding-delegations-from

The unbonding-delegations-from command allows users to query delegations that are unbonding from a validator.

Usage:

simd query staking unbonding-delegations-from [validator-addr] [flags]

Example:

simd query staking unbonding-delegations-from cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

Example Output:

pagination:
  next_key: null
  total: "0"
unbonding_responses:
- delegator_address: cosmos1qqq9txnw4c77sdvzx0tkedsafl5s3vk7hn53fn
  entries:
  - balance: "150000000"
    completion_time: "2021-11-01T21:41:13.098141574Z"
    creation_height: "46823"
    initial_balance: "150000000"
  validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj
- delegator_address: cosmos1peteje73eklqau66mr7h7rmewmt2vt99y24f5z
  entries:
  - balance: "24000000"
    completion_time: "2021-10-31T02:57:18.192280361Z"
    creation_height: "21516"
    initial_balance: "24000000"
  validator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

validator

The validator command allows users to query details about an individual validator.

Usage:

simd query staking validator [validator-addr] [flags]

Example:

simd query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj

Example Output:

commission:
  commission_rates:
    max_change_rate: "0.020000000000000000"
    max_rate: "0.200000000000000000"
    rate: "0.050000000000000000"
  update_time: "2021-10-01T19:24:52.663191049Z"
consensus_pubkey:
  '@type': /cosmos.crypto.ed25519.PubKey
  key: sIiexdJdYWn27+7iUHQJDnkp63gq/rzUq1Y+fxoGjXc=
delegator_shares: "32948270000.000000000000000000"
description:
  details: Witval is the validator arm from Vitwit. Vitwit is into software consulting
    and services business since 2015. We are working closely with Cosmos ecosystem
    since 2018. We are also building tools for the ecosystem, Aneka is our explorer
    for the cosmos ecosystem.
  identity: 51468B615127273A
  moniker: Witval
  security_contact: ""
  website: ""
jailed: false
min_self_delegation: "1"
operator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj
status: BOND_STATUS_BONDED
tokens: "32948270000"
unbonding_height: "0"
unbonding_time: "1970-01-01T00:00:00Z"

validators

The validators command allows users to query details about all validators on a network.

Usage:

simd query staking validators [flags]

Example:

simd query staking validators

Example Output:

pagination:
  next_key: FPTi7TKAjN63QqZh+BaXn6gBmD5/
  total: "0"
validators:
commission:
  commission_rates:
    max_change_rate: "0.020000000000000000"
    max_rate: "0.200000000000000000"
    rate: "0.050000000000000000"
  update_time: "2021-10-01T19:24:52.663191049Z"
consensus_pubkey:
  '@type': /cosmos.crypto.ed25519.PubKey
  key: sIiexdJdYWn27+7iUHQJDnkp63gq/rzUq1Y+fxoGjXc=
delegator_shares: "32948270000.000000000000000000"
description:
    details: Witval is the validator arm from Vitwit. Vitwit is into software consulting
      and services business since 2015. We are working closely with Cosmos ecosystem
      since 2018. We are also building tools for the ecosystem, Aneka is our explorer
      for the cosmos ecosystem.
    identity: 51468B615127273A
    moniker: Witval
    security_contact: ""
    website: ""
  jailed: false
  min_self_delegation: "1"
  operator_address: cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj
  status: BOND_STATUS_BONDED
  tokens: "32948270000"
  unbonding_height: "0"
  unbonding_time: "1970-01-01T00:00:00Z"
- commission:
    commission_rates:
      max_change_rate: "0.100000000000000000"
      max_rate: "0.200000000000000000"
      rate: "0.050000000000000000"
    update_time: "2021-10-04T18:02:21.446645619Z"
  consensus_pubkey:
    '@type': /cosmos.crypto.ed25519.PubKey
    key: GDNpuKDmCg9GnhnsiU4fCWktuGUemjNfvpCZiqoRIYA=
  delegator_shares: "559343421.000000000000000000"
  description:
    details: Noderunners is a professional validator in POS networks. We have a huge
      node running experience, reliable soft and hardware. Our commissions are always
      low, our support to delegators is always full. Stake with us and start receiving
      your Cosmos rewards now!
    identity: 812E82D12FEA3493
    moniker: Noderunners
    security_contact: info@noderunners.biz
    website: http://noderunners.biz
  jailed: false
  min_self_delegation: "1"
  operator_address: cosmosvaloper1q5ku90atkhktze83j9xjaks2p7uruag5zp6wt7
  status: BOND_STATUS_BONDED
  tokens: "559343421"
  unbonding_height: "0"
  unbonding_time: "1970-01-01T00:00:00Z"

Transactions

The tx commands allows users to interact with the staking module.

simd tx staking --help

create-validator

The command create-validator allows users to create new validator initialized with a self-delegation to it.

Usage:

simd tx staking create-validator [path/to/validator.json] [flags]

Example:

simd tx staking create-validator /path/to/validator.json \
  --chain-id="name_of_chain_id" \
  --gas="auto" \
  --gas-adjustment="1.2" \
  --gas-prices="0.025stake" \
  --from=mykey

where validator.json contains:

{
  "pubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"BnbwFpeONLqvWqJb3qaUbL5aoIcW3fSuAp9nT3z5f20="},
  "amount": "1000000stake",
  "moniker": "my-moniker",
  "website": "https://myweb.site",
  "security": "security-contact@gmail.com",
  "details": "description of your validator",
  "commission-rate": "0.10",
  "commission-max-rate": "0.20",
  "commission-max-change-rate": "0.01",
  "min-self-delegation": "1"
}

and pubkey can be obtained by using simd tendermint show-validator command.

delegate

The command delegate allows users to delegate liquid tokens to a validator.

Usage:

simd tx staking delegate [validator-addr] [amount] [flags]

Example:

simd tx staking delegate cosmosvaloper1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm 1000stake --from mykey

edit-validator

The command edit-validator allows users to edit an existing validator account.

Usage:

simd tx staking edit-validator [flags]

Example: