Upgrading the Runtime through Collective.

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:

  1. Navigate to polkadotjs\Developer\Extrinsic\system\setCode.
  2. Upload the Runtime Wasm file and locate the encoded call hash.
  3. 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:

  1. Go to polkadotjs\Governance\TechnicalCommittee\Proposals\SubmitAProposal.
  2. Paste the encoded call hash into the appropriate field.
  3. 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:

  1. Create and submit the second proposal. Wrapped the system\SetCode with whitelist\dispatchWhitelistedCallWithPreimage.
  2. 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.

Special thanks to https://github.com/KenSombreo and https://github.com/villenaj for the awesome work.

How to test DealWithFees?

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.

DealWithFees::<Test>::on_unbalanceds(vec![imbalance.unwrap()].into_iter());

assert_eq!(Balances::free_balance(TreasuryAccount::get()), 20);

assert_eq!(Balances::free_balance(1), 80);

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.

Manually injecting block authoring into your pallet unit test.

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);
}

Implement the AuthorGiven struct.

pub struct AuthorGiven;

static mut FIXED_AUTHOR: Option<AccountId> = None;
impl frame_support::traits::FindAuthor<AccountId> for AuthorGiven {
    fn find_author<'a, I>(_digests: I) -> Option<AccountId>
    where
        I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
    {
		unsafe {
            let author = FIXED_AUTHOR;
            author
        }
    }	
}
impl AuthorGiven {
    pub fn set_author(author: AccountId) {
        unsafe {
            FIXED_AUTHOR = Some(author);
        }
    }

    pub fn clear_author() {
        unsafe {
            FIXED_AUTHOR = None;
        }
    }
}

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.

Upgrade your Parachain Runtime

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.

$ ./target/release/parachain-node --alice --collator --force-authoring --chain parachain-chainspec.json \
--base-path /tmp/parachain-node/collator1 \
--rpc-port 30344 \
--rpc-external \
--rpc-methods Unsafe \
--rpc-cors all \
-- \
--execution wasm \
--chain rococo-local-cfde.json \
--rpc-port 30343
--rpc-external

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.

#[pallet::call_index(1)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn do_another_thing(origin: OriginFor<T>, something: u32) -> DispatchResultWithPostInfo {
 <Something<T>>::put(something);
 Self::deposit_event(Event::SomethingStored(something, who));
 Ok(().into())
}

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.

xcmPallet send(dest, message)
dest: XcmVersionedMultiLocation
{
V1: {
parents: 0
interior: {
X1: {
Parachain: 2,000
}
}
}
}
message: XcmVersionedXcm
{
V2: [
{
Transact: {
originType: Superuser
requireWeightAtMost: 1,000,000,000
call: {
encoded: 0xe52c9853e9360de916f44cd111ee6c8b4cabdc06ab269d927ca712a91da22c44
}
}
}
]
}

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.

Thats it! Keep doing Web3.

Adding pallet_contracts to Substrate Cumulus Parachain Template.

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.

pallet-randomness-collective-flip
pallet-assets
pallet-assets-chain-extension
pallet-contracts
pallet-contracts-primitives
pallet-contracts-rpc-runtime-api

Open the runtime/lib.rs and modify the construct_runtime! macro. Add the following libraries.

