# Staking Parachain high-level architecture - [Transactionless Relay-chain](https://github.com/paritytech/polkadot/issues/323) - [[Meta] Moving Staking off the Relay Chain #491](https://github.com/paritytech/polkadot-sdk/issues/491) - [Proposal for Minimal Relay (RFC)](https://github.com/polkadot-fellows/RFCs/pull/32) The proposed design for the Staking Chain (SC) features *native staking* capabilities, where stakers request funds to be teleported from AssetHub (AH) into SC and the subsequent staking operations are performed directly between the staker and SC. This document outlines the high level architecture of the Staking Chain and a few technical details related to the interfaces between the SC and Relay-chain (RC) and SC and AH, inflation apparatus, and migration, among others. **Future/stretch goals**: the current team's main priority is to move all the staking logic out of the Relay-chain asap. However this document also outlines a few longer-term goals and features that may be included in a the future (e.g. remote staking, XCM-specific instructions for staking, priviledged restaking, among others) -- see section [Ideas for Staking Chain 2.0](#Ideas-for-Staking-Chain-20) ### Goals - Set the standards and best practices for parachains on cross-chain communication and asset management to the community; - Remove all the DOT-related logic from the relay-chain. - Minimise the # of XCM programs between Staking Chain and Relay-chain/AssetHub; The storage and computation bottlenecks should be dictated by the staking chain blockspace itself, not the communication with external parachains or relay chain; - Staking UX should be not be worse than the current system, modulo the added complexity on the wallet development and integration; - SC should integrate seamlessly with governance and other system parachains that require integrating with assets held for staking. - The new inflation mechanism should allow multiple privileged system parachains to get DOT allocated directly from era inflation. ### Functional goals - Relay-chain will have a thin logic layer that implements the active validator enablement/disablement upon slash(to avoids validator disablement delays due to SC <> AH messaging); - DOT inflation minting is the reponsibility of AssetHub (SP) and it should not be spread across multiple SPs, to ensure that total issuance tracking is simple; - Abstract staking concepts (e.g. "era", "exposures", etc) from the relay chain and other system parachains; - The concept of exposures is local to the staking chain. There is no need to share exposure data cross-chain. Exposures are stored and used by the staking chain to keep track of who should be rewarded; - Nomination pools are first class stakers, similar to direct nominators. For the external consensus parties and wallets, a nomination pool is a direct nominator with different configurations (pooled nominations, operator, less minimum bond to nominate, etc). ### Assumptions #### Relay Chain - Knows nothing about the concept of "era"; - Trusts that the staking chain computes the correct new set of validators in a timely manner and enables the new set of validators announced periodically by Staking Chain through XCM. - Changes validator set as soon as it receives a new validator set from the staking chain at (roughly) every era. - Trusts that the staking chain handles offences correctly, no need for further verifications; - All of the current staking user interactions are moved away from relay chain. - Responsible for reporting offence and era points for block building (potentially batched). - Implements a simple active validator disablement strategy that can be enacted without requiring communication with the Staking chain. - Block authoring: Staking needs to know about which validators authored how many blocks in an era to assign them era points. Relay-chain buffers block authors by session keys and sends them as a batch at the end of every session to staking chain. - Session keys: Validators generate session key on their relay chain node and sets it on staking chain pairing it with their stash account. #### Asset Hub - DOT lifecycle is managed by Asset Hub; AH is the only system parachain where inflation DOT can be minted and burned; - Knows nothing about the concept of "era"; - AssetHub stores the minimal information required to calculate the era minting payout; The staking related information (e.g. duration of the era, staked DOT, etc) is passed through XCM by the staking chain; - Trusts the SC to request inflation minting in a timely manner (e.g. at the end of an era, which only the SC knows about). #### Staking Hub - Supports all staking operating natively as well as via XCM; - Proactively sends new validator set to the relay chain; - Relay chain interaction: the relay chain signals both offences and block authoring information through XCM. In the opposite direction, the SC announces the new validator set through XCM; - Receives teleported DOTs from AH as budget to reward stakers. #### Other System Parachains - Have visibility over balances in the Staking chain for remote freezing operations (e.g. governance using staking funds); ## Architecture and flow diagrams ### System/stakers journey ![](https://hackmd.io/_uploads/BJmomvXeT.png) **Figure 1**. System flow. System actions are initiated by the origin consensus system implicitly. System actions are initiated by the origin consensus system. Note: the numbering **does not** necessarily determine the actions' ordering. ① **Mint reward budget for staking rewards** At each era, the era payout for stakers is teleported from assets hub to the staking parchain (see more about the inflation flow in the [Inflation flow](#Inflation-flow) section). The minting and teleport is reactive (i.e. request initiated at SC). The AH calculates the era payout at the staking chain request (the only system that knows about eras and how much staked DOT there is at a particular era). ② **Set new validator set** Whenever a new set of validators is ready, the staking chain proactively signals the relay chain of the new set of validator keys. The relay chain offloads the logic of when/why to change the validator set to the staking chain and trusts the information from the SC without need for further verifications. ③ **Run on/offchain election** Similar to nowadays, EPM manages the era transitions and starts a new election when appropriate. Multi-block election, possibly on-chain if feasible. ④ **Set era points** Relay chain proactively announces the new block authors and their corresponding "points" (previously named `era_points` but we should be renamed since RC knows nothing about eras). The block author points should be batched before sending to SC. ⑤ **New offence** The relay chain announces new offences that are handled by the pallet slashes in the SC. The Relay-chain may implement a rapid-disablement strategy that can be enacted before SC knows about the slashes. ⑥ **Disable active validator** The staking chain announces which active validators should be disabled (or reenabled) due offences. ![](https://hackmd.io/_uploads/SJip7DQea.png) **Figure 2**. Actions initiated by staking validators or as a second-order consequence of validator/nominator requests. Actions initiated by the validators or triggered as a second-order consequence of validator requests. In this diagram, we focus mostly on the _native staking_. ① **Set session keys** When setting intention to become a validator, the session keys must be set in the staking chain. ② **Propagate session keys** Propagate the validator session keys to the relay chain. Perhaps as a batch of the most recent registered validators. ③ **Request teleport funds to SC** The validator request teleport of DOT the asset hub into the staking chain. ④ **Teleport assets to SC** Assets are teleported to staking chain into the `validator` account. ⑤ **Staking-related calls** With native staking, all the staking-related operations are sent as XCM transact directly to the staking chain. ⑥ **Teleport assets to AH** Upon request to withdraw, teleport assets back to AH. ## Staking slashes - Offences announced through XCM from staking lite pallet in the relay chain (in batches, if possible); - Relay-chain will implement a thin logic layer that handles enablement/disablement of active validators upon slash (to avoids validator disablement delays due to SC <> AH messaging); - All historical exposure is maintained in the staking chain; The relay chain trusts that the request regarding disabling of active validators (and new era validator set) is correct without further verification; - For accounts who use the remote staking method, further XCM are batched to AssetHub for slashing funds of nominators (validators are required to stake natively). ## Inflation minting Currently, the staking pallet [calculates how much inflation should be minted](https://github.com/paritytech/polkadot-sdk/blob/2c35bc3d273f47d45c17078134c048016ef7a57a/substrate/frame/staking/src/lib.rs#L840) at the end of each era, depending on how long the era took, current staked funds, current issuance, ideal stake rate, and a few other parameters. In addition, it is calculated how much of the era minted DOT that should 1) be used for stakers payout in the era and 2) should be minted directly into the treasury as a remainder of the maximum era payout. In the parachain context, the staking chain *is not* responsible for minting new DOT tokens. That responsability falls solely on the AssetHub. This is key to make it possible to track total issuance effectively. However, AssetHub needs to know era related information from the staking chain (e.g. when a era ends and total staked) to calculate how much DOT should be minted. Thus, AssetHub mints new DOT tokens *reactively* at the request of the staking parachain. **Goals** - Multiple System Parachains may have funds allocated directly from the era inflation. - Minting is performed by AssetHub. - The AssetHub does not know the concept of `era`: it mints new DOT at the request of the staking chain. **How** - All System Parachains that may get funds from the inflation have i) a dedicated pot in AH or ii) implement their own balances where funds can be teleported into. - Governance defines the distribution of the era inflation for each of the system parachains, staking included (e.g. 20% min for treaury; 5% asset hub, 5% governance chain, 70% staking rewards). - At the end of each era (only Staking Chain keeps track of era changes), the Staking Chains requests the AssetHub to mint the era inflation. SC needs to provide: - `era_duration` - `total_staked` - AssetHub calculates the era inflation. - AssetHub distributed the % of the era inflation to the correct sovereing pots or through teleporting. ### Inflation flow ![](https://hackmd.io/_uploads/SkWrnBEx6.png) **Figure 5**. High-level diagram of era payout calculation and inflation DOT minting flow between SC and AH. ① **`mint_inflation(era_duration, total_staked)`** At the end of each era, the SC requests the minting of new DOT from AH. It announces both the `era_duration` and `total_staked` so that the correct amount of DOT to mint can be calculated. ② **Calculates era inflation** AssetHub calculates how much DOT should be minted given: ``` - era_duration - total_staked - total_issuance - ideal_stake_rate - min_annual_inflation ``` ③ **Calculates inflation distribution** Since multiple system parachains may get a portion of the era inflation (e.g. to reward their own collators), the era payout distribution is calculated by AH based on the `inflation_dist` map. This map can be changed by governance. ④ **Distributes inflation to SPs and Treasury** The distribution of the newly minted dot can be done in one of two ways: 1. By teleporting (if the destination system parachain has balances, e.g. staking parachain) 2. By issuing the corresponding DOT to the system parachain's sovereign account in the assets hub (e.g. governance parachain). ⑤ **Teleport era inflation payout** In the case of the staking chain, the stakers payout portion of the era inflation is teleported to SC. **Note**: The logic for how and when each staking parachain distributes the era inflation budget allocated is defined by their own runtime (e.g. a `pallet-rewards` may be used that keeps track of each parachain era points, similarly to who staking does the reward distribution nowadays). ## Exposing teleported funds to governance DOT in the staking chain can be used for governance (etc) through a similar (`RequestLock -> LockAssset -> RequestUnlock -> UnlockAsset`) mechanism as if the DOT would be reserved in the AssetHub. In this case, the `LockAsset` is sent to the staking chain instead of AH. Stakers who stake through remote and native need to request lock for each of the accounts in SC through the appropriate channels: if remote staking, the `LockAsset` needs to be streamed through AH. In the case of native staking, the `LockAsset` request can be sent by the lock requester directly to the staking chain. This can be abstracted by wallets. Note that e.g. the governance chain should not care where the DOTs are locked. From the governance POV, natively staked or remotely staked DOTs are just two different multi-locations. ## Fees - Allow teleporting DOT to SC for fee payment; - (optionally) request a % of the rewards to be funneled to a fee pot in the staking chain. SC provides two fee payment options: 1) teleport DOT for fee payment; 2) allow stakers to optionally reserve a % of the staking rewards to cover local fees. The Staking chain could also optionally provide a free request quota per account (in the future). The quota would let wallets to interact with SC without paying fees. However, there should be other ways to allow users that exhaust their feeless request quota. ## Migration to Staking chain > WIP, current proposals ### 1. Snapshot based: Freezing and migrating all staked balance to the Staking Chain **Rough steps:** - Freeze all stakes, active and unlocking. - Setup genesis with the frozen state balances. - No new election happens during this phase. - Slashes are buffered in the relay chain (if any). - Once we are sure staking system is working as expected, staking state in relay chain can be killed. **Advantages** - Only one staking system and better overall economic security. - One shot migration. ### 2. Slow Migration: Parallel Staking System on Relay Chain and Staking Chain We want to scale the staking parachain gradually. This is an extremely important piece of logic that needs to be tested thoroughly, but even in production, we should try taking all the steps to mitigate against potential bugs/oversights. I will refer staking module to mean set of pallets on relay chain that contains the staking and validator election logic. The staking module interacts with the rest of relay chain in two ways: - pallet-session: Asks Staking module for a new set of validators (and their exposure) at start of each new session. - pallet-offences: Reports offences by validators to Staking module. The desired set of validator count is set today on the staking module. We can introduce another config to determine part of the validators to get from the staking parachain, and the rest we will elect from the local staking module itself as it happens today. We can start with a smaller number (10%) and eventually scale this to 100% from Staking parachain. The important thing to note is staking would work independently on both staking chain and relay chain. An account who wants to validate on staking chain would have to transfer DOTs to staking chain and register their intention to validate there. Same for nominators. The disadvantage of this approach is, all existing validators (and nominators) will have to start over and they will lose their current set of nominators (and nominations). Also, it might prove difficult to get all nominators to move to Staking Chain. Note on Economic Security: There will be times in the transition phase when economic security of two staking systems are not equal and validators with less stake behind them making it to active validator set. But the market economics of cost and opportunity should balance the stakes as new validators have high incentive to move to Staking Chain as its easier to get elected via there. --- # Ideas for Staking Chain 2.0 <span style="color:#FF3988">**IMPORTANT NOTE**: we are not actively implementing/designing around any of the ideas described in this section at the moment, but we'll keep them in mind as we work on the release of Staking Chain.</span> <span style="color:#FF3988">Treat the remaining of this document as a dump of ideas and notes from discussions that still need polishing and even confirmation of whether these are goals worth pursuing in the future.</span> **Goals**: - With remote staking: provide the ability for large custodians (e.g. exchanges) or any other stakers to perform basic staking operations through AssetHub, without requiring any direct integration with the staking hub by leveraging _remote staking_. This aims at keeping the AssetHub as the "universal" point of contact for all DOT related operations (if wallets/operations choose to do so). - Staking should provide a minimal interface that allows stakers (direct nominations or nominator pool users) that only requires integration and communication with the Assets Hub; - New XCM instructions for a minimal and general interface to be used by the staking chain and across the ecosystem. - Features restaking feature natively for priviledged system parachachains. - Implement a priviledged restaking where e.g. bridge operators/others on system parachains may expose their staking to be slashed on the staking holdings (if existing). ## Staking XCM instructions One advantage to have this staking-specific XCM instructions is that it may make the whole dapps much easier: If we implement and integrate these XCM programs on the staking relay chain, the switch to the Staking parachain consists only on switching target multilocation. > TODO: open RFC **Ideas for discussion** ``` - StakeAsset { asset: MultiAsset, staker: MultiLocation, targets: NominationTarget } - RequestUnstakeAsset { asset: MultiAsset, staker: MultiLocation } - ClaimStakeReward { staker: MultiLocation } ``` Its possible some of these could be replaced by existing instructions that we have (such as `UnstakeAsset` replace by `UnlockAsset` and `ClaimStakeReward` with transfer) but there are subtle differences between them and would need feedback from the XCM team. ```rust= pub enum Instruction<Call> { // todo /// Stake funds. /// /// Send an onward XCM program to `dest` with the given `xcm`. /// /// - `assets`: The asset(s) to be staked. /// - `dest`: The location where the funds will be staked. /// - `xcm`: The instructions that should follow the `ReserveAssetDeposited` /// instruction which is sent onwards to `dest`, potentially with staking /// related actions. Stake { assets: MultiAssets, dest: MultiLocation, xcm: Xcm<()>, }, /// Unstake funds. /// /// todo Unstake { // todo }, } ``` ## Remote staking via Asset Hub [Discussion on Polkadot Forum](https://forum.polkadot.network/t/remote-stake-any-asset-on-asset-hub/4210/1) Optionally a user who has DOT is asset hub can stake from asset hub by sending an `XCM::Stake` (or similar) instruction. The staked account on SC is a keyless account derived from the origin in Asset Hub and can only be accessed via XCM by AssetHub. > TODO: finish basic explanation of the native staking (refer to the diagrams). ![](https://hackmd.io/_uploads/HJZAmwmx6.png) **Figure 3**. Actions initiated by staking nominators or as a second-order consequence of validator requests (highlights the remote staking flow). > To finish ## Priviledged Restarking Priviledged restaking consists of allowing system parachains (thus "priviledged") to announce slashable offences of staking valdidators that happened outside of the staking context (e.g. the offence may have been commited by the validator on the system parachain when performing collation). Both system parachains and the validator that will be exposed to restaking need to first register their restaking agreement contract with the staking parachain. Once that's done, the system parachain can announce offences which may lead to slashes of the funds used to stake (up to a individual and global thresholds). The restaking contract can be submitted through XCM by the system parachain. The "contract" must be signed by the validator and is stored in the staking chain for the duration of the restaking. ![](https://hackmd.io/_uploads/H1cMQINxT.png) **Figure 6**. High-level interaction flow for of the priviledged restaking feature. ① **Stake** Set intention and lock funds to stake in the Staking chain. ② **Register as a restaker** The collator registers as a restaker with the system parachain by signing a `contract` with the private keys of the validator staking account. The contract may be a blob of metadata defining the maximum amount of slash, TTL etc (TBD). ③ **Registed `signed_contract`** Upon verifying the contract signed by the collator, the system parachain registers the restaking contract in the Staking chain. This step is necessary for the system parachain to start announcing offences to the staking. ④ **Announce offence** The system parachain may announce a slashable offence of one or multiple of the registered signed contracts. The staking chain will process and handle the offence. ⑤ **Unregisted `signed_contract`** The system parachain may unregister a signed contract; Contract TTL expirations may also cancel restaking contract implicitly. ### Security and trust assumptions - Since the staking parachain trusts the system parachain that may use restaking, there is no need to verify whether the claimed offences are valid on the SC side; - There should be a local (i.e. validator) and global maxima of how much DOT can be slashed through restaking to ensure that restaking slashes do not affect considerably the economic security of the network (TBD).