# Astar dApps Staking (master)
###### tags: #blockchain #staking #basicincome #shiden #astar #dApp #smartcontract
pallet source version: 1.1.2
## 1. What is dApps Staking
The dApp Staking is a unique feature from the Astar Network.
It is developed as a Rust pallet in the Substrate framework.
Interaction with the dApps staking is through Astar portal.
Chapter 4 focuses on the interactions between the portal and the pallet.
Chapters 5-11 describe the pallets API and the core functions.
First deployment of this application will be on Shibuya and Shiden Network
## 2. Actors in dApps Staking
- **developer**: a developer or organization who deploys the contract
- **staker**: any Astar user who stakes tokens on the developer's contract
- **portal**: UI, front-end implementation for this application
- **pallet**: blockchain backend, substrate pallet-dapps-staking
## 3. Abbreviations and Terminology
- `dApp`: decentralized application, is an application that runs on a distributed network.
- `smart contract`: on-chain part of the dApp
- `contract`: short for smart contract
- `EVM`: Ethereum Virtual Machine. Solidity Smart contract runs on it.
- `ink!`: Smart Contract written in Rust, complied as WASM
- `era`: Period of time. After it's end, rewards can be claimed
- `claim`: Claim ownership of the rewards from the contract's reward pool
- `bond`: Freeze funds to gain rewards
- `stake`: In this pallet a staker stakes bonded funds on a smart contract
- `unstake`: Unfreeze bonded funds and stop gaining rewards
- `wasm`: Web Assembly
- `contracts's reward pool`: Sum of unclaimed rewards on the contract. Including developer and staker parts.
---
## 4. Portal and Pallet Interaction
### 4.1 Developer portal-pallet interaction
#### 4.1.1 Create (register) new contract
<img src="https://i.imgur.com/3RB69iY.png" width="300">
1. The contract details (like project description, website, etc.) shall be stored in dB on the portal's backend, and not on-chain.
1. The Developer shall use one contract address for this action.
2. There shall be only one signed transaction for this call.
3. The Developer shall use unique account for this action. That address can not be reused to register another contract.
4. The Portal shall use type `SmartContract` for contract address.
5. The Developer shall deposit `RegisterDeposit` amount of tokens to register a new contract.
6. The claimed rewards shall be paid out to the developer's account
7. For the trial period there will be pre-approved list of of contract addresses.
The portal calls following function in the pallet:
```
pub fn register(
origin: developer's account,
contract_id: contract address
)
```
---
#### 4.1.2 Developer claims rewards
It is the same as for the Staker. See chapter 4.2.3 Claim Reward.
---
#### 4.1.3 Unregister existing contract
1. All funds currently staked on the contract shall be unstaked
2. The dispatch origin for this call must be Signed by the developer’s account. The same one as used for the registration.
The portal calls following function in the pallet:
```
pub fn unregister(
origin: developer's account,
contract_id: contract address
)
```
---
### 4.2 Staker portal-pallet interaction
The Staker can perform following 3 actions

