Skip to content

Commit 57186a5

Browse files
committed
comments v1
1 parent b69c938 commit 57186a5

File tree

7 files changed

+138
-72
lines changed

7 files changed

+138
-72
lines changed

pallets/contracts/src/benchmarking/mod.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,10 @@ benchmarks! {
399399
// contract has the full value
400400
assert_eq!(T::ContractCurrency::free_balance(&addr), value + Pallet::<T>::min_balance());
401401
}
402-
402+
403+
404+
// We construct two unique contracts (with input and salt as instantiate benchmark) (PoCS)
405+
// The primary contract is assigned a mock stake to pass delegate criteria
403406
#[pov_mode = Measured]
404407
delegate {
405408
let c in 0 .. T::MaxCodeLen::get();
@@ -422,6 +425,7 @@ benchmarks! {
422425
}: _(origin,contract_addr.clone(),delegate_to.clone())
423426
verify{
424427
let delegate_info = <DelegateInfo<T>>::get(&contract_addr)?;
428+
// We assert if the delegate information has been updated
425429
assert_eq!(delegate_info.delegate_to(),delegate_to)
426430
}
427431

pallets/contracts/src/exec.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -947,7 +947,7 @@ where
947947
);
948948
},
949949
}
950-
// Initiate Stake
950+
// Initiate Stake (PoCS)
951951
StakeRequest::<T>::stake(&caller, &account_id, &gas)?;
952952

953953
Ok(output)
@@ -1283,6 +1283,7 @@ where
12831283
beneficiary: beneficiary.clone(),
12841284
},
12851285
);
1286+
// Delete Stake (PoCS)
12861287
StakeRequest::<T>::delete(&frame.account_id);
12871288
Ok(())
12881289
}

pallets/contracts/src/lib.rs

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474
//! calls its constructor to initialize the contract.
7575
//! * [`Pallet::instantiate`] - The same as `instantiate_with_code` but instead of uploading new
7676
//! code an existing `code_hash` is supplied.
77-
//! * [`Pallet::update_delegate`] - Updates the delegate information of the contract. (PoCS)
77+
//! * [`Pallet::delegate`] - Updates the stake-delegate information of the contract. (PoCS)
7878
//! * [`Pallet::call`] - Makes a call to an account, optionally transferring some balance.
7979
//! * [`Pallet::upload_code`] - Uploads new code without instantiating a contract from it.
8080
//! * [`Pallet::remove_code`] - Removes the stored code and refunds the deposit to its owner. Only
@@ -695,7 +695,6 @@ use stake::{DelegateRequest, ValidateRequest};
695695
/// - If the `code_hash` already exists on the chain the underlying `code` will be shared.
696696
/// - The destination address is computed based on the sender, code_hash and the salt.
697697
/// - The smart-contract account is created at the computed address.
698-
/// - The [`gasstakeinfo::AccountStakeinfo`] and [`gasstakeinfo::ContractScarcityinfo`] values are set to default to contract address (PoCS)
699698
/// - The `value` is transferred to the new account.
700699
/// - The `deploy` function is executed in the context of the newly-created account.
701700
#[pallet::call_index(7)]
@@ -917,18 +916,29 @@ use stake::{DelegateRequest, ValidateRequest};
917916
code_hash: CodeHash<T>,
918917
},
919918

920-
// PoCS
919+
/// Stake Score is updated for a contract (PoCS)
921920
Staked {
921+
/// The contract address for which stake information is updated
922922
contract: T::AccountId,
923+
/// The contract's associated stake score
923924
stake_score: u128,
924925
},
926+
927+
/// Delegate Information is updated for a contract via [`Pallet::delegate`] (PoCS)
925928
Delegated {
929+
/// The contract address for which delegate information is updated by its owner
926930
contract: T::AccountId,
931+
/// The contract delegated to which account address i.e., the validator
927932
delegate_to: T::AccountId,
928933
},
934+
935+
/// Validator validation criteria information as event (PoCS)
929936
ValidateInfo {
937+
/// The validator's account address i.e., a contract address
930938
validator: T::AccountId,
939+
/// Number of delegates which the validator can utilize for validation
931940
num_delegates: u32,
941+
/// Provides Assurance if the validator can start validating
932942
can_validate: bool
933943
}
934944