RandomnessCollectiveFlip: pallet_randomness_collective_flip = 50,
Contracts: pallet_contracts = 51,
Assets: pallet_assets = 52,

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:

    impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, 
        AccountId, Balance, BlockNumber, Hash> for Runtime
    {
        fn call(
            origin: AccountId,
            dest: AccountId,
            value: Balance,
            gas_limit: u64,
            storage_deposit_limit: Option<Balance>,
            input_data: Vec<u8>,
            ) -> pallet_contracts_primitives::ContractExecResult<Balance> 
        {
                Contracts::bare_call(origin, dest, value, 
                                     Weight::from_ref_time(gas_limit), 
                                     storage_deposit_limit, input_data, 
                                     CONTRACTS_DEBUG_OUTPUT)
        }

        fn instantiate(
            origin: AccountId,
            value: Balance,
            gas_limit: u64,
            storage_deposit_limit: Option<Balance>,
	    code: pallet_contracts_primitives::Code<Hash>,
            data: Vec<u8>,
            salt: Vec<u8>,
            ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, Balance>
        {
                Contracts::bare_instantiate(origin, value,  
                                            Weight::from_ref_time(gas_limit), 
                                            storage_deposit_limit, code, data, 
                                            salt, CONTRACTS_DEBUG_OUTPUT)
        }

        fn upload_code(
            origin: AccountId,
            code: Vec<u8>,
            storage_deposit_limit: Option<Balance>,
            ) -> pallet_contracts_primitives::CodeUploadResult<Hash, Balance>
        {
                Contracts::bare_upload_code(origin, code, storage_deposit_limit)
        }

        fn get_storage(
            address: AccountId,
            key: Vec<u8>,
            ) -> pallet_contracts_primitives::GetStorageResult 
        {
                Contracts::get_storage(address, key)
        }
    }

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.

+ pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>

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.

Deploying and executing Web3 Smart Contracts in Polygon using Node.js and Web3.js

The ability to have premissionless transistion functions through smart contracts makes blockchain special. These are two most commonly used smart contracts:

  1. Tokens (ERC20) – Used mainly as cryptocurrency.
  2. Non-fungible Tokens (ERC721) – Everyone knows NFT.

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 Polygon here.

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.

$ mkdir web3
$ cd web3
$ npm install web3
$ npm install dotenv --save 

It is expected that we already installed Node.js and NPM, if not we follow these steps.

Make an environment file (.env) and put all the addresses, private keys and urls needed for the code.

TESTNET=https://rpc-mumbai.maticvigil.com/
ADDRESS1=0xbCBA4xxxxxxxxxxxx2bxxxxxx
ADDRESS1_PRIVATE_KEY=8c5305axxxxxxx8e80xxx03xxxxxx
ADDRESS2=0x52Ec00xxxxxxxxxxxxx2aB162Fc8xxxxxxxxx
TOKEN_CONTRACT=0xadxxxxxxxxx37818a9xxxxxxxxxx
NFT_CONTRACT=0x542e8xxxxxxxxxxx1842344xxxxxxxxxx

STEP 4: Code

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.

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 walletAddressPrivateKey = process.env.ADDRESS1_PRIVATE_KEY;
    const tokenContract = process.env.TOKEN_CONTRACT;

    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, tokenContract);
    const nonce = await web3.eth.getTransactionCount(walletAddress, "latest");
    const transaction = {
        from: walletAddress,
        to: tokenContract,
        nonce: nonce,
        gas: 500000,
        data: contract.methods.mint(100000).encodeABI(),
    };
    const signPromise = await web3.eth.accounts.signTransaction(
        transaction,
        walletAddressPrivateKey
    );
    const signedTransaction = await web3.eth.sendSignedTransaction(
        signPromise["rawTransaction"]
    );
    const hash = signedTransaction["transactionHash"];
    console.log(hash);
}

main().catch(console.error).finally(() => process.exit());

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.

require('dotenv').config();

const fs = require('fs');
const Web3 = require('web3');

async function main() {
    const testnet = process.env.TESTNET;
    const walletAddress1 = process.env.ADDRESS1;
    const walletAddress1PrivateKey = process.env.ADDRESS1_PRIVATE_KEY;
    const walletAddress2 = process.env.ADDRESS2;
    const nftContract = process.env.NFT_CONTRACT;

    const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
    const abi = JSON.parse(fs.readFileSync("./bnft_abi.json"));
    let contract = new web3.eth.Contract(abi, nftContract);
    const nonce = await web3.eth.getTransactionCount(walletAddress1, "latest");
    const transaction = {
        from: walletAddress1,
        to: nftContract,
        nonce: nonce,
        gas: 500000,
        data: contract.methods.safeTransferFrom(walletAddress1, walletAddress2, 1).encodeABI(),
    };
    const signPromise = await web3.eth.accounts.signTransaction(
        transaction,
        walletAddress1PrivateKey
    );
    const signedTransaction = await web3.eth.sendSignedTransaction(
        signPromise["rawTransaction"]
    );
    const hash = signedTransaction["transactionHash"];
    console.log(hash);
}

main().catch(console.error).finally(() => process.exit());

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.

Sending Gmail emails using Rust

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"