- Stake (add funds)
- Unstake (unbond, unstake and withdraw funds)
- Claim Reward for all stakers on a contract and for the developer
---
#### 4.2.1 Stake (add funds)
<img src="https://i.imgur.com/IZbyVQa.jpg" width="300">
1. The Staker shall use one address for this accion. No distinction between Stash and Control accounts.
1. There shall be only one signed transaction for this call.
3. This call is used for both inital staking and for possible additional stakings.
4. The Staker shall stake on only one contract per call
5. The Staker can stake on an unlimited number of contracts but one at the time.
6. The number of stakers per contract is limited to `MaxStakings`
The portal calls following function in the pallet:
```
pub fn bond_and_stake(
origin: staker's account,
value: amount in tokens,
contract_id: contract address,
)
```
#### 4.2.2 Unstake (unbond, unstake and withdraw funds)
<img src="https://i.imgur.com/U3keFQo.jpg" width="300">
1. The unbonding period shall be 0 era and withdrawal shall be possible just after `unbond()` call
1. There shall be only one signed transaction for this call
3. The fund withdrawal can be partial or in full.
4. If a staker, who is unstaking, still has some claimable rewards, those rewards shall stay on the contract's reward pool and will be shared among other stakers.
The portal calls following function in the pallet:
```
fn unbond_unstake_and_withdraw(
origin: staker's account,
contract_id: contract address,
value: value to unstake
)
```
---
#### 4.2.3 Claim Reward
<img src="https://i.imgur.com/jfVRos9.jpg" width="300">
1. Any account willing to pay the fee can call this function
1. There shall be only one signed transaction for this call
3. This action will initiate payout for the developer and for all stakers on this contract
4. The portal does not keep the notion of the current era
The portal calls following function in the pallet:
```
fn claim(
origin: claimer's address,
contract_id: contract address,
)
```
#### 4.2.4 Voting contracts good/bad
Voting will not be implemented in v1.
---
## 5. Registering new contract
### 5.1 Register
`pub fn register(origin: OriginFor<T>, contract_id: T::AccountId) -> DispatchResult {}`
1. Register contract as a staking target.
1. Prior to registering, a contract needs to be deployed on the network. The contract address where the contract is deployed is used as the argument in this call.
1. The `dapp-staking` pallet supports both contract types, evm and wasm. Since Shiden supports only EVM at the moment, wasm contracts will not be verified.
1. The type for contract address will be `SmartContract`, which abstracts EVM and Wasm address types.
1. The Developer who is registering the contract shall pay `RegisterFee`. This fee shall be included in the function's weight.
2. There will be pre-approved list of contract addresses. This preaproval could be enabled or disabled. Pre-aproval requires sudo call.
```sequence
Dave-->Portal: Register
Portal->Pallet: register(Dave, contract_id)
Note right of Pallet: insert to RegisteredDapps(contract_id, Dave)
Note right of Pallet: insert to RegisteredDevelopers(Dave, contract_id)
Pallet->Portal: OK
```
Event:
* NewContract(developer's account, contract_id)
Error:
* AlreadyRegisteredContract
* AlreadyUsedDeveloperAccount
* ContractIsNotValid
---
### 5.2 Set Register Fee
Developer pays fee during registration through extrinsic call's weight.
---
## 6. Bonding and Staking Funds
```
pub fn bond_and_stake(
origin: OriginFor<T>,
contract_id: SmartContract<T::AccountId>,
#[pallet::compact] value: BalanceOf<T>,
) -> DispatchResultWithPostInfo {}
```
1. The dispatch origin for this call must be _Signed_ by the staker's account.
1. Ledger struct will be saved in storage and keyed with staker's account.
1. Staked funds will be considered for reward after the end of the current era.
1. The Staker shall use one address for this accion. No distinction between Stash and Control accounts.
1. This call is used for both inital staking and for possible additional stakings.
1. The Staker shall stake on only one contract per call
1. The Staker can stake on an unlimited number of contracts but one at the time.
1. The number of stakers per contract is limited to `MaxStakings`
In the following example Alice bonds 1000 tokens on address 0x111.
```sequence
Alice-->Portal: Stake
Portal->Pallet: bond(Alice, 1000 tokens)
Note right of Pallet: Ledger Alice={1000}
Note right of Pallet: ContractEraStake.stakers add <Alice, 1000>
Note right of Pallet: ContractLastStaked = CurrentEra
Pallet->Currency: Lock(1000)
Pallet->Portal: OK
```
#### Events:
`BondAndStake(
staker,
contract_id,
value_to_stake,
)`
#### Errors:
* NotOperatedContract
* StakingWithNoValue
* MaxNumberOfStakersExceeded
* InsufficientStakingValue
---
## 7. Unbonding, Unstaking and Funds Withdrawal
```
pub fn unbond_unstake_and_withdraw(
origin: OriginFor<T>,
contract_id: SmartContract<T::AccountId>,
value: BalanceOf<T>,
) -> DispatchResultWithPostInfo {}
```
1. The dispatch origin for this call must be _Signed_ by the staker.
2. The unbonded funds shall be available for withdrawal after `UnbondingDuration` of eras.
:::info
:bulb: **info:** initially unbonding will be immediate
`UnbondingDuration = 0 EraIndex`
:::
In the following example Alice has bonded 1200 tokens and now wants to unbond 300.
```sequence
Alice-->Portal: Unstake
Note right of Pallet: Ledger Alice= {1200}
Portal->Pallet: unbond_unstake_and_withdraw(Alice, 300)
Note right of Pallet: ContractLastStaked = CurrentEra
Note right of Pallet: Ledger Alice= {900}
Pallet->Currency: Unlock(Alice, 300)
Pallet->Portal: OK
```
#### Events:
`UnbondUnstakeAndWithdraw(
staker,
contract_id,
value_to_unstake
)`
#### Errors:
* NotOperatedContract
* UnstakingWithNoValue
* NotStakedContract
---
## 8. Claim Rewards
```
pub fn claim(
origin: OriginFor<T>,
contract_id: T::SmartContract,
era: EraIndex,
) -> DispatchResultWithPostInfo {}
```
1. Any account can initiate this action.
1. All stakers and the developer of this contract_id will be paid out.
1. The rewards are paid out, they are transferable and they are NOT automatically re-staked.
2. The claim relates to rewards for specified era
```sequence
Portal->Pallet: claim(contract_id, era)
Note right of Pallet: distribute RewardPerContract to all stakers and dev
Pallet->Portal: OK
```
pseudo code for claim algorithm when an account claims reward for the contract_id:
#### Event:
`ContractClaimed(
contract_id,
claimer,
start_from_era,
current_era,
)`
#### Error:
* ContractNotRegistered
* NothingToClaim
* AlreadyClaimedInThisEra
---
## 10. Era handing
### 9.1 How is Era handled
1. The Era in this module is not following Eras from the Session pallet.
1. `CurrentBlock` storage is incremented each block after hook `on_initialize()`.
1. When `CurrentBlock >= Self::BlockPerEra::get()` :
* the newly minted rewards are are stored in EraRewardsAndStakes
* rewards are ready to be claimed
* unbonded funds are able to be withdrawn (if `UnbondinDuration` is > 0)
* `CurrentEra` is incremented
---
### 9.2 History Depth
* History Depth is set as configurable constant
* There is no deletion of unclaimed rewards per contract when there is a new era.
* Rewards older than HistoryDepth number of eras are deleted during claim(). See also chapter 8. Claim
* There is potential scenario that for some contracts there will not be any claim action. In that case a maintenance of the network is needed to claim that contract in order to not overflow storage. Suggested maintenace period is once per month.
---
### 9.3 Force New Era
`pub fn force_new_era(origin: OriginFor<T>) -> DispatchResult {}`
This is a sudo call
---
## 11. Rewards and Inflation
1. The existing `block-reward` pallet will be used for inflation compensation.
1. The `block-reward` pallet handles block reward as imbalance and distributes rewards to `dapps-staking` pallet's account.
* `Balances::resolve_creating(&DappsStakingPalletId::get().into_account(), dapps);`
3. The Block reward is constant 2.664 SDN [Source]( https://github.com/PlasmNetwork/Astar/blob/development/shiden/runtime/shiden/src/lib.rs#L379). On each block pallet-dapps-staking gets 50% = 1.332 SDN
1. All registered contracts will be rewarded according to the amount of staked funds.
5. The yearly inflation rate is 10% and `dapps-staking` pallet gets 50% of newly minted tokens
6. The contract reward pool gets new reward during last block in an era.
7. For the stakers and the developer to get rewards from the contract's reward pool a claim transaction from the portal is required
8. The developers are rewarded with 80% of the contract reward pool
9. The stakers are rewarded with 20% of total contract reward pool proportionally to the amount staked
11. The era rewards are divided per contract in the following manner