@@ -940,17 +950,27 @@ use stake::{DelegateRequest, ValidateRequest};
940950
InvalidSchedule,
941951
/// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`.
942952
InvalidCallFlags,
943-
/// PoCS
953+
/// Invalid Owner of a contract (PoCS)
944954
InvalidContractOwner,
955+
/// Stake Information i.e., `StakeInfoMap` doesn't hold the stake information for a given contract address (PoCS)
945956
NoStakeExists,
957+
/// No validator was found for the given contract address (PoCS)
946958
NoValidatorFound,
959+
/// The contract does not meet the minimum reputation requirement for updating delegates (PoCS)
947960
LowReputation,
961+
/// The contract or account is already delegated to the same address (PoCS)
948962
AlreadyDelegated,
963+
/// Failed to create a new bond for staking (PoCS)
949964
NewBondFailed,
965+
/// Failed to add extra funds to an existing bond (PoCS)
950966
BondExtraFailed,
967+
/// Failed to remove an existing bond (PoCS)
951968
BondRemoveFailed,
969+
/// The nomination process for selecting a validator has failed (PoCS)
952970
NominationFailed,
971+
/// The validation process has failed for a valid-to-be validator (PoCS)
953972
ValidationFailed,
973+
/// The required minimum number of delegates has not been met for validation (PoCS)
954974
InsufficientDelegates,
955975
/// The executed contract exhausted its gas limit.
956976
OutOfGas,
@@ -1073,13 +1093,19 @@ use stake::{DelegateRequest, ValidateRequest};
10731093

10741094
use crate::stake::{DelegateInfo,StakeInfo};
10751095

1076-
/// PoCS
1096+
/// Tracks Delegate Information of a staked contract (PoCS)
10771097
#[pallet::storage]
10781098
#[pallet::getter(fn get_delegate_info)]
10791099
pub type DelegateInfoMap<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, DelegateInfo<T>>;
1100+
1101+
/// Tracks Stake Score Information of a contract (PoCS)
10801102
#[pallet::storage]
10811103
#[pallet::getter(fn get_stake_info)]
10821104
pub type StakeInfoMap<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, StakeInfo<T>>;
1105+
1106+
/// Tracks Number of delegates associated with a validator (PoCS)
1107+
///
1108+
/// Gets updated via [`Pallet::delegate`] extrinsic.
10831109
#[pallet::storage]
10841110
#[pallet::getter(fn get_validator_info)]
10851111
pub type ValidatorInfoMap<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, u32>;