Create an .env file.

NOTIFY_EMAIL=sendittome@gmail.com
SMTP=smtp.gmail.com
SMTP_EMAIL=securesally@gmail.com
SMTP_PASSWORD =iocsnoaibtpfagvx

Then the final code: src/lib.rs

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 transfer balances from one account to another in Substrate.

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>;
}

3. Add a public type BalanceOf<T>. This is used to capture the balance parameter sent by the caller. Ordinary value sent, e.g., u128, u64, etc. will yield an error. Substrate primitives must be used for calling Currency::transfer. Reference: https://paritytech.github.io/substrate/monthly-2021-09+1/pallet_balances/index.html

pub type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;

4. All needed configuration are set. Now we can create the tx method for transfer (do_transfer).

#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn do_transfer(origin: OriginFor<T>,  source: T::AccountId, amount: BalanceOf<T>) -> DispatchResult {
      let owner = ensure_signed(origin)?;
      match PalletCustomDataStore::<T>::get() {
          Some(destination) => {
              T::Currency::transfer(&source, &destination, amount, ExistenceRequirement::KeepAlive)?;
          },
          None => return Err(Error::<T>::NoneValue.into()),
      };
      Self::deposit_event(Event::ATransferWasExecuted(source));
      Ok(())
}

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.

Hack the substrade-node-template to add support to WASM Smart Contracts?

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.

Runtime Modification (runtime/)

  • Install the dependencies (runtime/Cargo.toml)
pallet-contracts = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.23", default-features = false }
pallet-contracts-primitives = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.23", default-features = false }
pallet-contracts-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.23", default-features = false }
	"pallet-contracts/std",
	"pallet-contracts-primitives/std",
	"pallet-contracts-rpc-runtime-api/std",
  • Define the constants (runtime/src/lib.rs)
pub const TOKEN_DECIMALS: u32 = 12;
pub const TOKEN: u128 = 10u128.pow(TOKEN_DECIMALS);
pub const DEPOSIT_PER_BYTE: Balance = TOKEN / 1000;
pub const CONTRACTS_DEBUG_OUTPUT: bool = true;
  • Configure pallet_contracts (runtime/src/lib.rs)
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)
	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash> for Runtime {

        fn call(
            origin: AccountId,
            dest: AccountId,
            value: Balance,
            gas_limit: u64,
            storage_deposit_limit: Option<Balance>,
            input_data: Vec<u8>,
        ) -> pallet_contracts_primitives::ContractExecResult<Balance> {
            Contracts::bare_call(origin, dest, value, gas_limit, storage_deposit_limit, input_data, CONTRACTS_DEBUG_OUTPUT)
        }

        fn instantiate(
            origin: AccountId,
            value: Balance,
            gas_limit: u64,
            storage_deposit_limit: Option<Balance>,
            code: pallet_contracts_primitives::Code<Hash>,
            data: Vec<u8>,
            salt: Vec<u8>,
        ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, Balance>
        {
            Contracts::bare_instantiate(origin, value, gas_limit, storage_deposit_limit, code, data, salt, CONTRACTS_DEBUG_OUTPUT)
        }

        fn upload_code(
            origin: AccountId,
            code: Vec<u8>,
            storage_deposit_limit: Option<Balance>,
        ) -> pallet_contracts_primitives::CodeUploadResult<Hash, Balance>
        {
            Contracts::bare_upload_code(origin, code, storage_deposit_limit)
        }

        fn get_storage(
            address: AccountId,
            key: [u8; 32],
        ) -> pallet_contracts_primitives::GetStorageResult {
            Contracts::get_storage(address, key)
        }

    }

Node Modification (node/)

  1. Install dependencies (node/Cargo.toml)
pallet-contracts = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.23", default-features = false }
pallet-contracts-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.23", default-features = false }
  1. 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:

For the complete information about the pallet_contracts traits refer to the Rust documentation: https://docs.rs/pallet-contracts/2.0.1/pallet_contracts/trait.Trait.html

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.

How to pay the block author/validator on a Proof-of-Authority (PoA) consensus in Substrate.

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.

Here is how we do it:

Install pallet_authorship (runtime/Cargo.toml)

pallet-authorship = { version = "4.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.23" }

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.