The simplest form of governance in a blockchain is a Collective—a group of on-chain entities or accounts that collaborate to make decisions, execute governance actions, or perform specific tasks.
To upgrade your Runtime, you need to submit two proposals. The first is the WhitelistCall (polkadotjs\Developer\Extrinsics\whitelist\whitelistCall), which requires an encoded hash as its parameter. The second, submitted after the first proposal is approved, is the DispatchWhitelistedCallWithPreimage (polkadotjs\Developer\Extrinsics\whitelist\dispatchWhitelistedCallWithPreimage), which includes the call pre-image of the encoded hash. In this case, it would be the setCode call containing the Runtime Wasm.
Proposal 1: WhitelistCall
The first step in upgrading your Runtime is to hash your call data. In this context, the call data is the Runtime Wasm file. The Wasm file can be found at target/release/wbuild/custom-runtime/custom_runtime.compact.compressed.wasm after running cargo build --release.
To generate the hash:
Navigate to polkadotjs\Developer\Extrinsic\system\setCode.
Upload the Runtime Wasm file and locate the encoded call hash.
Copy the hash.
Once you have the encoded call hash of the Runtime Wasm, you can proceed to create a proposal in the Technical Committee:
Go to polkadotjs\Governance\TechnicalCommittee\Proposals\SubmitAProposal.
Paste the encoded call hash into the appropriate field.
To vote on the proposal, click the corresponding link.
After the voting process is complete, you can close the proposal and check the recent events. If successful, you will see that the motion has been approved by the Technical Committee.
Proposal 2: DispatchWhitelistedCallWithPreimage
Once the WhitelistCall is approved by the committee, you can proceed with the second proposal. The DispatchWhitelistedCallWithPreimage (polkadotjs\Developer\Extrinsics\whitelist\dispatchWhitelistedCallWithPreimage) includes the call pre-image of the encoded hash used in the first proposal.
To complete this step:
Create and submit the second proposal. Wrapped the system\SetCode with whitelist\dispatchWhitelistedCallWithPreimage.
Once again, the proposal will need to be voted on and closed for execution.
Make sure the execution confirmation does not return an error code.
Final Steps: Relay Chain Finalization
A Runtime upgrade requires finalization on the Relay Chain before it is applied to the Parachain. Once finalized, you will observe the changes reflected in the spec-version number.
That’s it. If you aspire to be a blockchain engineer and would like to contribute to Xode Blockchain (https://github.com/Xode-DAO/xode-blockchain), fork the repository and submit a pull request with your awesome work.
The DealWithFees struct, which handles the OnUnbalanced trait, is crucial for distributing transaction fees and tips throughout the chain. It is imperative to test this implementation thoroughly.
For instance, consider a DealWithFees implementation, as shown in the code below, which splits the imbalance such that 20% goes to the treasury and 80% to the author.
pub const TREASURY_SHARE: u32 = 20;
pub const AUTHOR_SHARE: u32 = 80;
pub struct DealWithFees<R>(core::marker::PhantomData<R>);
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for DealWithFees<R>
where
R: pallet_balances::Config + pallet_authorship::Config + pallet_treasury::Config + crate::Config,
<R as frame_system::Config>::AccountId: From<AccountId>,
<R as frame_system::Config>::AccountId: Into<AccountId>,
{
fn on_unbalanceds(
mut fees_then_tips: impl Iterator<Item = Credit<R::AccountId, pallet_balances::Pallet<R>>>,
) {
if let Some(fees) = fees_then_tips.next() {
let mut split = fees.ration(TREASURY_SHARE, AUTHOR_SHARE);
if let Some(tips) = fees_then_tips.next() {
tips.merge_into(&mut split.1);
}
ResolveTo::<pallet_treasury::TreasuryAccountId<R>, pallet_balances::Pallet<R>>::on_unbalanced(split.0);
<ToAuthor<R> as OnUnbalanced<_>>::on_unbalanced(split.1);
}
}
}
pub struct ToAuthor<R>(core::marker::PhantomData<R>);
impl<R> OnUnbalanced<Credit<R::AccountId, pallet_balances::Pallet<R>>> for ToAuthor<R>
where
R: pallet_balances::Config + pallet_authorship::Config + crate::Config,
<R as frame_system::Config>::AccountId: From<AccountId>,
<R as frame_system::Config>::AccountId: Into<AccountId>,
{
fn on_nonzero_unbalanced(
amount: Credit<<R as frame_system::Config>::AccountId, pallet_balances::Pallet<R>>,
) {
if let Some(author) = <pallet_authorship::Pallet<R>>::author() {
let _ = <pallet_balances::Pallet<R>>::resolve(&author, amount);
}
}
}
parameter_types! {
pub const TransactionByteFee: Balance = 10 * MICRO_UNIT;
}
impl pallet_transaction_payment::Config for Test {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, DealWithFees<Test>>;
type WeightToFee = WeightToFee;
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
type OperationalFeeMultiplier = ConstU8<5>;
}
To test the above code implementation, follow these steps:
STEP 1: First, you need to set up the author of the block. For more detailed information on this, you can visit my previous blog: Manually injecting the block author.
AuthorGiven::set_author(1);
Authorship::on_initialize(1);
Authorship::on_finalize(1);
let author = Authorship::author();
assert_eq!(author, Some(1));
STEP 2: Construct the extrinsic call and take note of the dispatch_info. It should show you the weights as calculated through your extrinsic and mock settings.
let call = RuntimeCall::CustomPallet(crate::Call::sample_extrinsic{});
let info = call.get_dispatch_info();
let len = call.encode().len();
println!("Info: {:?}",info.clone());
STEP 3: Dispatch the call. Before dispatching, we need to charge the call. After the call, we will get the actual_fee. Also, make sure that the actual_fee was deducted from the caller’s free_balance.
let pre_d = ChargeTransactionPayment::<Test>::from(0).pre_dispatch(
&caller,
&call.clone(),
&info,
len
).expect("pre_dispatch error");
let post_result = call.clone().dispatch(RuntimeOrigin::signed(caller.clone())).expect("dispatch failure");
let actual_fee = TransactionPayment::compute_actual_fee(len.try_into().unwrap(), &info, &post_result, 0);
println!("Fee: {:?}",actual_fee);
println!("After Balance: {:?}",Balances::free_balance(caller.clone()));
STEP 4: Once we have computed the actual_fee, we need to withdraw it to create an imbalance. This is critical; when withdrawing, we need to use the FungibleAdapter.
type FungibleAdapterT = FungibleAdapter<Balances, DealWithFees<Test>>;
let imbalance = <FungibleAdapterT as OnChargeTransaction<Test>>::withdraw_fee(
&caller,
&call.clone(),
&info,
actual_fee,
0
).expect("pre_dispatch error");
println!("Imbalance: {:?}",imbalance);
STEP 5: Lastly, execute on_unbalanceds of DealWithFees, then assert the Treasury and Author accounts.
That’s it—it’s very complicated. Hopefully, someone can simplify it.
If you aspire to be a blockchain engineer and would like to contribute to Xode Blockchain (https://github.com/Xode-DAO/xode-blockchain), fork the repository and submit a pull request with your awesome work.
Special thanks to brunopgalvao for showing the light.
There are many reasons why we need to manually inject authors into your custom pallet unit tests. Block authors play a significant role in the chain, and from time to time, they are rewarded. Therefore, it is essential to test that the rewards are correctly distributed to the appropriate authors. This necessitates manually injecting authors into our test transactions within the test blocks.
The first step is to load the pallet_authorship in the mock.rs file and then modify the FindAuthor type parameter.
impl pallet_authorship::Config for Test {
type FindAuthor = AuthorGiven;
type EventHandler = (CollatorSelection, XodeStaking);
}
This is a powerful implementation because you can set the author of the block in real-time using set_author, and it will be consumed by pallet_authorship as if it came from a consensus engine.
To use this mock configuration in your test.rs file, you just need to specify the author and instantiate the pallet_authorship. You can verify the author by calling Authorship::author(). The value will remain consistent across your custom pallet associated with pallet_authorship. One more thing, very important, you need to trigger two hooks of the pallet_authorship, on_initialize and on_finalize to stamp the block with the author.
System::set_block_number(1);
AuthorGiven::set_author(1);
Authorship::on_initialize(System::block_number());
Authorship::on_finalize(System::block_number());
let author = Authorship::author();
assert_eq!(author, Some(1));
That’s it, very simple!
If you aspire to be a blockchain engineer and would like to contribute to Xode Blockchain (https://github.com/Xode-DAO/xode-blockchain), fork the repository and submit a pull request with your awesome work.
This is how you upgrade your Parachain Runtime in Polkadot.
Requirement: Your parachain must have a democracy or a sudo pallet installed. You already know how to create the Chainspec, WASM and Genesis State files from your blockchain.
1. Setup a development infrastructure
Startup your Relaychain. You need atleast two nodes, e.g., Alice and Bob using the same chainspec (Rococo Local)
$ ./target/release/polkadot --chain rococo-local-cfde.json --alice --tmp --rpc-cors all --ws-external $ ./target/release/polkadot --chain rococo-local-cfde.json --bob --tmp --port 30334 --rpc-cors all --ws-external
Startup your Parachain. You have to create the Chainspec (parachain-chainspec.json) first using your reserved paraId, e.g., 2000. Make sure also your are using the same Chainspec for your Relaychain port.
2. Connect your development Parachain and Relaychain.
In your Relaychain provide the necessary information using paraSudoWrapper/sudoScheduleParaInitialize and make sure that the paraId matches your Parachain Chainspec.
You should be able to see that your Relaychain and Parachain are generating blocks.
3. Modify the Parachain code and create new runtime WASM.
Just add a function do_another_thing in the Pallet Template. Then compile and create a new runtime WASM file, call it parachain-v2-wasm.
4. Upgrade the Parachain throuch XCM via Relaychain
Using PolkadotJS, in your Parachain go to: Developer->Sudo->parachainSystem->authorizeUpgrade. CodeHash is your WASM file coded using H256.
Using PolkadotJS, in your Relaychain go to: Developer->Extrinsics->xcmPallet->send
Follow the XCM code below. Make sure that the Parachain Id matches with your ParaId and the encoded has to be your encoded H256 code. All users here are set to sudo, if ever you are using democracy, you should match it with the authorized user.
Enact your upgrade in the Parachain. Make sure to use now your version 2 runtime WASM file.
Now check the newly added extrinsic. You should be able to see a new function in your templatePallet called doAnotherThing. Very cool, you have upgraded your runtime without any downtime.
Anything Polkadot and Substrate is difficult, thus adding pallet_contracts to the latest Parachain Template requires a lot of hacking and begging from people in Parity Technology for help. But nevertheless we’ve managed to add support for smart contracts into our Parachain.
Parachain is a sharded blockchain implementation of Polkadot. Hence this blockchain needs a Relay Blockchain to be able to finalize blocks. The benefits of a sharded blockchain is huge, first and foremost the Relay Blockchain, e.g., Polkadot, Kusama, etc. will provide most of the security of your blocks as well as interconnectivity within the entire eco-system, making bridging obsolete.
First we need to clone the template
$ git clone https://github.com/substrate-developer-hub/substrate-parachain-template.git
$ cd substrate-parachain-template
$ cargo b -r
Lets modify the runtime by adding these libraries (runtime/Cargo.toml). I did not include the git location and version since almost daily Parity is changing the repository.
Next is to implement the Config traits of the following libraries.
For randomness:
impl pallet_randomness_collective_flip::Config for Runtime {}
For asset:
parameter_types! {
pub const AssetDeposit: Balance = 100 * DOLLARS;
pub const ApprovalDeposit: Balance = 1 * DOLLARS;
pub const StringLimit: u32 = 50;
pub const MetadataDepositBase: Balance = 10 * DOLLARS;
pub const MetadataDepositPerByte: Balance = 1 * DOLLARS;
}
impl pallet_assets::Config for Runtime {
type Event = Event;
type Balance = u128;
type AssetId = u32;
type Currency = Balances;
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
type AssetDeposit = AssetDeposit;
type AssetAccountDeposit = ConstU128<DOLLARS>;
type MetadataDepositBase = MetadataDepositBase;
type MetadataDepositPerByte = MetadataDepositPerByte;
type ApprovalDeposit = ApprovalDeposit;
type StringLimit = StringLimit;
type Freezer = ();
type Extra = ();
type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;
}
And lastly for the contract:
parameter_types! {
pub const DepositPerItem: Balance = deposit(1, 0);
pub const DepositPerByte: Balance = deposit(0, 1);
pub const DeletionQueueDepth: u32 = 128;
pub DeletionWeightLimit: Weight = RuntimeBlockWeights::get()
.per_class
.get(DispatchClass::Normal)
.max_total
.unwrap_or(RuntimeBlockWeights::get().max_block);
pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();
}
impl pallet_contracts::Config for Runtime {
type Time = Timestamp;
type Randomness = RandomnessCollectiveFlip;
type Currency = Balances;
type Event = Event;
type Call = Call;
type CallFilter = frame_support::traits::Nothing;
type DepositPerItem = DepositPerItem;
type DepositPerByte = DepositPerByte;
type CallStack = [pallet_contracts::Frame<Self>; 31];
type WeightPrice = pallet_transaction_payment::Pallet<Self>;
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
type ChainExtension = pallet_assets_chain_extension::substrate::AssetsExtension;
type DeletionQueueDepth = DeletionQueueDepth;
type DeletionWeightLimit = DeletionWeightLimit;
type Schedule = Schedule;
type AddressGenerator = pallet_contracts::DefaultAddressGenerator;
type ContractAccessWeight = DefaultContractAccessWeight<RuntimeBlockWeights>;
type MaxCodeLen = ConstU32<{ 256 * 1024 }>;
type RelaxedMaxCodeLen = ConstU32<{ 512 * 1024 }>;
type MaxStorageKeyLen = ConstU32<128>;
}
The next step after Config traits are implemented, is to expose the RPC Api calls for your pallet_contracts. Without exposing, you cannot upload or call your contracts. To do this, just modify the imp_runtime_apis! macro and add the following code:
Like all Substrate configuration, all you need to do is to identify the trait of a library and then implement it. The above trait is for ContractsApi of pallet_contracts_rpc_runtime_api library.
Now it’s time to modify the node of our Parachain.
Add the library below in node/Cargo.toml file. Again we did not provide the git location and version, the values depends on the Cumulus and Polkadot releases.
pallet-contracts-rpc
Modify the create_full function in the node/src/rpc.rs file by adding the following lines.
pub fn create_full<C, P>(
deps: FullDeps<C, P>,
) -> Result<RpcExtension, Box<dyn std::error::Error + Send + Sync>>
where
C: ProvideRuntimeApi<Block>
+ HeaderBackend<Block>
+ AuxStore
+ HeaderMetadata<Block, Error = BlockChainError>
+ Send
+ Sync
+ 'static,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>,
C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>, // Add this
C::Api: BlockBuilder<Block>,
P: TransactionPool + Sync + Send + 'static,
{
use pallet_contracts_rpc::{Contracts, ContractsApiServer}; // Add this
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use substrate_frame_rpc_system::{System, SystemApiServer};
let mut module = RpcExtension::new(());
let FullDeps { client, pool, deny_unsafe } = deps;
module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?;
module.merge(TransactionPayment::new(client.clone()).into_rpc())?;
module.merge(Contracts::new(client).into_rpc())?; // Add this
Ok(module)
}
Then finaly you need to modify the node/src/service.rs file by adding a constraint for RuntimeApi::RuntimeApi in the function start_node_impl.
That’s it. When your done and had your Parachain running, you should be able to see the Contracts menu as shown below:
To run a local Parachain, you need to setup a local Relay Blockchain also. All you need to do is to follow the Cumulus SDK manual on setting up local Parachain.
Also the code above may require declaration and some internal public function to run. The complete code can be found here, you can view all required declation in this code.
Have fun coding. Please don’t forget to donate if your find this blog helpful.
The ability to have premissionless transistion functions through smart contracts makes blockchain special. These are two most commonly used smart contracts:
Our goal is to deploy the two smart contracts into a blockchain and interact with it externally using Node.js with Web3.js libraries in four (4) steps. For our blockchain we will be using Polygon Mumbai Testnet: https://polygonscan.com/
STEP 1: Wallet
So the first step is to setup our wallet and connect it to a blockchain. The wallet that we will be using is Metamask and the blockchain is Polygon. Follow the documentation on how to setup Metamask and Polygonhere.
We need to create two addresses in our wallet. For the first address we need to have MATIC (Polygon’s native token) balance. We need a balance so that we can upload our smart contracts, since blockchains requires gas fees. For Polygon Testnet (Mumbai), we can ask for free MATIC using this link: https://faucet.polygon.technology/
STEP 2: Smart Contracts
Create the two smart contracts using OpenZeppelin. There is already a template for ERC20 (Token) and ERC721 (NFT). Just pick the methods, e.g., transfer, mint, burn, etc., that we need to have in our token and OpenZeppelin will write the Solidity code for us.
Once done we can compile and deploy our smart contract Solidity code using Remix. Make sure that we deploy our contracts to Polygon Testnet (Mumbai) using the first address.
Here is the detailed step on how to deploy smart contracts using OpenZeppelin and Remix.
Once we successfully deployed our smart contracts we can then view our deployed contract using Polygon Scan. Just search for the first address. Take note of the contract addresses in the transactions, we will use it in our Node.js project.
STEP 3: Node.js
Now that our wallet, blockchain and smart contracts are fully set up. It’s time to write the code, the first step is to make a Node.js project and install Web3.js.
It’s time to create the code that will interact with our blockchain smart contracts.
To interact with the blockchain smart contracts we need to have the Application Binary Inteface (ABI) of the said contracts. We can get ABI file upon smart contract deployment in Remix, it contains all functions, methods and properties of the deployed contract.
To view the ABI file, just uploaded it to any free JSON viewer websites.
Now that we know what functions, methods and properties to call in our smart contracts, we can proceed to writing the code on how to get the totalSupply of our Token and NFT.
require('dotenv').config();
const fs = require('fs');
const Web3 = require('web3');
async function main() {
const testnet = process.env.TESTNET;
const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
const abi = JSON.parse(fs.readFileSync("./token_abi.json"));
let contract = new web3.eth.Contract(abi, process.env.TOKEN_CONTRACT);
let supply = await contract.methods.totalSupply().call();
console.log(supply);
}
main().catch(console.error).finally(() => process.exit());
require('dotenv').config();
const fs = require('fs');
const Web3 = require('web3');
async function main() {
const testnet = process.env.TESTNET;
const walletAddress = process.env.ADDRESS1;
const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
const abi = JSON.parse(fs.readFileSync("./nft_abi.json"));
let contract = new web3.eth.Contract(abi, process.env.NFT_CONTRACT);
let supply = await contract.methods.totalSupply().call();
console.log(supply);
}
main().catch(console.error).finally(() => process.exit());
The code is so easy and self explanatory. We can then wrap this code to a REST API Node server, so that we can consume it on any App or DApp.
The totalSupply function is a mere query call, hence no encoding to hash values.
Let me give you another example that needs encoding, the function mint in our Token smart contract.
The mint function writes data to the blockchain, hence must be encoded.
The transaction is encoded, signed, and sent to the blockchain network. The blockchain network in response will return the hash code of the transaction.
Same process is needed for all new transactions, e.g., transfer, burn, etc., in the blockchain. In the safeTransferFrom code for NFT below, we will need the second address to transfer the NFT from the first address.
That’s it. Have fun coding. Please don’t forget to donate if your find this blog helpful. And if you want the complete code, just click the Github link.
This blog will show you how simple it is to send Gmail emails using Rust. We will be also using .env to securely store your Gmail credentials at the server. Let’s start!
The first step is to setup a Gmail app password:
Next is to modify the Cargo.toml file by adding dependecies. We will be using lettre libraries to generate and send emails. We will be setting up an environment (dotenv) to store our Gmail credentials. And lastly we will add tokio for asynchronous main.
tokio = { version = "1", features = ["full"] }
dotenv = "0.15.0"
lettre = "0.9"
lettre_email = "0.9"
use dotenv::dotenv;
use lettre_email::EmailBuilder;
use lettre::smtp::authentication::IntoCredentials;
use lettre::{SmtpClient, Transport};
use lettre_email::mime;
use std::path::Path;
#[tokio::main]
async fn main() {
dotenv().ok();
let notify_email = std::env::var("NOTIFY_EMAIL").expect("No email provided");
let smtp_email = std::env::var("SMTP_EMAIL").expect("No email provided");
let smtp_email_password = std::env::var("SMTP_PASSWORD").expect("No email password provided");
let attachment = "attached.csv";
let email = EmailBuilder::new()
.to(notify_email.clone())
.from(smtp_email.clone())
.subject("Sample Email from Rust")
.text("Sample Email from Rust with attachment.")
.attachment_from_file(
&Path::new(&attachment),
Some(&attachment),
&mime::TEXT_CSV,
)
.unwrap()
.build()
.unwrap();
let smtp = std::env::var("SMTP").expect("No SMTP");
let credentials = (smtp_email, smtp_email_password).into_credentials();
let mut mailer = SmtpClient::new_simple(&smtp)
.unwrap()
.credentials(credentials)
.transport();
let result = mailer.send(email.into());
println!("{:?}", result);
}
That’s it. Have fun coding Rust. Please don’t forget to donate if your find this blog helpful.
Programmatically transferring balances from one account to another is the most important automation function you will need to invoked in your blockchain if ever you want to act as an off-chain worker, decentralized exchange, oracle, pool or any other finance related activities.
Here are the steps on how to programmatically transfer a balance from one account to another in your pallet_custom.
1. Add a Currency type to your trait Config (pallets/custom/src/lib.rs)
pub trait Config: frame_system::Config {
type Currency: Currency<Self::AccountId>;
}
2. Configure the Currency type in your runtime (runtime/src/lib.rs). In our example, it is just our native token/asset balances.
impl pallet_custom::Config for Runtime {
type Currency = pallet_balances::Pallet<Runtime>;
}
After examining the code above thoroughly, you’ll noticed that the destination AccountId was stored in the pallet storage called PalletCustomDataStore, basically hidden from the transacting caller source.
Hidden AccountId is very useful in paying of fees, reserving pools or even swapping tokens. Hence, in our example we store these accounts in the blocks then used when they are needed for certain applications.
That’s it. Have fun with your own chain. Please don’t forget to donate if your find this blog helpful.
You need Smart Contracts to be able to expand the use-cases of your blockchain, without it, your chain will be just like Bitcoin, nothing but a UTXO ledger.
Web3 runs on top of Smart Contracts. Fungible and Non-fungible Tokens (NFT) runs on top of Smart Contracts. Other bridges and inter-blockchain automation runs on top of Smart Contracts. Hence Smart Contracts are not just “a” feature but essential to your DeFi blockchain.
Here is how to hack your existing substrate-node-template to support Smart Contracts.
parameter_types! {
// Refundable deposit per storage item
pub const DepositPerItem: Balance = 32 * DEPOSIT_PER_BYTE;
// Refundable deposit per byte of storage
pub const DepositPerByte: Balance = DEPOSIT_PER_BYTE;
// How much weight of each block can be spent on the lazy deletion queue of terminated contracts
pub DeletionWeightLimit: Weight = Perbill::from_percent(10) * BlockWeights::get().max_block; // 40ms
// Maximum size of the lazy deletion queue of terminated contracts.
// The weight needed for decoding the queue should be less or equal than a tenth
// of the overall weight dedicated to the lazy deletion.
pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (
<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -
<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)
)) / 10) as u32; // 2228
pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();
}
impl pallet_contracts::Config for Runtime {
type Time = Timestamp;
type Randomness = RandomnessCollectiveFlip;
type Currency = Balances;
type Event = Event;
type Call = Call;
// The safest default is to allow no calls at all. This is unsafe experimental feature with no support in ink!
type CallFilter = frame_support::traits::Nothing;
type DepositPerItem = DepositPerItem;
type DepositPerByte = DepositPerByte;
type WeightPrice = pallet_transaction_payment::Pallet<Self>;
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
type ChainExtension = ();
type DeletionQueueDepth = DeletionQueueDepth;
type DeletionWeightLimit = DeletionWeightLimit;
type Schedule = Schedule;
type CallStack = [pallet_contracts::Frame<Self>; 31];
type AddressGenerator = pallet_contracts::DefaultAddressGenerator;
type ContractAccessWeight = ConstU64<0>;
type MaxCodeLen = ConstU32<{ 128 * 1024 }>;
type RelaxedMaxCodeLen = ConstU32<{ 256 * 1024 }>;
}
Configure RPC API end-points (runtime/src/lib.rs – impl_runtime_apis macro)
Expose the RPC API end-points (node/src/rpc.rs) – Make sure to take note of the mutable characteristic of the client variable, all precendent usage must be cloned.
/// Instantiate all full RPC extensions.
pub fn create_full<C, P>(
deps: FullDeps<C, P>,
) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>
where
C: ProvideRuntimeApi<Block>,
C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
C: Send + Sync + 'static,
C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,
C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: BlockBuilder<Block>,
P: TransactionPool + 'static,
{
use pallet_contracts_rpc::{Contracts, ContractsApiServer};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use substrate_frame_rpc_system::{System, SystemApiServer};
let mut module = RpcModule::new(());
let FullDeps { client, pool, deny_unsafe } = deps;
module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?;
module.merge(TransactionPayment::new(client.clone()).into_rpc())?;
module.merge(Contracts::new(client).into_rpc())?;
// Extend this RPC with a custom API by using the following syntax.
// `YourRpcStruct` should have a reference to a client, which is needed
// to call into the runtime.
// `module.merge(YourRpcTrait::into_rpc(YourRpcStruct::new(ReferenceToClient, ...)))?;`
Ok(module)
}
Once everything is done, you can use the Flipper Smart Contract sample to test. Compile the Flipper contract only, it should create a WASM and a Contract file. Then upload the Contract File to your node. After uploading, you can interact with your Smart Contract through the expose RPC calls as shown below:
Use directly the above documentation rather than following the steps provided by Substrate website. The website documentation is old, outdated and does not work (as of the writing of this blog, so I am not going to post the link here).
That’s it. Have fun with your own chain. Please don’t forget to donate if your find this blog helpful.
If you are starting your own blockchain and you don’t want the complexity of a large chain, you need start with a new and controlled community which later on be converted into Parachains, a large shared chain that can connect to a relay chain in the Polkadot eco-system.
For me, starting with Proof-of-Aurthority (PoA) is the most suitable consensus mechanism for small and controlled community while having the flexibility to scale to Nominated Proof-of-Stake (nPoS).
The current PoA of Substrate using Aura and Grandpa does not incentivize the block authors nor validators, making it hard for you to grow your network because you have to pay for all servers and infrastructures on your own.
To solve this issue we need to activated the fees and rewards of the author of the blocks. In this way other people are more committed to join the network because they will be incentivize for the infrastructure without having to stake or be nominated like in a typical nPoS network.
Configure the pallet to get the current author of the block (runtime/src/lib.rs)
You need to implement the FindAuthor trait in the AuraAccountAdaptor and use it to feed the FindAuthor type enum in the pallet_authorship.
pub struct AuraAccountAdapter;
impl frame_support::traits::FindAuthor<AccountId> for AuraAccountAdapter {
fn find_author<'a, I>(digests: I) -> Option<AccountId>
where I: 'a + IntoIterator<Item=(frame_support::ConsensusEngineId, &'a [u8])>
{
pallet_aura::AuraAuthorId::<Runtime>::find_author(digests).and_then(|k| {
AccountId::try_from(k.as_ref()).ok()
})
}
}
impl pallet_authorship::Config for Runtime {
type FindAuthor = AuraAccountAdapter;
type UncleGenerations = ();
type FilterUncle = ();
type EventHandler = ();
}
Create OnUnbalanced implementation of Author and DealWithFees (runtime/src/impls.rs)
This is a separate rust (rs) file. You need to include it in the lib.rs by adding a line mod impls. I commented the Treasury share since we haven’t implemented the treasury pallet yet.
use crate::{Authorship, Balances};
use frame_support::traits::{Imbalance, OnUnbalanced};
use crate::sp_api_hidden_includes_construct_runtime::hidden_include::traits::Currency;
use crate::AccountId;
type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
pub struct Author;
impl OnUnbalanced<NegativeImbalance> for Author {
fn on_nonzero_unbalanced(amount: NegativeImbalance) {
if let Some(author) = Authorship::author() {
Balances::resolve_creating(&author, amount);
}
}
}
pub struct DealWithFees;
impl OnUnbalanced<NegativeImbalance> for DealWithFees {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {
if let Some(fees) = fees_then_tips.next() {
let mut split = fees.ration(80, 20);
if let Some(tips) = fees_then_tips.next() {
// for tips, if any, 80% to treasury, 20% to block author (though this can be anything)
tips.ration_merge_into(80, 20, &mut split);
}
//Treasury::on_unbalanced(split.0);
Author::on_unbalanced(split.1);
}
}
}
Call the implementation in the pallet_transaction_payment tuple OnChargeTransaction(runtime/src/lib.rs)
The substrate-node-template repository already has pallet_transaction_payment pallet, just replace the tupple parameter in OnChargeTransaction by calling the DealWithFees implementation.
impl pallet_transaction_payment::Config for Runtime {
type OnChargeTransaction = CurrencyAdapter<Balances, crate::impls::DealWithFees>;
type OperationalFeeMultiplier = ConstU8<5>;
type WeightToFee = IdentityFee<Balance>;
type LengthToFee = IdentityFee<Balance>;
type FeeMultiplierUpdate = ();
}
That’s it. Have fun with your own chain. Please don’t forget to donate if your find this blog helpful.