pallets/contracts/src/stake/chain_ext.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,24 @@
1-
use crate::{Config as ContractsConfig, Pallet as ContractsPallet};
1+
// This file is part of Substrate.
2+
// Copyright (C) Auguth Research Foundation, India.
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
// Licensed under the Apache License, Version 2.0 (the "License");
6+
// you may not use this file except in compliance with the License.
7+
// You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing, software
12+
// distributed under the License is distributed on an "AS IS" BASIS,
13+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
// See the License for the specific language governing permissions and
15+
// limitations under the License.
16+
//
17+
// This file is utilized for Proof of Contract Stake Protocol (PoCS).
18+
//
19+
use crate::Config as ContractsConfig;
220
use codec::Encode;
3-
use frame_support::log::{error, info}; // Import logging functions
21+
use frame_support::log::error; // Import logging functions
422
use crate::{
523
chain_extension::{ChainExtension, Environment, Ext, InitState, RetVal},
624
stake::{DelegateInfo, StakeInfo},

pallets/contracts/src/stake/mod.rs

Lines changed: 80 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,27 @@
1+
// This file is part of Substrate.
2+
// Copyright (C) Auguth Research Foundation, India.
3+
// SPDX-License-Identifier: Apache-2.0
4+
5+
// Licensed under the Apache License, Version 2.0 (the "License");
6+
// you may not use this file except in compliance with the License.
7+
// You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing, software
12+
// distributed under the License is distributed on an "AS IS" BASIS,
13+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
// See the License for the specific language governing permissions and
15+
// limitations under the License.
16+
//
17+
// This file is utilized for Proof of Contract Stake Protocol (PoCS).
18+
//
19+
20+
// Module Imports
21+
pub mod chain_ext;
22+
23+
24+
// Imports
125
use crate::{
226
Config, Error, Event, OriginFor, Pallet as Contracts, DelegateInfoMap, StakeInfoMap, ValidatorInfoMap,
327
};
@@ -10,13 +34,24 @@ use sp_runtime::{
1034
use sp_std::prelude::*;
1135
use pallet_staking::{Pallet as Staking, ValidatorPrefs,Bonded};
1236

37+
/// The minimum reputation required to participate in staking contracts.
1338
pub const MIN_REPUTATION: u32 = 3;
39+
40+
/// The minimum number of delegates required for a validator to be eligible.
1441
pub const MIN_DELEGATES: u32 = 10;
15-
pub const REPUTATION_FACTOR : u32 = 1;
16-
pub const INITIAL_STAKE_SCORE : u128 = 0;
1742

18-
pub mod chain_ext;
43+
/// The fixed unit used for incrementing reputation and initializing it during instantiation.
44+
pub const REPUTATION_FACTOR: u32 = 1;
45+
46+
/// The initial stake score, set to zero for contract constructor purposes.
47+
pub const INITIAL_STAKE_SCORE: u128 = 0;
1948

49+
50+
/// Represents the delegation details of a deployed contract.
51+
/// It includes:
52+
/// - The owner of the contract.
53+
/// - The validator account i.e., contract to which the contract is delegated.
54+
/// - The block number when the delegation was set.
2055
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
2156
#[scale_info(skip_type_params(T))]
2257
pub struct DelegateInfo<T: Config> {
@@ -26,42 +61,52 @@ pub struct DelegateInfo<T: Config> {
2661
}
2762

2863
impl<T: Config> DelegateInfo<T> {
29-
64+
/// Returns the owner `AccountId` of the contract associated with this `DelegateInfo`.
3065
pub fn owner(&self) -> T::AccountId {
3166
self.owner.clone()
3267
}
3368

69+
/// Returns the `AccountId` of the validator to whom the contract is delegated.
3470
pub fn delegate_to(&self) -> T::AccountId {
3571
self.delegate_to.clone()
3672
}
3773

74+
/// Returns the block number when the delegate information was last updated.
3875
pub fn delegate_at(&self) -> BlockNumberFor<T> {
3976
self.delegate_at
4077
}
4178

79+
/// Retrieves the `DelegateInfo` for a given contract address.
4280
pub fn get(contract_addr: &T::AccountId) -> Result<DelegateInfo<T>, DispatchError> {
4381
Contracts::<T>::get_delegate_info(contract_addr)
44-
.ok_or_else(|| Error::<T>::NoStakeExists.into())
82+
.ok_or_else(|| Error::<T>::NoStakeExists.into())
4583
}
4684

47-
fn new(owner: &T::AccountId,) -> Self {
48-
Self {
49-
owner: owner.clone(),
85+
/// Creates a new `DelegateInfo` instance where the deployer is both the owner and delegate.
86+
pub fn new(owner: &T::AccountId) -> Self {
87+
Self {
88+
owner: owner.clone(),
5089
delegate_to: owner.clone(),
51-
delegate_at: frame_system::Pallet::<T>::block_number()
52-
}
53-
}
54-
55-
fn update(&self, delegate: &T::AccountId) -> Self {
56-
Self{
57-
owner: self.owner.clone(),
58-
delegate_to: delegate.clone(),
59-
delegate_at: frame_system::Pallet::<T>::block_number()
60-
}
61-
}
90+
delegate_at: frame_system::Pallet::<T>::block_number(),
91+
}
92+
}
6293

94+
/// Updates the `delegate_to` field and returns an updated `DelegateInfo` instance.
95+
pub fn update(&self, delegate: &T::AccountId) -> Self {
96+
Self {
97+
owner: self.owner.clone(),
98+
delegate_to: delegate.clone(),
99+
delegate_at: frame_system::Pallet::<T>::block_number(),
100+
}
101+
}
63102
}
64103

104+
105+
/// Tracks the gas usage metrics of a contract for staking purposes.
106+
/// It includes:
107+
/// - The reputation score of the contract.
108+
/// - The block height of its most recent usage.
109+
/// - The stake score associated with the contract.
65110
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
66111
#[scale_info(skip_type_params(T))]
67112
pub struct StakeInfo<T: Config> {
@@ -72,23 +117,28 @@ pub struct StakeInfo<T: Config> {
72117

73118
impl<T: Config> StakeInfo<T>{
74119

120+
/// Returns the stake score of a contract's `StakeInfo`.
75121
pub fn stake_score(&self) -> u128 {
76122
self.stake_score
77123
}
78124

125+
/// Returns the reputation score of a contract's `StakeInfo`.
79126
pub fn reputation(&self) -> u32 {
80127
self.reputation
81128
}
82129

130+
/// Returns the block height of the most recent interaction with the contract.
83131
pub fn blockheight(&self) -> BlockNumberFor<T> {
84132
self.blockheight
85133
}
86134

135+
/// Retrieves the `StakeInfo` of an instantiated contract.
87136
pub fn get(contract_addr: &T::AccountId) -> Result<StakeInfo<T>,DispatchError> {
88137
Contracts::<T>::get_stake_info(contract_addr)
89138
.ok_or_else(|| Error::<T>::NoStakeExists.into())
90139
}
91140

141+
/// Creates a mock `StakeInfo` instance for testing with a given stake score and reputation.
92142
pub fn mock_stake(stake_score: u128, reputation: u32) -> Self{
93143
Self{
94144
reputation: reputation,
@@ -97,6 +147,7 @@ impl<T: Config> StakeInfo<T>{
97147
}
98148
}
99149

150+
/// Creates a new `StakeInfo` instance using predefined constants for instantiation.
100151
fn new() -> Self {
101152
Self{
102153
reputation: REPUTATION_FACTOR,
@@ -105,6 +156,7 @@ impl<T: Config> StakeInfo<T>{
105156
}
106157
}
107158

159+
/// Resets the stake score in `StakeInfo` to zero, updates the block number, and retains the reputation.
108160
fn reset(&self)-> Self {
109161
Self{
110162
reputation: self.reputation,
@@ -113,6 +165,7 @@ impl<T: Config> StakeInfo<T>{
113165
}
114166
}
115167

168+
/// Updates the stake score based on gas usage provided and adjusts reputation if the block height has changed.
116169
fn update(&self, gas: &u64) -> Self {
117170
let current_block_height = <frame_system::Pallet<T>>::block_number();
118171
let current_reputation = self.reputation;
@@ -227,6 +280,14 @@ impl<T: Config> StakeRequest<T>{
227280
if StakeInfoMap::<T>::contains_key(&contract_addr) {
228281
StakeInfoMap::<T>::remove(&contract_addr);
229282
}
283+
if DelegateInfoMap::<T>::contains_key(&contract_addr){
284+
let delegate_info = <DelegateInfo<T>>::get(&contract_addr).unwrap();
285+
let delegate_to = delegate_info.delegate_to();
286+
if delegate_to != delegate_info.owner(){
287+
<DelegateRequest<T>>::decrement(&delegate_to);
288+
}
289+
DelegateInfoMap::<T>::remove(&contract_addr);
290+
}
230291
}
231292

232293
fn nominate(owner: &T::AccountId, validator: &T::AccountId) -> Result<(),DispatchError>{

pallets/contracts/src/tests.rs

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -6843,41 +6843,3 @@ fn pocs_stake_score_increment_during_delegate_call(){
68436843
assert!(<StakeInfo<Test>>::get(&callee_addr).unwrap().stake_score() > init_stake_score);
68446844
});
68456845
}
6846-
6847-
#[test]
6848-
fn pocs_delegate_by_owner_contract_via_chain_extension(){
6849-
6850-
}
6851-
6852-
#[test]
6853-
fn pocs_delegate_by_non_owner_contract_via_chain_extension(){
6854-
6855-
}
6856-
6857-
#[test]
6858-
fn pocs_fetch_delegate_to_via_chain_extension(){
6859-
6860-
}
6861-
6862-
#[test]
6863-
fn pocs_fetch_delegate_at_via_chain_extension(){
6864-
6865-
}
6866-
#[test]
6867-
fn pocs_check_is_delegate_via_chain_extension(){
6868-
6869-
}
6870-
#[test]
6871-
fn pocs_fetch_stake_score_via_chain_extension(){
6872-
6873-
}
6874-
6875-
#[test]
6876-
fn pocs_fetch_reputation_via_chain_extension(){
6877-
6878-
}
6879-
6880-
#[test]
6881-
fn pocs_fetch_stake_info_tuple_via_chain_extension(){
6882-
6883-
}

0 commit comments

Comments
 (0)